Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1015
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1015 ! raeburn 4: # $Id: lonnet.pm,v 1.1014 2009/08/11 11:33:52 droeschl Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968 raeburn 79: $_64bit %env %protocol);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.807 albertel 95: use LONCAPA qw(:DEFAULT :match);
1.740 www 96: use LONCAPA::Configuration;
1.676 albertel 97:
1.195 www 98: my $readit;
1.550 foxr 99: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 100:
1.977 amueller 101: my $upload_photo_form = 0; #Variable to check when user upload a photo 0=not 1=true
102:
1.619 albertel 103: require Exporter;
104:
105: our @ISA = qw (Exporter);
106: our @EXPORT = qw(%env);
107:
1.449 matthew 108:
1.1 albertel 109: # --------------------------------------------------------------------- Logging
1.729 www 110: {
111: my $logid;
112: sub instructor_log {
1.957 raeburn 113: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
114: if (($cnum eq '') || ($cdom eq '')) {
115: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
116: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
117: }
1.729 www 118: $logid++;
1.957 raeburn 119: my $now = time();
120: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 121: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 122: { $id => {
123: 'exe_uname' => $env{'user.name'},
124: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 125: 'exe_time' => $now,
1.730 www 126: 'exe_ip' => $ENV{'REMOTE_ADDR'},
127: 'delflag' => $delflag,
128: 'logentry' => $storehash,
129: 'uname' => $uname,
130: 'udom' => $udom,
131: }
1.957 raeburn 132: },$cdom,$cnum);
1.729 www 133: }
134: }
1.1 albertel 135:
1.163 harris41 136: sub logtouch {
137: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 138: unless (-e "$execdir/logs/lonnet.log") {
139: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 140: close $fh;
141: }
142: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
143: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
144: }
145:
1.1 albertel 146: sub logthis {
147: my $message=shift;
148: my $execdir=$perlvar{'lonDaemons'};
149: my $now=time;
150: my $local=localtime($now);
1.448 albertel 151: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 152: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
153: print $fh $logstring;
1.448 albertel 154: close($fh);
155: }
1.1 albertel 156: return 1;
157: }
158:
159: sub logperm {
160: my $message=shift;
161: my $execdir=$perlvar{'lonDaemons'};
162: my $now=time;
163: my $local=localtime($now);
1.448 albertel 164: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
165: print $fh "$now:$message:$local\n";
166: close($fh);
167: }
1.1 albertel 168: return 1;
169: }
170:
1.850 albertel 171: sub create_connection {
1.853 albertel 172: my ($hostname,$lonid) = @_;
1.851 albertel 173: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 174: Type => SOCK_STREAM,
175: Timeout => 10);
176: return 0 if (!$client);
1.890 albertel 177: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 178: my $result = <$client>;
179: chomp($result);
180: return 1 if ($result eq 'done');
181: return 0;
182: }
183:
1.983 raeburn 184: sub get_server_timezone {
185: my ($cnum,$cdom) = @_;
186: my $home=&homeserver($cnum,$cdom);
187: if ($home ne 'no_host') {
188: my $cachetime = 24*3600;
189: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
190: if (defined($cached)) {
191: return $timezone;
192: } else {
193: my $timezone = &reply('servertimezone',$home);
194: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
195: }
196: }
197: }
1.850 albertel 198:
1.993 raeburn 199: sub get_server_loncaparev {
200: my ($dom,$lonhost) = @_;
201: if (defined($lonhost)) {
202: if (!defined(&hostname($lonhost))) {
203: undef($lonhost);
204: }
205: }
206: if (!defined($lonhost)) {
207: if (defined(&domain($dom,'primary'))) {
208: $lonhost=&domain($dom,'primary');
209: if ($lonhost eq 'no_host') {
210: undef($lonhost);
211: }
212: }
213: }
214: if (defined($lonhost)) {
215: my $cachetime = 24*3600;
216: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
217: if (defined($cached)) {
218: return $loncaparev;
219: } else {
220: my $loncaparev = &reply('serverloncaparev',$lonhost);
221: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
222: }
223: }
224: }
225:
1.1 albertel 226: # -------------------------------------------------- Non-critical communication
227: sub subreply {
228: my ($cmd,$server)=@_;
1.838 albertel 229: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 230: #
231: # With loncnew process trimming, there's a timing hole between lonc server
232: # process exit and the master server picking up the listen on the AF_UNIX
233: # socket. In that time interval, a lock file will exist:
234:
235: my $lockfile=$peerfile.".lock";
236: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
237: sleep(1);
238: }
239: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 240: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 241: #
1.550 foxr 242: # We'll give the connection a few tries before abandoning it. If
243: # connection is not possible, we'll con_lost back to the client.
244: #
245: my $client;
246: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
247: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
248: Type => SOCK_STREAM,
249: Timeout => 10);
1.869 albertel 250: if ($client) {
1.550 foxr 251: last; # Connected!
1.850 albertel 252: } else {
1.853 albertel 253: &create_connection(&hostname($server),$server);
1.550 foxr 254: }
1.850 albertel 255: sleep(1); # Try again later if failed connection.
1.550 foxr 256: }
257: my $answer;
258: if ($client) {
1.704 albertel 259: print $client "sethost:$server:$cmd\n";
1.550 foxr 260: $answer=<$client>;
261: if (!$answer) { $answer="con_lost"; }
262: chomp($answer);
263: } else {
264: $answer = 'con_lost'; # Failed connection.
265: }
1.1 albertel 266: return $answer;
267: }
268:
269: sub reply {
270: my ($cmd,$server)=@_;
1.838 albertel 271: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 272: my $answer=subreply($cmd,$server);
1.65 www 273: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 274: &logthis("<font color=\"blue\">WARNING:".
1.12 www 275: " $cmd to $server returned $answer</font>");
276: }
1.1 albertel 277: return $answer;
278: }
279:
280: # ----------------------------------------------------------- Send USR1 to lonc
281:
282: sub reconlonc {
1.891 albertel 283: my ($lonid) = @_;
284: my $hostname = &hostname($lonid);
285: if ($lonid) {
286: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
287: if ($hostname && -e $peerfile) {
288: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
289: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
290: Type => SOCK_STREAM,
291: Timeout => 10);
292: if ($client) {
293: print $client ("reset_retries\n");
294: my $answer=<$client>;
295: #reset just this one.
296: }
297: }
298: return;
299: }
300:
1.836 www 301: &logthis("Trying to reconnect lonc");
1.1 albertel 302: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 303: if (open(my $fh,"<$loncfile")) {
1.1 albertel 304: my $loncpid=<$fh>;
305: chomp($loncpid);
306: if (kill 0 => $loncpid) {
307: &logthis("lonc at pid $loncpid responding, sending USR1");
308: kill USR1 => $loncpid;
309: sleep 1;
1.836 www 310: } else {
1.12 www 311: &logthis(
1.672 albertel 312: "<font color=\"blue\">WARNING:".
1.12 www 313: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 314: }
315: } else {
1.836 www 316: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 317: }
318: }
319:
320: # ------------------------------------------------------ Critical communication
1.12 www 321:
1.1 albertel 322: sub critical {
323: my ($cmd,$server)=@_;
1.838 albertel 324: unless (&hostname($server)) {
1.672 albertel 325: &logthis("<font color=\"blue\">WARNING:".
1.89 www 326: " Critical message to unknown server ($server)</font>");
327: return 'no_such_host';
328: }
1.1 albertel 329: my $answer=reply($cmd,$server);
330: if ($answer eq 'con_lost') {
331: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 332: my $answer=reply($cmd,$server);
1.1 albertel 333: if ($answer eq 'con_lost') {
334: my $now=time;
335: my $middlename=$cmd;
1.5 www 336: $middlename=substr($middlename,0,16);
1.1 albertel 337: $middlename=~s/\W//g;
338: my $dfilename=
1.305 www 339: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
340: $dumpcount++;
1.1 albertel 341: {
1.448 albertel 342: my $dfh;
343: if (open($dfh,">$dfilename")) {
344: print $dfh "$cmd\n";
345: close($dfh);
346: }
1.1 albertel 347: }
348: sleep 2;
349: my $wcmd='';
350: {
1.448 albertel 351: my $dfh;
352: if (open($dfh,"<$dfilename")) {
353: $wcmd=<$dfh>;
354: close($dfh);
355: }
1.1 albertel 356: }
357: chomp($wcmd);
1.7 www 358: if ($wcmd eq $cmd) {
1.672 albertel 359: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 360: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 361: &logperm("D:$server:$cmd");
362: return 'con_delayed';
363: } else {
1.672 albertel 364: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 365: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 366: &logperm("F:$server:$cmd");
367: return 'con_failed';
368: }
369: }
370: }
371: return $answer;
1.405 albertel 372: }
373:
1.755 albertel 374: # ------------------------------------------- check if return value is an error
375:
376: sub error {
377: my ($result) = @_;
1.756 albertel 378: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 379: if ($2 == 2) { return undef; }
380: return $1;
381: }
382: return undef;
383: }
384:
1.783 albertel 385: sub convert_and_load_session_env {
386: my ($lonidsdir,$handle)=@_;
387: my @profile;
388: {
1.917 albertel 389: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
390: if (!$opened) {
1.915 albertel 391: return 0;
392: }
1.783 albertel 393: flock($idf,LOCK_SH);
394: @profile=<$idf>;
395: close($idf);
396: }
397: my %temp_env;
398: foreach my $line (@profile) {
1.786 albertel 399: if ($line !~ m/=/) {
400: return 0;
401: }
1.783 albertel 402: chomp($line);
403: my ($envname,$envvalue)=split(/=/,$line,2);
404: $temp_env{&unescape($envname)} = &unescape($envvalue);
405: }
406: unlink("$lonidsdir/$handle.id");
407: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
408: 0640)) {
409: %disk_env = %temp_env;
410: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
411: untie(%disk_env);
412: }
1.786 albertel 413: return 1;
1.783 albertel 414: }
415:
1.374 www 416: # ------------------------------------------- Transfer profile into environment
1.780 albertel 417: my $env_loaded;
418: sub transfer_profile_to_env {
1.788 albertel 419: my ($lonidsdir,$handle,$force_transfer) = @_;
420: if (!$force_transfer && $env_loaded) { return; }
1.374 www 421:
1.720 albertel 422: if (!defined($lonidsdir)) {
423: $lonidsdir = $perlvar{'lonIDsDir'};
424: }
425: if (!defined($handle)) {
426: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
427: }
428:
1.786 albertel 429: my $convert;
430: {
1.917 albertel 431: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
432: if (!$opened) {
1.915 albertel 433: return;
434: }
1.786 albertel 435: flock($idf,LOCK_SH);
436: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
437: &GDBM_READER(),0640)) {
438: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
439: untie(%disk_env);
440: } else {
441: $convert = 1;
442: }
443: }
444: if ($convert) {
445: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
446: &logthis("Failed to load session, or convert session.");
447: }
1.374 www 448: }
1.783 albertel 449:
1.786 albertel 450: my %remove;
1.783 albertel 451: while ( my $envname = each(%env) ) {
1.433 matthew 452: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
453: if ($time < time-300) {
1.783 albertel 454: $remove{$key}++;
1.433 matthew 455: }
456: }
457: }
1.783 albertel 458:
1.619 albertel 459: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 460: $env_loaded=1;
1.783 albertel 461: foreach my $expired_key (keys(%remove)) {
1.433 matthew 462: &delenv($expired_key);
1.374 www 463: }
1.1 albertel 464: }
465:
1.916 albertel 466: # ---------------------------------------------------- Check for valid session
467: sub check_for_valid_session {
468: my ($r) = @_;
469: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
470: my $lonid=$cookies{'lonID'};
471: return undef if (!$lonid);
472:
473: my $handle=&LONCAPA::clean_handle($lonid->value);
474: my $lonidsdir=$r->dir_config('lonIDsDir');
475: return undef if (!-e "$lonidsdir/$handle.id");
476:
1.917 albertel 477: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
478: return undef if (!$opened);
1.916 albertel 479:
480: flock($idf,LOCK_SH);
481: my %disk_env;
482: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
483: &GDBM_READER(),0640)) {
484: return undef;
485: }
486:
487: if (!defined($disk_env{'user.name'})
488: || !defined($disk_env{'user.domain'})) {
489: return undef;
490: }
491: return $handle;
492: }
493:
1.830 albertel 494: sub timed_flock {
495: my ($file,$lock_type) = @_;
496: my $failed=0;
497: eval {
498: local $SIG{__DIE__}='DEFAULT';
499: local $SIG{ALRM}=sub {
500: $failed=1;
501: die("failed lock");
502: };
503: alarm(13);
504: flock($file,$lock_type);
505: alarm(0);
506: };
507: if ($failed) {
508: return undef;
509: } else {
510: return 1;
511: }
512: }
513:
1.5 www 514: # ---------------------------------------------------------- Append Environment
515:
516: sub appenv {
1.949 raeburn 517: my ($newenv,$roles) = @_;
518: if (ref($newenv) eq 'HASH') {
519: foreach my $key (keys(%{$newenv})) {
520: my $refused = 0;
521: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
522: $refused = 1;
523: if (ref($roles) eq 'ARRAY') {
524: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
525: if (grep(/^\Q$role\E$/,@{$roles})) {
526: $refused = 0;
527: }
528: }
529: }
530: if ($refused) {
531: &logthis("<font color=\"blue\">WARNING: ".
532: "Attempt to modify environment ".$key." to ".$newenv->{$key}
533: .'</font>');
534: delete($newenv->{$key});
535: } else {
536: $env{$key}=$newenv->{$key};
537: }
538: }
539: my $opened = open(my $env_file,'+<',$env{'user.environment'});
540: if ($opened
541: && &timed_flock($env_file,LOCK_EX)
542: &&
543: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
544: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
545: while (my ($key,$value) = each(%{$newenv})) {
546: $disk_env{$key} = $value;
547: }
548: untie(%disk_env);
1.35 www 549: }
1.191 harris41 550: }
1.56 www 551: return 'ok';
552: }
553: # ----------------------------------------------------- Delete from Environment
554:
555: sub delenv {
1.987 raeburn 556: my ($delthis,$regexp) = @_;
1.56 www 557: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 558: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 559: "Attempt to delete from environment ".$delthis);
560: return 'error';
561: }
1.917 albertel 562: my $opened = open(my $env_file,'+<',$env{'user.environment'});
563: if ($opened
1.915 albertel 564: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 565: &&
566: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
567: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 568: foreach my $key (keys(%disk_env)) {
1.987 raeburn 569: if ($regexp) {
570: if ($key=~/^$delthis/) {
571: delete($env{$key});
572: delete($disk_env{$key});
573: }
574: } else {
575: if ($key=~/^\Q$delthis\E/) {
576: delete($env{$key});
577: delete($disk_env{$key});
578: }
579: }
1.448 albertel 580: }
1.783 albertel 581: untie(%disk_env);
1.5 www 582: }
583: return 'ok';
1.369 albertel 584: }
585:
1.790 albertel 586: sub get_env_multiple {
587: my ($name) = @_;
588: my @values;
589: if (defined($env{$name})) {
590: # exists is it an array
591: if (ref($env{$name})) {
592: @values=@{ $env{$name} };
593: } else {
594: $values[0]=$env{$name};
595: }
596: }
597: return(@values);
598: }
599:
1.958 www 600: # ------------------------------------------------------------------- Locking
601:
602: sub set_lock {
603: my ($text)=@_;
604: $locknum++;
605: my $id=$$.'-'.$locknum;
606: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
607: 'session.lock.'.$id => $text});
608: return $id;
609: }
610:
611: sub get_locks {
612: my $num=0;
613: my %texts=();
614: foreach my $lock (split(/\,/,$env{'session.locks'})) {
615: if ($lock=~/\w/) {
616: $num++;
617: $texts{$lock}=$env{'session.lock.'.$lock};
618: }
619: }
620: return ($num,%texts);
621: }
622:
623: sub remove_lock {
624: my ($id)=@_;
625: my $newlocks='';
626: foreach my $lock (split(/\,/,$env{'session.locks'})) {
627: if (($lock=~/\w/) && ($lock ne $id)) {
628: $newlocks.=','.$lock;
629: }
630: }
631: &appenv({'session.locks' => $newlocks});
632: &delenv('session.lock.'.$id);
633: }
634:
635: sub remove_all_locks {
636: my $activelocks=$env{'session.locks'};
637: foreach my $lock (split(/\,/,$env{'session.locks'})) {
638: if ($lock=~/\w/) {
639: &remove_lock($lock);
640: }
641: }
642: }
643:
644:
1.369 albertel 645: # ------------------------------------------ Find out current server userload
646: sub userload {
647: my $numusers=0;
648: {
649: opendir(LONIDS,$perlvar{'lonIDsDir'});
650: my $filename;
651: my $curtime=time;
652: while ($filename=readdir(LONIDS)) {
1.925 albertel 653: next if ($filename eq '.' || $filename eq '..');
654: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 655: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 656: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 657: }
658: closedir(LONIDS);
659: }
660: my $userloadpercent=0;
661: my $maxuserload=$perlvar{'lonUserLoadLim'};
662: if ($maxuserload) {
1.371 albertel 663: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 664: }
1.372 albertel 665: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 666: return $userloadpercent;
1.283 www 667: }
668:
669: # ------------------------------------------ Fight off request when overloaded
670:
671: sub overloaderror {
672: my ($r,$checkserver)=@_;
673: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
674: my $loadavg;
675: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 676: open(my $loadfile,'/proc/loadavg');
1.283 www 677: $loadavg=<$loadfile>;
678: $loadavg =~ s/\s.*//g;
1.285 matthew 679: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 680: close($loadfile);
1.283 www 681: } else {
682: $loadavg=&reply('load',$checkserver);
683: }
1.285 matthew 684: my $overload=$loadavg-100;
1.283 www 685: if ($overload>0) {
1.285 matthew 686: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 687: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 688: return 413;
1.283 www 689: }
690: return '';
1.5 www 691: }
1.1 albertel 692:
693: # ------------------------------ Find server with least workload from spare.tab
1.11 www 694:
1.1 albertel 695: sub spareserver {
1.670 albertel 696: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 697: my $spare_server;
1.370 albertel 698: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 699: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
700: : $userloadpercent;
701:
702: foreach my $try_server (@{ $spareid{'primary'} }) {
703: ($spare_server, $lowest_load) =
704: &compare_server_load($try_server, $spare_server, $lowest_load);
705: }
706:
707: my $found_server = ($spare_server ne '' && $lowest_load < 100);
708:
709: if (!$found_server) {
710: foreach my $try_server (@{ $spareid{'default'} }) {
711: ($spare_server, $lowest_load) =
712: &compare_server_load($try_server, $spare_server, $lowest_load);
713: }
714: }
715:
716: if (!$want_server_name) {
1.968 raeburn 717: my $protocol = 'http';
718: if ($protocol{$spare_server} eq 'https') {
719: $protocol = $protocol{$spare_server};
720: }
1.1001 raeburn 721: if (defined($spare_server)) {
722: my $hostname = &hostname($spare_server);
723: if (defined($hostname)) {
724: $spare_server = $protocol.'://'.$hostname;
725: }
726: }
1.784 albertel 727: }
728: return $spare_server;
729: }
730:
731: sub compare_server_load {
732: my ($try_server, $spare_server, $lowest_load) = @_;
733:
734: my $loadans = &reply('load', $try_server);
735: my $userloadans = &reply('userload',$try_server);
736:
737: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
738: next; #didn't get a number from the server
739: }
740:
741: my $load;
742: if ($loadans =~ /\d/) {
743: if ($userloadans =~ /\d/) {
744: #both are numbers, pick the bigger one
745: $load = ($loadans > $userloadans) ? $loadans
746: : $userloadans;
1.411 albertel 747: } else {
1.784 albertel 748: $load = $loadans;
1.411 albertel 749: }
1.784 albertel 750: } else {
751: $load = $userloadans;
752: }
753:
754: if (($load =~ /\d/) && ($load < $lowest_load)) {
755: $spare_server = $try_server;
756: $lowest_load = $load;
1.370 albertel 757: }
1.784 albertel 758: return ($spare_server,$lowest_load);
1.202 matthew 759: }
1.914 albertel 760:
761: # --------------------------- ask offload servers if user already has a session
762: sub find_existing_session {
763: my ($udom,$uname) = @_;
764: foreach my $try_server (@{ $spareid{'primary'} },
765: @{ $spareid{'default'} }) {
766: return $try_server if (&has_user_session($try_server, $udom, $uname));
767: }
768: return;
769: }
770:
771: # -------------------------------- ask if server already has a session for user
772: sub has_user_session {
773: my ($lonid,$udom,$uname) = @_;
774: my $result = &reply(join(':','userhassession',
775: map {&escape($_)} ($udom,$uname)),$lonid);
776: return 1 if ($result eq 'ok');
777:
778: return 0;
779: }
780:
1.202 matthew 781: # --------------------------------------------- Try to change a user's password
782:
783: sub changepass {
1.799 raeburn 784: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 785: $currentpass = &escape($currentpass);
786: $newpass = &escape($newpass);
1.799 raeburn 787: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 788: $server);
789: if (! $answer) {
790: &logthis("No reply on password change request to $server ".
791: "by $uname in domain $udom.");
792: } elsif ($answer =~ "^ok") {
793: &logthis("$uname in $udom successfully changed their password ".
794: "on $server.");
795: } elsif ($answer =~ "^pwchange_failure") {
796: &logthis("$uname in $udom was unable to change their password ".
797: "on $server. The action was blocked by either lcpasswd ".
798: "or pwchange");
799: } elsif ($answer =~ "^non_authorized") {
800: &logthis("$uname in $udom did not get their password correct when ".
801: "attempting to change it on $server.");
802: } elsif ($answer =~ "^auth_mode_error") {
803: &logthis("$uname in $udom attempted to change their password despite ".
804: "not being locally or internally authenticated on $server.");
805: } elsif ($answer =~ "^unknown_user") {
806: &logthis("$uname in $udom attempted to change their password ".
807: "on $server but were unable to because $server is not ".
808: "their home server.");
809: } elsif ($answer =~ "^refused") {
810: &logthis("$server refused to change $uname in $udom password because ".
811: "it was sent an unencrypted request to change the password.");
812: }
813: return $answer;
1.1 albertel 814: }
815:
1.169 harris41 816: # ----------------------- Try to determine user's current authentication scheme
817:
818: sub queryauthenticate {
819: my ($uname,$udom)=@_;
1.456 albertel 820: my $uhome=&homeserver($uname,$udom);
821: if (!$uhome) {
822: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
823: return 'no_host';
824: }
825: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
826: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
827: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 828: }
1.456 albertel 829: return $answer;
1.169 harris41 830: }
831:
1.1 albertel 832: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 833:
1.1 albertel 834: sub authenticate {
1.952 raeburn 835: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 836: $upass=&escape($upass);
837: $uname= &LONCAPA::clean_username($uname);
1.836 www 838: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 839: my $newhome;
1.836 www 840: if ((!$uhome) || ($uhome eq 'no_host')) {
841: # Maybe the machine was offline and only re-appeared again recently?
842: &reconlonc();
843: # One more
1.952 raeburn 844: $uhome=&homeserver($uname,$udom,1);
845: if (($uhome eq 'no_host') && $checkdefauth) {
846: if (defined(&domain($udom,'primary'))) {
847: $newhome=&domain($udom,'primary');
848: }
849: if ($newhome ne '') {
850: $uhome = $newhome;
851: }
852: }
1.836 www 853: if ((!$uhome) || ($uhome eq 'no_host')) {
854: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 855: return 'no_host';
856: }
1.1 albertel 857: }
1.952 raeburn 858: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 859: if ($answer eq 'authorized') {
1.952 raeburn 860: if ($newhome) {
861: &logthis("User $uname at $udom authorized by $uhome, but needs account");
862: return 'no_account_on_host';
863: } else {
864: &logthis("User $uname at $udom authorized by $uhome");
865: return $uhome;
866: }
1.471 albertel 867: }
868: if ($answer eq 'non_authorized') {
869: &logthis("User $uname at $udom rejected by $uhome");
870: return 'no_host';
1.9 www 871: }
1.471 albertel 872: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 873: return 'no_host';
874: }
875:
876: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 877:
1.599 albertel 878: my %homecache;
1.1 albertel 879: sub homeserver {
1.230 stredwic 880: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 881: my $index="$uname:$udom";
1.426 albertel 882:
1.599 albertel 883: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 884:
885: my %servers = &get_servers($udom,'library');
886: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 887: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 888: exists($badServerCache{$tryserver}));
1.841 albertel 889:
890: my $answer=reply("home:$udom:$uname",$tryserver);
891: if ($answer eq 'found') {
892: delete($badServerCache{$tryserver});
893: return $homecache{$index}=$tryserver;
894: } elsif ($answer eq 'no_host') {
895: $badServerCache{$tryserver}=1;
896: }
1.1 albertel 897: }
898: return 'no_host';
1.70 www 899: }
900:
901: # ------------------------------------- Find the usernames behind a list of IDs
902:
903: sub idget {
904: my ($udom,@ids)=@_;
905: my %returnhash=();
906:
1.841 albertel 907: my %servers = &get_servers($udom,'library');
908: foreach my $tryserver (keys(%servers)) {
909: my $idlist=join('&',@ids);
910: $idlist=~tr/A-Z/a-z/;
911: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
912: my @answer=();
913: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
914: @answer=split(/\&/,$reply);
915: } ;
916: my $i;
917: for ($i=0;$i<=$#ids;$i++) {
918: if ($answer[$i]) {
919: $returnhash{$ids[$i]}=$answer[$i];
920: }
921: }
922: }
1.70 www 923: return %returnhash;
924: }
925:
926: # ------------------------------------- Find the IDs behind a list of usernames
927:
928: sub idrget {
929: my ($udom,@unames)=@_;
930: my %returnhash=();
1.800 albertel 931: foreach my $uname (@unames) {
932: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 933: }
1.70 www 934: return %returnhash;
935: }
936:
937: # ------------------------------- Store away a list of names and associated IDs
938:
939: sub idput {
940: my ($udom,%ids)=@_;
941: my %servers=();
1.800 albertel 942: foreach my $uname (keys(%ids)) {
943: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
944: my $uhom=&homeserver($uname,$udom);
1.70 www 945: if ($uhom ne 'no_host') {
1.800 albertel 946: my $id=&escape($ids{$uname});
1.70 www 947: $id=~tr/A-Z/a-z/;
1.800 albertel 948: my $esc_unam=&escape($uname);
1.70 www 949: if ($servers{$uhom}) {
1.800 albertel 950: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 951: } else {
1.800 albertel 952: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 953: }
954: }
1.191 harris41 955: }
1.800 albertel 956: foreach my $server (keys(%servers)) {
957: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 958: }
1.344 www 959: }
960:
1.1012 raeburn 961: # ------------------------------------------------ dump from domain db files
962:
963: sub dump_dom {
964: my ($namespace,$udom,$uhome,$regexp,$range)=@_;
965: if (!$udom) {
966: $udom=$env{'user.domain'};
967: if (defined(&domain($udom,'primary'))) {
968: $uhome=&domain($udom,'primary');
969: } else {
970: undef($uhome);
971: }
972: } else {
973: if (!$uhome) {
974: if (defined(&domain($udom,'primary'))) {
975: $uhome=&domain($udom,'primary');
976: }
977: }
978: }
979: my %returnhash;
980: if ($udom && $uhome && ($uhome ne 'no_host')) {
981: if ($regexp) {
982: $regexp=&escape($regexp);
983: } else {
984: $regexp='.';
985: }
986: my $rep=&reply("dumpdom:$udom:$namespace:$regexp:$range",$uhome);
987: my @pairs=split(/\&/,$rep);
988: foreach my $item (@pairs) {
989: my ($key,$value)=split(/=/,$item,2);
990: $key = &unescape($key);
991: next if ($key =~ /^error: 2 /);
992: $returnhash{$key}=&thaw_unescape($value);
993: }
994: }
995: return %returnhash;
996: }
997:
1.806 raeburn 998: # ------------------------------------------- get items from domain db files
999:
1000: sub get_dom {
1.860 raeburn 1001: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1002: my $items='';
1003: foreach my $item (@$storearr) {
1004: $items.=&escape($item).'&';
1005: }
1006: $items=~s/\&$//;
1.860 raeburn 1007: if (!$udom) {
1008: $udom=$env{'user.domain'};
1009: if (defined(&domain($udom,'primary'))) {
1010: $uhome=&domain($udom,'primary');
1011: } else {
1.874 albertel 1012: undef($uhome);
1.860 raeburn 1013: }
1014: } else {
1015: if (!$uhome) {
1016: if (defined(&domain($udom,'primary'))) {
1017: $uhome=&domain($udom,'primary');
1018: }
1019: }
1020: }
1021: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1022: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1023: my %returnhash;
1.875 albertel 1024: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1025: return %returnhash;
1026: }
1.806 raeburn 1027: my @pairs=split(/\&/,$rep);
1028: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1029: return @pairs;
1030: }
1031: my $i=0;
1032: foreach my $item (@$storearr) {
1033: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1034: $i++;
1035: }
1036: return %returnhash;
1037: } else {
1.880 banghart 1038: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1039: }
1040: }
1041:
1042: # -------------------------------------------- put items in domain db files
1043:
1044: sub put_dom {
1.860 raeburn 1045: my ($namespace,$storehash,$udom,$uhome)=@_;
1046: if (!$udom) {
1047: $udom=$env{'user.domain'};
1048: if (defined(&domain($udom,'primary'))) {
1049: $uhome=&domain($udom,'primary');
1050: } else {
1.874 albertel 1051: undef($uhome);
1.860 raeburn 1052: }
1053: } else {
1054: if (!$uhome) {
1055: if (defined(&domain($udom,'primary'))) {
1056: $uhome=&domain($udom,'primary');
1057: }
1058: }
1059: }
1060: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1061: my $items='';
1062: foreach my $item (keys(%$storehash)) {
1063: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1064: }
1065: $items=~s/\&$//;
1066: return &reply("putdom:$udom:$namespace:$items",$uhome);
1067: } else {
1.860 raeburn 1068: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1069: }
1070: }
1071:
1.1012 raeburn 1072: # -------------------------------------- newput for items in domain db files
1073:
1074: sub newput_dom {
1075: my ($namespace,$storehash,$udom,$uhome) = @_;
1076: my $result;
1077: if (!$udom) {
1078: $udom=$env{'user.domain'};
1079: if (defined(&domain($udom,'primary'))) {
1080: $uhome=&domain($udom,'primary');
1081: } else {
1082: undef($uhome);
1083: }
1084: } else {
1085: if (!$uhome) {
1086: if (defined(&domain($udom,'primary'))) {
1087: $uhome=&domain($udom,'primary');
1088: }
1089: }
1090: }
1091: if ($udom && $uhome && ($uhome ne 'no_host')) {
1092: my $items='';
1093: if (ref($storehash) eq 'HASH') {
1094: foreach my $key (keys(%$storehash)) {
1095: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1096: }
1097: $items=~s/\&$//;
1098: $result = &reply("newputdom:$udom:$namespace:$items",$uhome);
1099: }
1100: } else {
1101: &logthis("put_dom failed - no homeserver and/or domain");
1102: }
1103: return $result;
1104: }
1105:
1106: sub del_dom {
1107: my ($namespace,$storearr,$udom,$uhome)=@_;
1108: if (ref($storearr) eq 'ARRAY') {
1109: my $items='';
1110: foreach my $item (@$storearr) {
1111: $items.=&escape($item).'&';
1112: }
1113: $items=~s/\&$//;
1114: if (!$udom) {
1115: $udom=$env{'user.domain'};
1116: if (defined(&domain($udom,'primary'))) {
1117: $uhome=&domain($udom,'primary');
1118: } else {
1119: undef($uhome);
1120: }
1121: } else {
1122: if (!$uhome) {
1123: if (defined(&domain($udom,'primary'))) {
1124: $uhome=&domain($udom,'primary');
1125: }
1126: }
1127: }
1128: if ($udom && $uhome && ($uhome ne 'no_host')) {
1129: return &reply("deldom:$udom:$namespace:$items",$uhome);
1130: } else {
1131: &logthis("del_dom failed - no homeserver and/or domain");
1132: }
1133: }
1134: }
1135:
1.837 raeburn 1136: sub retrieve_inst_usertypes {
1137: my ($udom) = @_;
1138: my (%returnhash,@order);
1.989 raeburn 1139: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1140: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1141: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1142: %returnhash = %{$domdefs{'inststatustypes'}};
1143: @order = @{$domdefs{'inststatusorder'}};
1144: } else {
1145: if (defined(&domain($udom,'primary'))) {
1146: my $uhome=&domain($udom,'primary');
1147: my $rep=&reply("inst_usertypes:$udom",$uhome);
1148: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1149: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1150: return (\%returnhash,\@order);
1151: }
1152: my ($hashitems,$orderitems) = split(/:/,$rep);
1153: my @pairs=split(/\&/,$hashitems);
1154: foreach my $item (@pairs) {
1155: my ($key,$value)=split(/=/,$item,2);
1156: $key = &unescape($key);
1157: next if ($key =~ /^error: 2 /);
1158: $returnhash{$key}=&thaw_unescape($value);
1159: }
1160: my @esc_order = split(/\&/,$orderitems);
1161: foreach my $item (@esc_order) {
1162: push(@order,&unescape($item));
1163: }
1164: } else {
1165: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1166: }
1167: }
1168: return (\%returnhash,\@order);
1169: }
1170:
1.868 raeburn 1171: sub is_domainimage {
1172: my ($url) = @_;
1173: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1174: if (&domain($1) ne '') {
1175: return '1';
1176: }
1177: }
1178: return;
1179: }
1180:
1.899 raeburn 1181: sub inst_directory_query {
1182: my ($srch) = @_;
1183: my $udom = $srch->{'srchdomain'};
1184: my %results;
1185: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1186: my $outcome;
1.899 raeburn 1187: if ($homeserver ne '') {
1.904 albertel 1188: my $queryid=&reply("querysend:instdirsearch:".
1189: &escape($srch->{'srchby'}).':'.
1190: &escape($srch->{'srchterm'}).':'.
1191: &escape($srch->{'srchtype'}),$homeserver);
1192: my $host=&hostname($homeserver);
1193: if ($queryid !~/^\Q$host\E\_/) {
1194: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1195: return;
1196: }
1197: my $response = &get_query_reply($queryid);
1198: my $maxtries = 5;
1199: my $tries = 1;
1200: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1201: $response = &get_query_reply($queryid);
1202: $tries ++;
1203: }
1204:
1205: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1206: if ($response eq 'unavailable') {
1207: $outcome = $response;
1208: } else {
1209: $outcome = 'ok';
1210: my @matches = split(/\n/,$response);
1211: foreach my $match (@matches) {
1212: my ($key,$value) = split(/=/,$match);
1213: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1214: }
1.899 raeburn 1215: }
1216: }
1217: }
1.909 raeburn 1218: return ($outcome,%results);
1.899 raeburn 1219: }
1220:
1221: sub usersearch {
1222: my ($srch) = @_;
1223: my $dom = $srch->{'srchdomain'};
1224: my %results;
1225: my %libserv = &all_library();
1226: my $query = 'usersearch';
1227: foreach my $tryserver (keys(%libserv)) {
1228: if (&host_domain($tryserver) eq $dom) {
1229: my $host=&hostname($tryserver);
1230: my $queryid=
1.911 raeburn 1231: &reply("querysend:".&escape($query).':'.
1232: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1233: &escape($srch->{'srchtype'}).':'.
1234: &escape($srch->{'srchterm'}),$tryserver);
1235: if ($queryid !~/^\Q$host\E\_/) {
1236: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1237: next;
1.899 raeburn 1238: }
1239: my $reply = &get_query_reply($queryid);
1240: my $maxtries = 1;
1241: my $tries = 1;
1242: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1243: $reply = &get_query_reply($queryid);
1244: $tries ++;
1245: }
1246: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1247: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1248: } else {
1.911 raeburn 1249: my @matches;
1250: if ($reply =~ /\n/) {
1251: @matches = split(/\n/,$reply);
1252: } else {
1253: @matches = split(/\&/,$reply);
1254: }
1.899 raeburn 1255: foreach my $match (@matches) {
1256: my ($uname,$udom,%userhash);
1.911 raeburn 1257: foreach my $entry (split(/:/,$match)) {
1258: my ($key,$value) =
1259: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1260: $userhash{$key} = $value;
1261: if ($key eq 'username') {
1262: $uname = $value;
1263: } elsif ($key eq 'domain') {
1264: $udom = $value;
1.911 raeburn 1265: }
1.899 raeburn 1266: }
1267: $results{$uname.':'.$udom} = \%userhash;
1268: }
1269: }
1270: }
1271: }
1272: return %results;
1273: }
1274:
1.912 raeburn 1275: sub get_instuser {
1276: my ($udom,$uname,$id) = @_;
1277: my $homeserver = &domain($udom,'primary');
1278: my ($outcome,%results);
1279: if ($homeserver ne '') {
1280: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1281: &escape($id).':'.&escape($udom),$homeserver);
1282: my $host=&hostname($homeserver);
1283: if ($queryid !~/^\Q$host\E\_/) {
1284: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1285: return;
1286: }
1287: my $response = &get_query_reply($queryid);
1288: my $maxtries = 5;
1289: my $tries = 1;
1290: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1291: $response = &get_query_reply($queryid);
1292: $tries ++;
1293: }
1294: if (!&error($response) && $response ne 'refused') {
1295: if ($response eq 'unavailable') {
1296: $outcome = $response;
1297: } else {
1298: $outcome = 'ok';
1299: my @matches = split(/\n/,$response);
1300: foreach my $match (@matches) {
1301: my ($key,$value) = split(/=/,$match);
1302: $results{&unescape($key)} = &thaw_unescape($value);
1303: }
1304: }
1305: }
1306: }
1307: my %userinfo;
1308: if (ref($results{$uname}) eq 'HASH') {
1309: %userinfo = %{$results{$uname}};
1310: }
1311: return ($outcome,%userinfo);
1312: }
1313:
1314: sub inst_rulecheck {
1.923 raeburn 1315: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1316: my %returnhash;
1317: if ($udom ne '') {
1318: if (ref($rules) eq 'ARRAY') {
1319: @{$rules} = map {&escape($_);} (@{$rules});
1320: my $rulestr = join(':',@{$rules});
1321: my $homeserver=&domain($udom,'primary');
1322: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1323: my $response;
1324: if ($item eq 'username') {
1325: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1326: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1327: $homeserver));
1.923 raeburn 1328: } elsif ($item eq 'id') {
1329: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1330: ':'.&escape($id).':'.$rulestr,
1331: $homeserver));
1.945 raeburn 1332: } elsif ($item eq 'selfcreate') {
1333: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1334: &escape($udom).':'.&escape($uname).
1335: ':'.$rulestr,$homeserver));
1.923 raeburn 1336: }
1.912 raeburn 1337: if ($response ne 'refused') {
1338: my @pairs=split(/\&/,$response);
1339: foreach my $item (@pairs) {
1340: my ($key,$value)=split(/=/,$item,2);
1341: $key = &unescape($key);
1342: next if ($key =~ /^error: 2 /);
1343: $returnhash{$key}=&thaw_unescape($value);
1344: }
1345: }
1346: }
1347: }
1348: }
1349: return %returnhash;
1350: }
1351:
1352: sub inst_userrules {
1.923 raeburn 1353: my ($udom,$check) = @_;
1.912 raeburn 1354: my (%ruleshash,@ruleorder);
1355: if ($udom ne '') {
1356: my $homeserver=&domain($udom,'primary');
1357: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1358: my $response;
1359: if ($check eq 'id') {
1360: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1361: $homeserver);
1.943 raeburn 1362: } elsif ($check eq 'email') {
1363: $response=&reply('instemailrules:'.&escape($udom),
1364: $homeserver);
1.923 raeburn 1365: } else {
1366: $response=&reply('instuserrules:'.&escape($udom),
1367: $homeserver);
1368: }
1.912 raeburn 1369: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1370: ($response ne 'unknown_cmd') &&
1.912 raeburn 1371: ($response ne 'no_such_host')) {
1372: my ($hashitems,$orderitems) = split(/:/,$response);
1373: my @pairs=split(/\&/,$hashitems);
1374: foreach my $item (@pairs) {
1375: my ($key,$value)=split(/=/,$item,2);
1376: $key = &unescape($key);
1377: next if ($key =~ /^error: 2 /);
1378: $ruleshash{$key}=&thaw_unescape($value);
1379: }
1380: my @esc_order = split(/\&/,$orderitems);
1381: foreach my $item (@esc_order) {
1382: push(@ruleorder,&unescape($item));
1383: }
1384: }
1385: }
1386: }
1387: return (\%ruleshash,\@ruleorder);
1388: }
1389:
1.976 raeburn 1390: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1391:
1392: sub get_domain_defaults {
1393: my ($domain) = @_;
1394: my $cachetime = 60*60*24;
1395: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1396: if (defined($cached)) {
1397: if (ref($result) eq 'HASH') {
1398: return %{$result};
1399: }
1400: }
1401: my %domdefaults;
1402: my %domconfig =
1.989 raeburn 1403: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1404: 'requestcourses','inststatus'],$domain);
1.943 raeburn 1405: if (ref($domconfig{'defaults'}) eq 'HASH') {
1406: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1407: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1408: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1409: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1410: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1411: } else {
1412: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1413: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1414: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1415: }
1.976 raeburn 1416: if (ref($domconfig{'quotas'}) eq 'HASH') {
1417: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1418: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1419: } else {
1420: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1421: }
1422: my @usertools = ('aboutme','blog','portfolio');
1423: foreach my $item (@usertools) {
1424: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1425: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1426: }
1427: }
1428: }
1.985 raeburn 1429: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1430: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1431: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1432: }
1433: }
1.989 raeburn 1434: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1435: foreach my $item ('inststatustypes','inststatusorder') {
1436: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1437: }
1438: }
1.943 raeburn 1439: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1440: $cachetime);
1441: return %domdefaults;
1442: }
1443:
1.344 www 1444: # --------------------------------------------------- Assign a key to a student
1445:
1446: sub assign_access_key {
1.364 www 1447: #
1448: # a valid key looks like uname:udom#comments
1449: # comments are being appended
1450: #
1.498 www 1451: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1452: $kdom=
1.620 albertel 1453: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1454: $knum=
1.620 albertel 1455: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1456: $cdom=
1.620 albertel 1457: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1458: $cnum=
1.620 albertel 1459: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1460: $udom=$env{'user.name'} unless (defined($udom));
1461: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1462: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1463: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1464: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1465: # assigned to this person
1466: # - this should not happen,
1.345 www 1467: # unless something went wrong
1468: # the first time around
1469: # ready to assign
1.364 www 1470: $logentry=$1.'; '.$logentry;
1.496 www 1471: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1472: $kdom,$knum) eq 'ok') {
1.345 www 1473: # key now belongs to user
1.346 www 1474: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1475: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1476: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1477: return 'ok';
1478: } else {
1479: return
1480: 'error: Count not permanently assign key, will need to be re-entered later.';
1481: }
1482: } else {
1483: return 'error: Could not assign key, try again later.';
1484: }
1.364 www 1485: } elsif (!$existing{$ckey}) {
1.345 www 1486: # the key does not exist
1487: return 'error: The key does not exist';
1488: } else {
1489: # the key is somebody else's
1490: return 'error: The key is already in use';
1491: }
1.344 www 1492: }
1493:
1.364 www 1494: # ------------------------------------------ put an additional comment on a key
1495:
1496: sub comment_access_key {
1497: #
1498: # a valid key looks like uname:udom#comments
1499: # comments are being appended
1500: #
1501: my ($ckey,$cdom,$cnum,$logentry)=@_;
1502: $cdom=
1.620 albertel 1503: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1504: $cnum=
1.620 albertel 1505: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1506: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1507: if ($existing{$ckey}) {
1508: $existing{$ckey}.='; '.$logentry;
1509: # ready to assign
1.367 www 1510: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1511: $cdom,$cnum) eq 'ok') {
1512: return 'ok';
1513: } else {
1514: return 'error: Count not store comment.';
1515: }
1516: } else {
1517: # the key does not exist
1518: return 'error: The key does not exist';
1519: }
1520: }
1521:
1.344 www 1522: # ------------------------------------------------------ Generate a set of keys
1523:
1524: sub generate_access_keys {
1.364 www 1525: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1526: $cdom=
1.620 albertel 1527: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1528: $cnum=
1.620 albertel 1529: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1530: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1531: unless (($cdom) && ($cnum)) { return 0; }
1532: if ($number>10000) { return 0; }
1533: sleep(2); # make sure don't get same seed twice
1534: srand(time()^($$+($$<<15))); # from "Programming Perl"
1535: my $total=0;
1536: for (my $i=1;$i<=$number;$i++) {
1537: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1538: sprintf("%lx",int(100000*rand)).'-'.
1539: sprintf("%lx",int(100000*rand));
1540: $newkey=~s/1/g/g; # folks mix up 1 and l
1541: $newkey=~s/0/h/g; # and also 0 and O
1542: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1543: if ($existing{$newkey}) {
1544: $i--;
1545: } else {
1.364 www 1546: if (&put('accesskeys',
1547: { $newkey => '# generated '.localtime().
1.620 albertel 1548: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1549: '; '.$logentry },
1550: $cdom,$cnum) eq 'ok') {
1.344 www 1551: $total++;
1552: }
1553: }
1554: }
1.620 albertel 1555: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1556: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1557: return $total;
1558: }
1559:
1560: # ------------------------------------------------------- Validate an accesskey
1561:
1562: sub validate_access_key {
1563: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1564: $cdom=
1.620 albertel 1565: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1566: $cnum=
1.620 albertel 1567: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1568: $udom=$env{'user.domain'} unless (defined($udom));
1569: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1570: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1571: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1572: }
1573:
1574: # ------------------------------------- Find the section of student in a course
1.652 albertel 1575: sub devalidate_getsection_cache {
1576: my ($udom,$unam,$courseid)=@_;
1577: my $hashid="$udom:$unam:$courseid";
1578: &devalidate_cache_new('getsection',$hashid);
1579: }
1.298 matthew 1580:
1.815 albertel 1581: sub courseid_to_courseurl {
1582: my ($courseid) = @_;
1583: #already url style courseid
1584: return $courseid if ($courseid =~ m{^/});
1585:
1586: if (exists($env{'course.'.$courseid.'.num'})) {
1587: my $cnum = $env{'course.'.$courseid.'.num'};
1588: my $cdom = $env{'course.'.$courseid.'.domain'};
1589: return "/$cdom/$cnum";
1590: }
1591:
1592: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1593: if (exists($courseinfo{'num'})) {
1594: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1595: }
1596:
1597: return undef;
1598: }
1599:
1.298 matthew 1600: sub getsection {
1601: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1602: my $cachetime=1800;
1.551 albertel 1603:
1604: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1605: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1606: if (defined($cached)) { return $result; }
1607:
1.298 matthew 1608: my %Pending;
1609: my %Expired;
1610: #
1611: # Each role can either have not started yet (pending), be active,
1612: # or have expired.
1613: #
1614: # If there is an active role, we are done.
1615: #
1616: # If there is more than one role which has not started yet,
1617: # choose the one which will start sooner
1618: # If there is one role which has not started yet, return it.
1619: #
1620: # If there is more than one expired role, choose the one which ended last.
1621: # If there is a role which has expired, return it.
1622: #
1.815 albertel 1623: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1624: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1625: foreach my $key (keys(%roleshash)) {
1.479 albertel 1626: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1627: my $section=$1;
1628: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1629: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1630: my $now=time;
1.548 albertel 1631: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1632: $Expired{$end}=$section;
1633: next;
1634: }
1.548 albertel 1635: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1636: $Pending{$start}=$section;
1637: next;
1638: }
1.599 albertel 1639: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1640: }
1641: #
1642: # Presumedly there will be few matching roles from the above
1643: # loop and the sorting time will be negligible.
1644: if (scalar(keys(%Pending))) {
1645: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1646: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1647: }
1648: if (scalar(keys(%Expired))) {
1649: my @sorted = sort {$a <=> $b} keys(%Expired);
1650: my $time = pop(@sorted);
1.599 albertel 1651: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1652: }
1.599 albertel 1653: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1654: }
1.70 www 1655:
1.599 albertel 1656: sub save_cache {
1657: &purge_remembered();
1.722 albertel 1658: #&Apache::loncommon::validate_page();
1.620 albertel 1659: undef(%env);
1.780 albertel 1660: undef($env_loaded);
1.599 albertel 1661: }
1.452 albertel 1662:
1.599 albertel 1663: my $to_remember=-1;
1664: my %remembered;
1665: my %accessed;
1666: my $kicks=0;
1667: my $hits=0;
1.849 albertel 1668: sub make_key {
1669: my ($name,$id) = @_;
1.872 albertel 1670: if (length($id) > 65
1671: && length(&escape($id)) > 200) {
1672: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1673: }
1.849 albertel 1674: return &escape($name.':'.$id);
1675: }
1676:
1.599 albertel 1677: sub devalidate_cache_new {
1678: my ($name,$id,$debug) = @_;
1679: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1680: $id=&make_key($name,$id);
1.599 albertel 1681: $memcache->delete($id);
1682: delete($remembered{$id});
1683: delete($accessed{$id});
1684: }
1685:
1686: sub is_cached_new {
1687: my ($name,$id,$debug) = @_;
1.849 albertel 1688: $id=&make_key($name,$id);
1.599 albertel 1689: if (exists($remembered{$id})) {
1690: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1691: $accessed{$id}=[&gettimeofday()];
1692: $hits++;
1693: return ($remembered{$id},1);
1694: }
1695: my $value = $memcache->get($id);
1696: if (!(defined($value))) {
1697: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1698: return (undef,undef);
1.416 albertel 1699: }
1.599 albertel 1700: if ($value eq '__undef__') {
1701: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1702: $value=undef;
1703: }
1704: &make_room($id,$value,$debug);
1705: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1706: return ($value,1);
1707: }
1708:
1709: sub do_cache_new {
1710: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1711: $id=&make_key($name,$id);
1.599 albertel 1712: my $setvalue=$value;
1713: if (!defined($setvalue)) {
1714: $setvalue='__undef__';
1715: }
1.623 albertel 1716: if (!defined($time) ) {
1717: $time=600;
1718: }
1.599 albertel 1719: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1720: my $result = $memcache->set($id,$setvalue,$time);
1721: if (! $result) {
1.872 albertel 1722: &logthis("caching of id -> $id failed");
1.910 albertel 1723: $memcache->disconnect_all();
1.872 albertel 1724: }
1.600 albertel 1725: # need to make a copy of $value
1.919 albertel 1726: &make_room($id,$value,$debug);
1.599 albertel 1727: return $value;
1728: }
1729:
1730: sub make_room {
1731: my ($id,$value,$debug)=@_;
1.919 albertel 1732:
1733: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1734: : $value;
1.599 albertel 1735: if ($to_remember<0) { return; }
1736: $accessed{$id}=[&gettimeofday()];
1737: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1738: my $to_kick;
1739: my $max_time=0;
1740: foreach my $other (keys(%accessed)) {
1741: if (&tv_interval($accessed{$other}) > $max_time) {
1742: $to_kick=$other;
1743: $max_time=&tv_interval($accessed{$other});
1744: }
1745: }
1746: delete($remembered{$to_kick});
1747: delete($accessed{$to_kick});
1748: $kicks++;
1749: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1750: return;
1751: }
1752:
1.599 albertel 1753: sub purge_remembered {
1.604 albertel 1754: #&logthis("Tossing ".scalar(keys(%remembered)));
1755: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1756: undef(%remembered);
1757: undef(%accessed);
1.428 albertel 1758: }
1.70 www 1759: # ------------------------------------- Read an entry from a user's environment
1760:
1761: sub userenvironment {
1762: my ($udom,$unam,@what)=@_;
1.976 raeburn 1763: my $items;
1764: foreach my $item (@what) {
1765: $items.=&escape($item).'&';
1766: }
1767: $items=~s/\&$//;
1.70 www 1768: my %returnhash=();
1.1009 raeburn 1769: my $uhome = &homeserver($unam,$udom);
1770: unless ($uhome eq 'no_host') {
1771: my @answer=split(/\&/,
1772: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1773: my $i;
1774: for ($i=0;$i<=$#what;$i++) {
1775: $returnhash{$what[$i]}=&unescape($answer[$i]);
1776: }
1.70 www 1777: }
1778: return %returnhash;
1.1 albertel 1779: }
1780:
1.617 albertel 1781: # ---------------------------------------------------------- Get a studentphoto
1782: sub studentphoto {
1783: my ($udom,$unam,$ext) = @_;
1784: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1785: if (defined($env{'request.course.id'})) {
1.708 raeburn 1786: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1787: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1788: return(&retrievestudentphoto($udom,$unam,$ext));
1789: } else {
1790: my ($result,$perm_reqd)=
1.707 albertel 1791: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1792: if ($result eq 'ok') {
1793: if (!($perm_reqd eq 'yes')) {
1794: return(&retrievestudentphoto($udom,$unam,$ext));
1795: }
1796: }
1797: }
1798: }
1799: } else {
1800: my ($result,$perm_reqd) =
1.707 albertel 1801: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1802: if ($result eq 'ok') {
1803: if (!($perm_reqd eq 'yes')) {
1804: return(&retrievestudentphoto($udom,$unam,$ext));
1805: }
1806: }
1807: }
1808: return '/adm/lonKaputt/lonlogo_broken.gif';
1809: }
1810:
1811: sub retrievestudentphoto {
1812: my ($udom,$unam,$ext,$type) = @_;
1813: my $home=&Apache::lonnet::homeserver($unam,$udom);
1814: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1815: if ($ret eq 'ok') {
1816: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1817: if ($type eq 'thumbnail') {
1818: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1819: }
1820: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1821: return $tokenurl;
1822: } else {
1823: if ($type eq 'thumbnail') {
1824: return '/adm/lonKaputt/genericstudent_tn.gif';
1825: } else {
1826: return '/adm/lonKaputt/lonlogo_broken.gif';
1827: }
1.617 albertel 1828: }
1829: }
1830:
1.263 www 1831: # -------------------------------------------------------------------- New chat
1832:
1833: sub chatsend {
1.724 raeburn 1834: my ($newentry,$anon,$group)=@_;
1.620 albertel 1835: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1836: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1837: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1838: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1839: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1840: &escape($newentry)).':'.$group,$chome);
1.292 www 1841: }
1842:
1843: # ------------------------------------------ Find current version of a resource
1844:
1845: sub getversion {
1846: my $fname=&clutter(shift);
1847: unless ($fname=~/^\/res\//) { return -1; }
1848: return ¤tversion(&filelocation('',$fname));
1849: }
1850:
1851: sub currentversion {
1852: my $fname=shift;
1.599 albertel 1853: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1854: if (defined($cached)) { return $result; }
1.292 www 1855: my $author=$fname;
1856: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1857: my ($udom,$uname)=split(/\//,$author);
1858: my $home=homeserver($uname,$udom);
1859: if ($home eq 'no_host') {
1860: return -1;
1861: }
1862: my $answer=reply("currentversion:$fname",$home);
1863: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1864: return -1;
1865: }
1.599 albertel 1866: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1867: }
1868:
1.1 albertel 1869: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1870:
1.1 albertel 1871: sub subscribe {
1872: my $fname=shift;
1.761 raeburn 1873: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1874: $fname=~s/[\n\r]//g;
1.1 albertel 1875: my $author=$fname;
1876: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1877: my ($udom,$uname)=split(/\//,$author);
1878: my $home=homeserver($uname,$udom);
1.335 albertel 1879: if ($home eq 'no_host') {
1880: return 'not_found';
1.1 albertel 1881: }
1882: my $answer=reply("sub:$fname",$home);
1.64 www 1883: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1884: $answer.=' by '.$home;
1885: }
1.1 albertel 1886: return $answer;
1887: }
1888:
1.8 www 1889: # -------------------------------------------------------------- Replicate file
1890:
1891: sub repcopy {
1892: my $filename=shift;
1.23 www 1893: $filename=~s/\/+/\//g;
1.607 raeburn 1894: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1895: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1896: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1897: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1898: return &repcopy_userfile($filename);
1899: }
1.532 albertel 1900: $filename=~s/[\n\r]//g;
1.8 www 1901: my $transname="$filename.in.transfer";
1.828 www 1902: # FIXME: this should flock
1.607 raeburn 1903: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1904: my $remoteurl=subscribe($filename);
1.64 www 1905: if ($remoteurl =~ /^con_lost by/) {
1906: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1907: return 'unavailable';
1.8 www 1908: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1909: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1910: return 'not_found';
1.64 www 1911: } elsif ($remoteurl =~ /^rejected by/) {
1912: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1913: return 'forbidden';
1.20 www 1914: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1915: return 'ok';
1.8 www 1916: } else {
1.290 www 1917: my $author=$filename;
1918: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1919: my ($udom,$uname)=split(/\//,$author);
1920: my $home=homeserver($uname,$udom);
1921: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1922: my @parts=split(/\//,$filename);
1923: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1924: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1925: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1926: return 'bad_request';
1.8 www 1927: }
1928: my $count;
1929: for ($count=5;$count<$#parts;$count++) {
1930: $path.="/$parts[$count]";
1931: if ((-e $path)!=1) {
1932: mkdir($path,0777);
1933: }
1934: }
1935: my $ua=new LWP::UserAgent;
1936: my $request=new HTTP::Request('GET',"$remoteurl");
1937: my $response=$ua->request($request,$transname);
1938: if ($response->is_error()) {
1939: unlink($transname);
1940: my $message=$response->status_line;
1.672 albertel 1941: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1942: ." LWP get: $message: $filename</font>");
1.607 raeburn 1943: return 'unavailable';
1.8 www 1944: } else {
1.16 www 1945: if ($remoteurl!~/\.meta$/) {
1946: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1947: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1948: if ($mresponse->is_error()) {
1949: unlink($filename.'.meta');
1950: &logthis(
1.672 albertel 1951: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1952: }
1953: }
1.8 www 1954: rename($transname,$filename);
1.607 raeburn 1955: return 'ok';
1.8 www 1956: }
1.290 www 1957: }
1.8 www 1958: }
1.330 www 1959: }
1960:
1961: # ------------------------------------------------ Get server side include body
1962: sub ssi_body {
1.381 albertel 1963: my ($filelink,%form)=@_;
1.606 matthew 1964: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1965: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1966: }
1.953 www 1967: my $output='';
1968: my $response;
1.980 raeburn 1969: if ($filelink=~/^https?\:/) {
1.954 raeburn 1970: ($output,$response)=&externalssi($filelink);
1.953 www 1971: } else {
1.1004 droeschl 1972: $filelink .= $filelink=~/\?/ ? '&' : '?';
1973: $filelink .= 'inhibitmenu=yes';
1.953 www 1974: ($output,$response)=&ssi($filelink,%form);
1975: }
1.778 albertel 1976: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1977: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1978: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1979: if (wantarray) {
1980: return ($output, $response);
1981: } else {
1982: return $output;
1983: }
1.8 www 1984: }
1985:
1.15 www 1986: # --------------------------------------------------------- Server Side Include
1987:
1.782 albertel 1988: sub absolute_url {
1989: my ($host_name) = @_;
1990: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1991: if ($host_name eq '') {
1992: $host_name = $ENV{'SERVER_NAME'};
1993: }
1994: return $protocol.$host_name;
1995: }
1996:
1.942 foxr 1997: #
1998: # Server side include.
1999: # Parameters:
2000: # fn Possibly encrypted resource name/id.
2001: # form Hash that describes how the rendering should be done
2002: # and other things.
1.944 foxr 2003: # Returns:
1.950 raeburn 2004: # Scalar context: The content of the response.
2005: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2006: #
1.15 www 2007: sub ssi {
2008:
1.944 foxr 2009: my ($fn,%form)=@_;
1.15 www 2010: my $ua=new LWP::UserAgent;
1.23 www 2011: my $request;
1.711 albertel 2012:
2013: $form{'no_update_last_known'}=1;
1.895 albertel 2014: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2015: if (%form) {
1.782 albertel 2016: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2017: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2018: } else {
1.782 albertel 2019: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2020: }
2021:
1.15 www 2022: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2023: my $response=$ua->request($request);
2024:
1.944 foxr 2025: if (wantarray) {
2026: return ($response->content, $response);
2027: } else {
2028: return $response->content;
1.942 foxr 2029: }
1.324 www 2030: }
2031:
2032: sub externalssi {
2033: my ($url)=@_;
2034: my $ua=new LWP::UserAgent;
2035: my $request=new HTTP::Request('GET',$url);
2036: my $response=$ua->request($request);
1.954 raeburn 2037: if (wantarray) {
2038: return ($response->content, $response);
2039: } else {
2040: return $response->content;
2041: }
1.15 www 2042: }
1.254 www 2043:
1.492 albertel 2044: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2045:
2046: sub allowuploaded {
2047: my ($srcurl,$url)=@_;
2048: $url=&clutter(&declutter($url));
2049: my $dir=$url;
2050: $dir=~s/\/[^\/]+$//;
2051: my %httpref=();
2052: my $httpurl=&hreflocation('',$url);
2053: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2054: &Apache::lonnet::appenv(\%httpref);
1.254 www 2055: }
1.477 raeburn 2056:
1.478 albertel 2057: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2058: # input: action, courseID, current domain, intended
1.637 raeburn 2059: # path to file, source of file, instruction to parse file for objects,
2060: # ref to hash for embedded objects,
2061: # ref to hash for codebase of java objects.
2062: #
1.485 raeburn 2063: # output: url to file (if action was uploaddoc),
2064: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2065: #
1.478 albertel 2066: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2067: # course.
1.477 raeburn 2068: #
1.478 albertel 2069: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2070: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2071: # course's home server.
1.477 raeburn 2072: #
1.478 albertel 2073: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2074: # be copied from $source (current location) to
2075: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2076: # and will then be copied to
2077: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2078: # course's home server.
1.485 raeburn 2079: #
1.481 raeburn 2080: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2081: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2082: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2083: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2084: # in course's home server.
1.637 raeburn 2085: #
1.477 raeburn 2086:
2087: sub process_coursefile {
1.638 albertel 2088: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2089: my $fetchresult;
1.638 albertel 2090: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2091: if ($action eq 'propagate') {
1.638 albertel 2092: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2093: $home);
1.481 raeburn 2094: } else {
1.477 raeburn 2095: my $fpath = '';
2096: my $fname = $file;
1.478 albertel 2097: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2098: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2099: my $filepath = &build_filepath($fpath);
1.481 raeburn 2100: if ($action eq 'copy') {
2101: if ($source eq '') {
2102: $fetchresult = 'no source file';
2103: return $fetchresult;
2104: } else {
2105: my $destination = $filepath.'/'.$fname;
2106: rename($source,$destination);
2107: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2108: $home);
1.481 raeburn 2109: }
2110: } elsif ($action eq 'uploaddoc') {
2111: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2112: print $fh $env{'form.'.$source};
1.481 raeburn 2113: close($fh);
1.637 raeburn 2114: if ($parser eq 'parse') {
1.961 raeburn 2115: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637 raeburn 2116: unless ($parse_result eq 'ok') {
2117: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2118: }
2119: }
1.477 raeburn 2120: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2121: $home);
1.481 raeburn 2122: if ($fetchresult eq 'ok') {
2123: return '/uploaded/'.$fpath.'/'.$fname;
2124: } else {
2125: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2126: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2127: return '/adm/notfound.html';
2128: }
1.477 raeburn 2129: }
2130: }
1.485 raeburn 2131: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2132: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2133: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2134: }
2135: return $fetchresult;
2136: }
2137:
1.637 raeburn 2138: sub build_filepath {
2139: my ($fpath) = @_;
2140: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2141: unless ($fpath eq '') {
2142: my @parts=split('/',$fpath);
2143: foreach my $part (@parts) {
2144: $filepath.= '/'.$part;
2145: if ((-e $filepath)!=1) {
2146: mkdir($filepath,0777);
2147: }
2148: }
2149: }
2150: return $filepath;
2151: }
2152:
2153: sub store_edited_file {
1.638 albertel 2154: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2155: my $file = $primary_url;
2156: $file =~ s#^/uploaded/$docudom/$docuname/##;
2157: my $fpath = '';
2158: my $fname = $file;
2159: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2160: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2161: my $filepath = &build_filepath($fpath);
2162: open(my $fh,'>'.$filepath.'/'.$fname);
2163: print $fh $content;
2164: close($fh);
1.638 albertel 2165: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2166: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2167: $home);
1.637 raeburn 2168: if ($$fetchresult eq 'ok') {
2169: return '/uploaded/'.$fpath.'/'.$fname;
2170: } else {
1.638 albertel 2171: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2172: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2173: return '/adm/notfound.html';
2174: }
2175: }
2176:
1.531 albertel 2177: sub clean_filename {
1.831 albertel 2178: my ($fname,$args)=@_;
1.315 www 2179: # Replace Windows backslashes by forward slashes
1.257 www 2180: $fname=~s/\\/\//g;
1.831 albertel 2181: if (!$args->{'keep_path'}) {
2182: # Get rid of everything but the actual filename
2183: $fname=~s/^.*\/([^\/]+)$/$1/;
2184: }
1.315 www 2185: # Replace spaces by underscores
2186: $fname=~s/\s+/\_/g;
2187: # Replace all other weird characters by nothing
1.831 albertel 2188: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2189: # Replace all .\d. sequences with _\d. so they no longer look like version
2190: # numbers
2191: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2192: return $fname;
2193: }
1.984 neumanie 2194: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
2195: sub resizeImage {
2196: my($img_url) = @_;
2197: my $ima = Image::Magick->new;
2198: $ima->Read($img_url);
2199: if($ima->Get('width') > 400)
2200: {
2201: my $factor = $ima->Get('width')/400;
2202: $ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
2203: }
2204: if($ima->Get('height') > 500)
2205: {
2206: my $factor = $ima->Get('height')/500;
2207: $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
2208: }
2209:
2210: $ima->Write($img_url);
2211: }
1.531 albertel 2212:
1.977 amueller 2213: #Wrapper function for userphotoupload
2214: sub userphotoupload
2215: {
2216: my($formname,$subdir) = @_;
2217: $upload_photo_form = 1;
2218: return &userfileupload($formname,undef,$subdir);
2219: }
2220:
1.608 albertel 2221: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2222: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2223: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2224: # $coursedoc - if true up to the current course
2225: # if false
2226: # $subdir - directory in userfile to store the file into
1.858 raeburn 2227: # $parser - instruction to parse file for objects ($parser = parse)
2228: # $allfiles - reference to hash for embedded objects
2229: # $codebase - reference to hash for codebase of java objects
2230: # $desuname - username for permanent storage of uploaded file
2231: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2232: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2233: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 2234: #
1.686 albertel 2235: # output: url of file in userspace, or error: <message>
2236: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2237:
2238:
1.531 albertel 2239: sub userfileupload {
1.860 raeburn 2240: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2241: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 2242: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2243: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2244: $fname=&clean_filename($fname);
1.315 www 2245: # See if there is anything left
1.257 www 2246: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2247: chop($env{'form.'.$formname});
1.523 raeburn 2248: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2249: my $now = time;
2250: my $filepath = 'tmp/helprequests/'.$now;
2251: my @parts=split(/\//,$filepath);
2252: my $fullpath = $perlvar{'lonDaemons'};
2253: for (my $i=0;$i<@parts;$i++) {
2254: $fullpath .= '/'.$parts[$i];
2255: if ((-e $fullpath)!=1) {
2256: mkdir($fullpath,0777);
2257: }
2258: }
2259: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2260: print $fh $env{'form.'.$formname};
1.523 raeburn 2261: close($fh);
1.741 raeburn 2262: return $fullpath.'/'.$fname;
2263: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2264: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2265: '_'.$env{'user.domain'}.'/pending';
2266: my @parts=split(/\//,$filepath);
2267: my $fullpath = $perlvar{'lonDaemons'};
2268: for (my $i=0;$i<@parts;$i++) {
2269: $fullpath .= '/'.$parts[$i];
2270: if ((-e $fullpath)!=1) {
2271: mkdir($fullpath,0777);
2272: }
2273: }
2274: open(my $fh,'>'.$fullpath.'/'.$fname);
2275: print $fh $env{'form.'.$formname};
2276: close($fh);
2277: return $fullpath.'/'.$fname;
1.523 raeburn 2278: }
1.995 raeburn 2279: if ($subdir eq 'scantron') {
2280: $fname = 'scantron_orig_'.$fname;
2281: } else {
1.258 www 2282: # Create the directory if not present
1.995 raeburn 2283: $fname="$subdir/$fname";
2284: }
1.259 www 2285: if ($coursedoc) {
1.638 albertel 2286: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2287: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2288: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2289: return &finishuserfileupload($docuname,$docudom,
2290: $formname,$fname,$parser,$allfiles,
1.860 raeburn 2291: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 2292: } else {
1.620 albertel 2293: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2294: return &process_coursefile('uploaddoc',$docuname,$docudom,
2295: $fname,$formname,$parser,
2296: $allfiles,$codebase);
1.481 raeburn 2297: }
1.719 banghart 2298: } elsif (defined($destuname)) {
2299: my $docuname=$destuname;
2300: my $docudom=$destudom;
1.860 raeburn 2301: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2302: $parser,$allfiles,$codebase,
2303: $thumbwidth,$thumbheight);
1.719 banghart 2304:
1.259 www 2305: } else {
1.638 albertel 2306: my $docuname=$env{'user.name'};
2307: my $docudom=$env{'user.domain'};
1.714 raeburn 2308: if (exists($env{'form.group'})) {
2309: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2310: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2311: }
1.860 raeburn 2312: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2313: $parser,$allfiles,$codebase,
2314: $thumbwidth,$thumbheight);
1.259 www 2315: }
1.271 www 2316: }
2317:
2318: sub finishuserfileupload {
1.860 raeburn 2319: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2320: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 2321: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2322: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2323:
1.860 raeburn 2324: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2325: $file=$fname;
2326: if ($fname=~m|/|) {
2327: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2328: $path.=$fnamepath.'/';
2329: }
1.259 www 2330: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2331: my $count;
2332: for ($count=4;$count<=$#parts;$count++) {
2333: $filepath.="/$parts[$count]";
2334: if ((-e $filepath)!=1) {
2335: mkdir($filepath,0777);
2336: }
2337: }
1.984 neumanie 2338:
1.258 www 2339: # Save the file
2340: {
1.701 albertel 2341: if (!open(FH,'>'.$filepath.'/'.$file)) {
2342: &logthis('Failed to create '.$filepath.'/'.$file);
2343: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2344: return '/adm/notfound.html';
2345: }
2346: if (!print FH ($env{'form.'.$formname})) {
2347: &logthis('Failed to write to '.$filepath.'/'.$file);
2348: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2349: return '/adm/notfound.html';
2350: }
1.570 albertel 2351: close(FH);
1.977 amueller 2352: if($upload_photo_form==1)
2353: {
1.984 neumanie 2354: resizeImage($filepath.'/'.$file);
1.977 amueller 2355: $upload_photo_form = 0;
2356: }
1.258 www 2357: }
1.637 raeburn 2358: if ($parser eq 'parse') {
1.961 raeburn 2359: my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638 albertel 2360: $codebase);
1.637 raeburn 2361: unless ($parse_result eq 'ok') {
1.638 albertel 2362: &logthis('Failed to parse '.$filepath.$file.
2363: ' for embedded media: '.$parse_result);
1.637 raeburn 2364: }
2365: }
1.860 raeburn 2366: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2367: my $input = $filepath.'/'.$file;
2368: my $output = $filepath.'/'.'tn-'.$file;
2369: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2370: system("convert -sample $thumbsize $input $output");
2371: if (-e $filepath.'/'.'tn-'.$file) {
2372: $fetchthumb = 1;
2373: }
2374: }
1.858 raeburn 2375:
1.259 www 2376: # Notify homeserver to grep it
2377: #
1.984 neumanie 2378: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2379: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2380: if ($fetchresult eq 'ok') {
1.860 raeburn 2381: if ($fetchthumb) {
2382: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2383: if ($thumbresult ne 'ok') {
2384: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2385: $docuhome.': '.$thumbresult);
2386: }
2387: }
1.259 www 2388: #
1.258 www 2389: # Return the URL to it
1.494 albertel 2390: return '/uploaded/'.$path.$file;
1.263 www 2391: } else {
1.494 albertel 2392: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2393: ': '.$fetchresult);
1.263 www 2394: return '/adm/notfound.html';
1.858 raeburn 2395: }
1.493 albertel 2396: }
2397:
1.637 raeburn 2398: sub extract_embedded_items {
1.961 raeburn 2399: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2400: my @state = ();
2401: my %javafiles = (
2402: codebase => '',
2403: code => '',
2404: archive => ''
2405: );
2406: my %mediafiles = (
2407: src => '',
2408: movie => '',
2409: );
1.648 raeburn 2410: my $p;
2411: if ($content) {
2412: $p = HTML::LCParser->new($content);
2413: } else {
1.961 raeburn 2414: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2415: }
1.641 albertel 2416: while (my $t=$p->get_token()) {
1.640 albertel 2417: if ($t->[0] eq 'S') {
2418: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2419: push(@state, $tagname);
1.648 raeburn 2420: if (lc($tagname) eq 'allow') {
2421: &add_filetype($allfiles,$attr->{'src'},'src');
2422: }
1.640 albertel 2423: if (lc($tagname) eq 'img') {
2424: &add_filetype($allfiles,$attr->{'src'},'src');
2425: }
1.886 albertel 2426: if (lc($tagname) eq 'a') {
2427: &add_filetype($allfiles,$attr->{'href'},'href');
2428: }
1.645 raeburn 2429: if (lc($tagname) eq 'script') {
2430: if ($attr->{'archive'} =~ /\.jar$/i) {
2431: &add_filetype($allfiles,$attr->{'archive'},'archive');
2432: } else {
2433: &add_filetype($allfiles,$attr->{'src'},'src');
2434: }
2435: }
2436: if (lc($tagname) eq 'link') {
2437: if (lc($attr->{'rel'}) eq 'stylesheet') {
2438: &add_filetype($allfiles,$attr->{'href'},'href');
2439: }
2440: }
1.640 albertel 2441: if (lc($tagname) eq 'object' ||
2442: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2443: foreach my $item (keys(%javafiles)) {
2444: $javafiles{$item} = '';
2445: }
2446: }
2447: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2448: my $name = lc($attr->{'name'});
2449: foreach my $item (keys(%javafiles)) {
2450: if ($name eq $item) {
2451: $javafiles{$item} = $attr->{'value'};
2452: last;
2453: }
2454: }
2455: foreach my $item (keys(%mediafiles)) {
2456: if ($name eq $item) {
2457: &add_filetype($allfiles, $attr->{'value'}, 'value');
2458: last;
2459: }
2460: }
2461: }
2462: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2463: foreach my $item (keys(%javafiles)) {
2464: if ($attr->{$item}) {
2465: $javafiles{$item} = $attr->{$item};
2466: last;
2467: }
2468: }
2469: foreach my $item (keys(%mediafiles)) {
2470: if ($attr->{$item}) {
2471: &add_filetype($allfiles,$attr->{$item},$item);
2472: last;
2473: }
2474: }
2475: }
2476: } elsif ($t->[0] eq 'E') {
2477: my ($tagname) = ($t->[1]);
2478: if ($javafiles{'codebase'} ne '') {
2479: $javafiles{'codebase'} .= '/';
2480: }
2481: if (lc($tagname) eq 'applet' ||
2482: lc($tagname) eq 'object' ||
2483: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2484: ) {
2485: foreach my $item (keys(%javafiles)) {
2486: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2487: my $file=$javafiles{'codebase'}.$javafiles{$item};
2488: &add_filetype($allfiles,$file,$item);
2489: }
2490: }
2491: }
2492: pop @state;
2493: }
2494: }
1.637 raeburn 2495: return 'ok';
2496: }
2497:
1.639 albertel 2498: sub add_filetype {
2499: my ($allfiles,$file,$type)=@_;
2500: if (exists($allfiles->{$file})) {
2501: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2502: push(@{$allfiles->{$file}}, &escape($type));
2503: }
2504: } else {
2505: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2506: }
2507: }
2508:
1.493 albertel 2509: sub removeuploadedurl {
1.984 neumanie 2510: my ($url)=@_;
2511: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2512: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2513: }
2514:
2515: sub removeuserfile {
2516: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2517: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2518: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2519: if ($result eq 'ok') {
1.798 raeburn 2520: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2521: my $metafile = $fname.'.meta';
2522: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2523: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2524: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2525: my $sqlresult =
1.823 albertel 2526: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2527: 'portfolio_metadata',$group,
2528: 'delete');
1.798 raeburn 2529: }
2530: }
2531: return $result;
1.257 www 2532: }
1.15 www 2533:
1.530 albertel 2534: sub mkdiruserfile {
2535: my ($docuname,$docudom,$dir)=@_;
2536: my $home=&homeserver($docuname,$docudom);
2537: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2538: }
2539:
1.531 albertel 2540: sub renameuserfile {
2541: my ($docuname,$docudom,$old,$new)=@_;
2542: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2543: my $result = &reply("renameuserfile:$docudom:$docuname:".
2544: &escape("$old").':'.&escape("$new"),$home);
2545: if ($result eq 'ok') {
2546: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2547: my $oldmeta = $old.'.meta';
2548: my $newmeta = $new.'.meta';
2549: my $metaresult =
2550: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2551: my $url = "/uploaded/$docudom/$docuname/$old";
2552: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2553: my $sqlresult =
1.823 albertel 2554: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2555: 'portfolio_metadata',$group,
2556: 'delete');
1.798 raeburn 2557: }
2558: }
2559: return $result;
1.531 albertel 2560: }
2561:
1.14 www 2562: # ------------------------------------------------------------------------- Log
2563:
2564: sub log {
2565: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2566: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2567: }
2568:
2569: # ------------------------------------------------------------------ Course Log
1.352 www 2570: #
2571: # This routine flushes several buffers of non-mission-critical nature
2572: #
1.157 www 2573:
2574: sub flushcourselogs {
1.352 www 2575: &logthis('Flushing log buffers');
2576: #
2577: # course logs
2578: # This is a log of all transactions in a course, which can be used
2579: # for data mining purposes
2580: #
2581: # It also collects the courseid database, which lists last transaction
2582: # times and course titles for all courseids
2583: #
2584: my %courseidbuffer=();
1.921 raeburn 2585: foreach my $crsid (keys(%courselogs)) {
1.352 www 2586: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2587: &escape($courselogs{$crsid}),
2588: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2589: delete $courselogs{$crsid};
2590: } else {
2591: &logthis('Failed to flush log buffer for '.$crsid);
2592: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2593: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2594: " exceeded maximum size, deleting.</font>");
2595: delete $courselogs{$crsid};
2596: }
1.352 www 2597: }
1.920 raeburn 2598: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2599: 'description' => $coursedescrbuf{$crsid},
2600: 'inst_code' => $courseinstcodebuf{$crsid},
2601: 'type' => $coursetypebuf{$crsid},
2602: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2603: };
1.191 harris41 2604: }
1.352 www 2605: #
2606: # Write course id database (reverse lookup) to homeserver of courses
2607: # Is used in pickcourse
2608: #
1.840 albertel 2609: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2610: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2611: $courseidbuffer{$crs_home},
2612: $crs_home,'timeonly');
1.352 www 2613: }
2614: #
2615: # File accesses
2616: # Writes to the dynamic metadata of resources to get hit counts, etc.
2617: #
1.449 matthew 2618: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2619: if ($entry =~ /___count$/) {
2620: my ($dom,$name);
1.807 albertel 2621: ($dom,$name,undef)=
1.811 albertel 2622: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2623: if (! defined($dom) || $dom eq '' ||
2624: ! defined($name) || $name eq '') {
1.620 albertel 2625: my $cid = $env{'request.course.id'};
2626: $dom = $env{'request.'.$cid.'.domain'};
2627: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2628: }
1.450 matthew 2629: my $value = $accesshash{$entry};
2630: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2631: my %temphash=($url => $value);
1.449 matthew 2632: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2633: if ($result eq 'ok') {
2634: delete $accesshash{$entry};
2635: } elsif ($result eq 'unknown_cmd') {
2636: # Target server has old code running on it.
1.450 matthew 2637: my %temphash=($entry => $value);
1.449 matthew 2638: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2639: delete $accesshash{$entry};
2640: }
2641: }
2642: } else {
1.811 albertel 2643: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2644: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2645: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2646: delete $accesshash{$entry};
2647: }
1.185 www 2648: }
1.191 harris41 2649: }
1.352 www 2650: #
2651: # Roles
2652: # Reverse lookup of user roles for course faculty/staff and co-authorship
2653: #
1.800 albertel 2654: foreach my $entry (keys(%userrolehash)) {
1.351 www 2655: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2656: split(/\:/,$entry);
2657: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2658: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2659: $rudom,$runame) eq 'ok') {
2660: delete $userrolehash{$entry};
2661: }
2662: }
1.662 raeburn 2663: #
2664: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2665: #
2666: my %domrolebuffer = ();
1.1000 raeburn 2667: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2668: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2669: if ($domrolebuffer{$rudom}) {
2670: $domrolebuffer{$rudom}.='&'.&escape($entry).
2671: '='.&escape($domainrolehash{$entry});
2672: } else {
2673: $domrolebuffer{$rudom}.=&escape($entry).
2674: '='.&escape($domainrolehash{$entry});
2675: }
2676: delete $domainrolehash{$entry};
2677: }
2678: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2679: my %servers = &get_servers($dom,'library');
2680: foreach my $tryserver (keys(%servers)) {
2681: unless (&reply('domroleput:'.$dom.':'.
2682: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2683: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2684: }
1.662 raeburn 2685: }
2686: }
1.186 www 2687: $dumpcount++;
1.157 www 2688: }
2689:
2690: sub courselog {
2691: my $what=shift;
1.158 www 2692: $what=time.':'.$what;
1.620 albertel 2693: unless ($env{'request.course.id'}) { return ''; }
2694: $coursedombuf{$env{'request.course.id'}}=
2695: $env{'course.'.$env{'request.course.id'}.'.domain'};
2696: $coursenumbuf{$env{'request.course.id'}}=
2697: $env{'course.'.$env{'request.course.id'}.'.num'};
2698: $coursehombuf{$env{'request.course.id'}}=
2699: $env{'course.'.$env{'request.course.id'}.'.home'};
2700: $coursedescrbuf{$env{'request.course.id'}}=
2701: $env{'course.'.$env{'request.course.id'}.'.description'};
2702: $courseinstcodebuf{$env{'request.course.id'}}=
2703: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2704: $courseownerbuf{$env{'request.course.id'}}=
2705: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2706: $coursetypebuf{$env{'request.course.id'}}=
2707: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2708: if (defined $courselogs{$env{'request.course.id'}}) {
2709: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2710: } else {
1.620 albertel 2711: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2712: }
1.620 albertel 2713: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2714: &flushcourselogs();
2715: }
1.158 www 2716: }
2717:
2718: sub courseacclog {
2719: my $fnsymb=shift;
1.620 albertel 2720: unless ($env{'request.course.id'}) { return ''; }
2721: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2722: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2723: $what.=':POST';
1.583 matthew 2724: # FIXME: Probably ought to escape things....
1.800 albertel 2725: foreach my $key (keys(%env)) {
2726: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2727: my $formitem = $1;
2728: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2729: $what.=':'.$formitem.'='.$env{$key};
2730: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2731: $what.=':'.$formitem.'='.$env{$key};
2732: }
1.158 www 2733: }
1.191 harris41 2734: }
1.583 matthew 2735: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2736: # FIXME: We should not be depending on a form parameter that someone
2737: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2738: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2739: $what.= ':POST';
2740: # FIXME: Probably ought to escape things....
2741: foreach my $element ('courseexp','crsfulltext','crsrelated',
2742: 'crsdiscuss') {
1.620 albertel 2743: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2744: }
2745: }
1.158 www 2746: }
2747: &courselog($what);
1.149 www 2748: }
2749:
1.185 www 2750: sub countacc {
2751: my $url=&declutter(shift);
1.458 matthew 2752: return if (! defined($url) || $url eq '');
1.620 albertel 2753: unless ($env{'request.course.id'}) { return ''; }
2754: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2755: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2756: $accesshash{$key}++;
1.185 www 2757: }
1.349 www 2758:
1.361 www 2759: sub linklog {
2760: my ($from,$to)=@_;
2761: $from=&declutter($from);
2762: $to=&declutter($to);
2763: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2764: $accesshash{$to.'___'.$from.'___goto'}=1;
2765: }
2766:
1.349 www 2767: sub userrolelog {
2768: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2769: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2770: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2771: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2772: ($trole=~/^ta/)) {
1.350 www 2773: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2774: $userrolehash
2775: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2776: =$tend.':'.$tstart;
1.662 raeburn 2777: }
1.898 albertel 2778: if (($env{'request.role'} =~ /dc\./) &&
2779: (($trole=~/^au/) || ($trole=~/^in/) ||
2780: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2781: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2782: $userrolehash
2783: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2784: =$tend.':'.$tstart;
2785: }
1.662 raeburn 2786: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2787: ($trole=~/^li/) || ($trole=~/^li/) ||
2788: ($trole=~/^au/) || ($trole=~/^dg/) ||
2789: ($trole=~/^sc/)) {
2790: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2791: $domainrolehash
2792: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2793: = $tend.':'.$tstart;
2794: }
1.351 www 2795: }
2796:
1.957 raeburn 2797: sub courserolelog {
2798: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2799: if (($trole eq 'cc') || ($trole eq 'in') ||
2800: ($trole eq 'ep') || ($trole eq 'ad') ||
2801: ($trole eq 'ta') || ($trole eq 'st') ||
2802: ($trole=~/^cr/) || ($trole eq 'gr')) {
2803: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2804: my $cdom = $1;
2805: my $cnum = $2;
2806: my $sec = $3;
2807: my $namespace = 'rolelog';
2808: my %storehash = (
2809: role => $trole,
2810: start => $tstart,
2811: end => $tend,
2812: selfenroll => $selfenroll,
2813: context => $context,
2814: );
2815: if ($trole eq 'gr') {
2816: $namespace = 'groupslog';
2817: $storehash{'group'} = $sec;
2818: } else {
2819: $storehash{'section'} = $sec;
2820: }
2821: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2822: if (($trole ne 'st') || ($sec ne '')) {
2823: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2824: }
1.957 raeburn 2825: }
2826: }
2827: return;
2828: }
2829:
1.351 www 2830: sub get_course_adv_roles {
1.948 raeburn 2831: my ($cid,$codes) = @_;
1.620 albertel 2832: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2833: my %coursehash=&coursedescription($cid);
1.988 raeburn 2834: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2835: my %nothide=();
1.800 albertel 2836: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2837: if ($user !~ /:/) {
2838: $nothide{join(':',split(/[\@]/,$user))}=1;
2839: } else {
2840: $nothide{$user}=1;
2841: }
1.470 www 2842: }
1.351 www 2843: my %returnhash=();
2844: my %dumphash=
2845: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2846: my $now=time;
1.997 raeburn 2847: my %privileged;
1.1000 raeburn 2848: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2849: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2850: if (($tstart) && ($tstart<0)) { next; }
2851: if (($tend) && ($tend<$now)) { next; }
2852: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2853: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2854: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2855: unless (ref($privileged{$domain}) eq 'HASH') {
2856: my %dompersonnel =
1.998 raeburn 2857: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2858: $privileged{$domain} = {};
2859: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2860: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2861: foreach my $user (keys(%{$dompersonnel{$server}})) {
2862: my ($trole,$uname,$udom) = split(/:/,$user);
2863: $privileged{$udom}{$uname} = 1;
2864: }
2865: }
2866: }
2867: }
2868: if ((exists($privileged{$domain}{$username})) &&
2869: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2870: if ($role eq 'cr') { next; }
1.948 raeburn 2871: if ($codes) {
2872: if ($section) { $role .= ':'.$section; }
2873: if ($returnhash{$role}) {
2874: $returnhash{$role}.=','.$username.':'.$domain;
2875: } else {
2876: $returnhash{$role}=$username.':'.$domain;
2877: }
1.351 www 2878: } else {
1.988 raeburn 2879: my $key=&plaintext($role,$crstype);
1.973 bisitz 2880: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2881: if ($returnhash{$key}) {
2882: $returnhash{$key}.=','.$username.':'.$domain;
2883: } else {
2884: $returnhash{$key}=$username.':'.$domain;
2885: }
1.351 www 2886: }
1.948 raeburn 2887: }
1.400 www 2888: return %returnhash;
2889: }
2890:
2891: sub get_my_roles {
1.937 raeburn 2892: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2893: unless (defined($uname)) { $uname=$env{'user.name'}; }
2894: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2895: my (%dumphash,%nothide);
1.858 raeburn 2896: if ($context eq 'userroles') {
2897: %dumphash = &dump('roles',$udom,$uname);
2898: } else {
2899: %dumphash=
1.400 www 2900: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2901: if ($hidepriv) {
2902: my %coursehash=&coursedescription($udom.'_'.$uname);
2903: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2904: if ($user !~ /:/) {
2905: $nothide{join(':',split(/[\@]/,$user))} = 1;
2906: } else {
2907: $nothide{$user} = 1;
2908: }
2909: }
2910: }
1.858 raeburn 2911: }
1.400 www 2912: my %returnhash=();
2913: my $now=time;
1.999 raeburn 2914: my %privileged;
1.800 albertel 2915: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2916: my ($role,$tend,$tstart);
2917: if ($context eq 'userroles') {
2918: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2919: } else {
2920: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2921: }
1.400 www 2922: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2923: my $status = 'active';
1.939 raeburn 2924: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2925: $status = 'previous';
2926: }
2927: if (($tstart) && ($now<$tstart)) {
2928: $status = 'future';
2929: }
2930: if (ref($types) eq 'ARRAY') {
2931: if (!grep(/^\Q$status\E$/,@{$types})) {
2932: next;
2933: }
2934: } else {
2935: if ($status ne 'active') {
2936: next;
2937: }
2938: }
1.867 raeburn 2939: my ($rolecode,$username,$domain,$section,$area);
2940: if ($context eq 'userroles') {
2941: ($area,$rolecode) = split(/_/,$entry);
2942: (undef,$domain,$username,$section) = split(/\//,$area);
2943: } else {
2944: ($role,$username,$domain,$section) = split(/\:/,$entry);
2945: }
1.832 raeburn 2946: if (ref($roledoms) eq 'ARRAY') {
2947: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2948: next;
2949: }
2950: }
2951: if (ref($roles) eq 'ARRAY') {
2952: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2953: if ($role =~ /^cr\//) {
2954: if (!grep(/^cr$/,@{$roles})) {
2955: next;
2956: }
2957: } else {
2958: next;
2959: }
1.832 raeburn 2960: }
1.867 raeburn 2961: }
1.937 raeburn 2962: if ($hidepriv) {
1.999 raeburn 2963: if ($context eq 'userroles') {
2964: if ((&privileged($username,$domain)) &&
2965: (!$nothide{$username.':'.$domain})) {
2966: next;
2967: }
2968: } else {
2969: unless (ref($privileged{$domain}) eq 'HASH') {
2970: my %dompersonnel =
2971: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2972: $privileged{$domain} = {};
2973: if (keys(%dompersonnel)) {
2974: foreach my $server (keys(%dompersonnel)) {
2975: if (ref($dompersonnel{$server}) eq 'HASH') {
2976: foreach my $user (keys(%{$dompersonnel{$server}})) {
2977: my ($trole,$uname,$udom) = split(/:/,$user);
2978: $privileged{$udom}{$uname} = $trole;
2979: }
2980: }
2981: }
2982: }
2983: }
2984: if (exists($privileged{$domain}{$username})) {
2985: if (!$nothide{$username.':'.$domain}) {
2986: next;
2987: }
2988: }
1.937 raeburn 2989: }
2990: }
1.933 raeburn 2991: if ($withsec) {
2992: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2993: $tstart.':'.$tend;
2994: } else {
2995: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2996: }
1.832 raeburn 2997: }
1.373 www 2998: return %returnhash;
1.399 www 2999: }
3000:
3001: # ----------------------------------------------------- Frontpage Announcements
3002: #
3003: #
3004:
3005: sub postannounce {
3006: my ($server,$text)=@_;
1.844 albertel 3007: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3008: unless ($text=~/\w/) { $text=''; }
3009: return &reply('setannounce:'.&escape($text),$server);
3010: }
3011:
3012: sub getannounce {
1.448 albertel 3013:
3014: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3015: my $announcement='';
1.800 albertel 3016: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3017: close($fh);
1.399 www 3018: if ($announcement=~/\w/) {
3019: return
3020: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3021: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3022: } else {
3023: return '';
3024: }
3025: } else {
3026: return '';
3027: }
1.351 www 3028: }
1.353 www 3029:
3030: # ---------------------------------------------------------- Course ID routines
3031: # Deal with domain's nohist_courseid.db files
3032: #
3033:
3034: sub courseidput {
1.921 raeburn 3035: my ($domain,$storehash,$coursehome,$caller) = @_;
3036: my $outcome;
3037: if ($caller eq 'timeonly') {
3038: my $cids = '';
3039: foreach my $item (keys(%$storehash)) {
3040: $cids.=&escape($item).'&';
3041: }
3042: $cids=~s/\&$//;
3043: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3044: $coursehome);
3045: } else {
3046: my $items = '';
3047: foreach my $item (keys(%$storehash)) {
3048: $items.= &escape($item).'='.
3049: &freeze_escape($$storehash{$item}).'&';
3050: }
3051: $items=~s/\&$//;
3052: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3053: $coursehome);
1.918 raeburn 3054: }
3055: if ($outcome eq 'unknown_cmd') {
3056: my $what;
3057: foreach my $cid (keys(%$storehash)) {
3058: $what .= &escape($cid).'=';
1.921 raeburn 3059: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3060: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3061: }
3062: $what =~ s/\:$/&/;
3063: }
3064: $what =~ s/\&$//;
3065: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3066: } else {
3067: return $outcome;
3068: }
1.353 www 3069: }
3070:
3071: sub courseiddump {
1.921 raeburn 3072: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3073: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1008 raeburn 3074: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,$cloneonly)=@_;
1.918 raeburn 3075: my $as_hash = 1;
3076: my %returnhash;
3077: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3078: my %libserv = &all_library();
3079: foreach my $tryserver (keys(%libserv)) {
3080: if ( ( $hostidflag == 1
3081: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3082: || (!defined($hostidflag)) ) {
3083:
1.918 raeburn 3084: if (($domfilter eq '') ||
3085: (&host_domain($tryserver) eq $domfilter)) {
3086: my $rep =
3087: &reply('courseiddump:'.&host_domain($tryserver).':'.
3088: $sincefilter.':'.&escape($descfilter).':'.
3089: &escape($instcodefilter).':'.&escape($ownerfilter).
3090: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3091: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3092: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3093: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3094: &escape($cc_clone).':'.$cloneonly,$tryserver);
1.918 raeburn 3095: my @pairs=split(/\&/,$rep);
3096: foreach my $item (@pairs) {
3097: my ($key,$value)=split(/\=/,$item,2);
3098: $key = &unescape($key);
3099: next if ($key =~ /^error: 2 /);
3100: my $result = &thaw_unescape($value);
3101: if (ref($result) eq 'HASH') {
3102: $returnhash{$key}=$result;
3103: } else {
1.921 raeburn 3104: my @responses = split(/:/,$value);
3105: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3106: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3107: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3108: }
1.1008 raeburn 3109: }
1.353 www 3110: }
3111: }
3112: }
3113: }
3114: return %returnhash;
3115: }
3116:
1.658 raeburn 3117: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3118:
3119: sub dcmailput {
1.685 raeburn 3120: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3121: my $status = &Apache::lonnet::critical(
1.740 www 3122: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3123: &escape($message),$server);
1.662 raeburn 3124: return $status;
3125: }
3126:
1.658 raeburn 3127: sub dcmaildump {
3128: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3129: my %returnhash=();
1.846 albertel 3130:
3131: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3132: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3133: &escape($enddate).':';
3134: my @esc_senders=map { &escape($_)} @$senders;
3135: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3136: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3137: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3138: if (($key) && ($value)) {
3139: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3140: }
3141: }
3142: }
3143: return %returnhash;
3144: }
1.662 raeburn 3145: # ---------------------------------------------------------- Domain roles
3146:
3147: sub get_domain_roles {
3148: my ($dom,$roles,$startdate,$enddate)=@_;
3149: if (undef($startdate) || $startdate eq '') {
3150: $startdate = '.';
3151: }
3152: if (undef($enddate) || $enddate eq '') {
3153: $enddate = '.';
3154: }
1.922 raeburn 3155: my $rolelist;
3156: if (ref($roles) eq 'ARRAY') {
3157: $rolelist = join(':',@{$roles});
3158: }
1.662 raeburn 3159: my %personnel = ();
1.841 albertel 3160:
3161: my %servers = &get_servers($dom,'library');
3162: foreach my $tryserver (keys(%servers)) {
3163: %{$personnel{$tryserver}}=();
3164: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3165: &escape($startdate).':'.
3166: &escape($enddate).':'.
3167: &escape($rolelist), $tryserver))) {
3168: my ($key,$value) = split(/\=/,$line,2);
3169: if (($key) && ($value)) {
3170: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3171: }
3172: }
1.662 raeburn 3173: }
3174: return %personnel;
3175: }
1.658 raeburn 3176:
1.149 www 3177: # ----------------------------------------------------------- Check out an item
3178:
1.504 albertel 3179: sub get_first_access {
3180: my ($type,$argsymb)=@_;
1.790 albertel 3181: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3182: if ($argsymb) { $symb=$argsymb; }
3183: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3184: if ($type eq 'course') {
3185: $res='course';
3186: } elsif ($type eq 'map') {
1.588 albertel 3187: $res=&symbread($map);
3188: } else {
3189: $res=$symb;
3190: }
3191: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3192: return $times{"$courseid\0$res"};
1.504 albertel 3193: }
3194:
3195: sub set_first_access {
3196: my ($type)=@_;
1.790 albertel 3197: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3198: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3199: if ($type eq 'course') {
3200: $res='course';
3201: } elsif ($type eq 'map') {
1.588 albertel 3202: $res=&symbread($map);
3203: } else {
3204: $res=$symb;
3205: }
3206: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3207: if (!$firstaccess) {
1.588 albertel 3208: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3209: }
3210: return 'already_set';
1.504 albertel 3211: }
3212:
1.149 www 3213: sub checkout {
3214: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3215: my $now=time;
3216: my $lonhost=$perlvar{'lonHostID'};
3217: my $infostr=&escape(
1.234 www 3218: 'CHECKOUTTOKEN&'.
1.149 www 3219: $tuname.'&'.
3220: $tudom.'&'.
3221: $tcrsid.'&'.
3222: $symb.'&'.
3223: $now.'&'.$ENV{'REMOTE_ADDR'});
3224: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3225: if ($token=~/^error\:/) {
1.672 albertel 3226: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3227: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3228: "</font>");
3229: return '';
3230: }
3231:
1.149 www 3232: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3233: $token=~tr/a-z/A-Z/;
3234:
1.153 www 3235: my %infohash=('resource.0.outtoken' => $token,
3236: 'resource.0.checkouttime' => $now,
3237: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3238:
3239: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3240: return '';
1.151 www 3241: } else {
1.672 albertel 3242: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3243: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3244: "</font>");
1.149 www 3245: }
3246:
3247: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3248: &escape('Checkout '.$infostr.' - '.
3249: $token)) ne 'ok') {
3250: return '';
1.151 www 3251: } else {
1.672 albertel 3252: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3253: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3254: "</font>");
1.149 www 3255: }
1.151 www 3256: return $token;
1.149 www 3257: }
3258:
3259: # ------------------------------------------------------------ Check in an item
3260:
3261: sub checkin {
3262: my $token=shift;
1.150 www 3263: my $now=time;
3264: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3265: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3266: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3267: $dtoken=~s/\W/\_/g;
1.234 www 3268: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3269: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3270:
1.154 www 3271: unless (($tuname) && ($tudom)) {
3272: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3273: return '';
3274: }
3275:
3276: unless (&allowed('mgr',$tcrsid)) {
3277: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3278: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3279: return '';
3280: }
3281:
1.153 www 3282: my %infohash=('resource.0.intoken' => $token,
3283: 'resource.0.checkintime' => $now,
3284: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3285:
3286: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3287: return '';
3288: }
3289:
3290: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3291: &escape('Checkin - '.$token)) ne 'ok') {
3292: return '';
3293: }
3294:
3295: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3296: }
3297:
3298: # --------------------------------------------- Set Expire Date for Spreadsheet
3299:
3300: sub expirespread {
3301: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3302: my $cid=$env{'request.course.id'};
1.110 www 3303: if ($cid) {
3304: my $now=time;
3305: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3306: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3307: $env{'course.'.$cid.'.num'}.
1.110 www 3308: ':nohist_expirationdates:'.
3309: &escape($key).'='.$now,
1.620 albertel 3310: $env{'course.'.$cid.'.home'})
1.110 www 3311: }
3312: return 'ok';
1.14 www 3313: }
3314:
1.109 www 3315: # ----------------------------------------------------- Devalidate Spreadsheets
3316:
3317: sub devalidate {
1.325 www 3318: my ($symb,$uname,$udom)=@_;
1.620 albertel 3319: my $cid=$env{'request.course.id'};
1.109 www 3320: if ($cid) {
1.391 matthew 3321: # delete the stored spreadsheets for
3322: # - the student level sheet of this user in course's homespace
3323: # - the assessment level sheet for this resource
3324: # for this user in user's homespace
1.553 albertel 3325: # - current conditional state info
1.325 www 3326: my $key=$uname.':'.$udom.':';
1.109 www 3327: my $status=
1.299 matthew 3328: &del('nohist_calculatedsheets',
1.391 matthew 3329: [$key.'studentcalc:'],
1.620 albertel 3330: $env{'course.'.$cid.'.domain'},
3331: $env{'course.'.$cid.'.num'})
1.133 albertel 3332: .' '.
3333: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3334: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3335: unless ($status eq 'ok ok') {
3336: &logthis('Could not devalidate spreadsheet '.
1.325 www 3337: $uname.' at '.$udom.' for '.
1.109 www 3338: $symb.': '.$status);
1.133 albertel 3339: }
1.553 albertel 3340: &delenv('user.state.'.$cid);
1.109 www 3341: }
3342: }
3343:
1.265 albertel 3344: sub get_scalar {
3345: my ($string,$end) = @_;
3346: my $value;
3347: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3348: $value = $1;
3349: } elsif ($$string =~ s/^([^&]*?)&//) {
3350: $value = $1;
3351: }
3352: return &unescape($value);
3353: }
3354:
3355: sub array2str {
3356: my (@array) = @_;
3357: my $result=&arrayref2str(\@array);
3358: $result=~s/^__ARRAY_REF__//;
3359: $result=~s/__END_ARRAY_REF__$//;
3360: return $result;
3361: }
3362:
1.204 albertel 3363: sub arrayref2str {
3364: my ($arrayref) = @_;
1.265 albertel 3365: my $result='__ARRAY_REF__';
1.204 albertel 3366: foreach my $elem (@$arrayref) {
1.265 albertel 3367: if(ref($elem) eq 'ARRAY') {
3368: $result.=&arrayref2str($elem).'&';
3369: } elsif(ref($elem) eq 'HASH') {
3370: $result.=&hashref2str($elem).'&';
3371: } elsif(ref($elem)) {
3372: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3373: } else {
3374: $result.=&escape($elem).'&';
3375: }
3376: }
3377: $result=~s/\&$//;
1.265 albertel 3378: $result .= '__END_ARRAY_REF__';
1.204 albertel 3379: return $result;
3380: }
3381:
1.168 albertel 3382: sub hash2str {
1.204 albertel 3383: my (%hash) = @_;
3384: my $result=&hashref2str(\%hash);
1.265 albertel 3385: $result=~s/^__HASH_REF__//;
3386: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3387: return $result;
3388: }
3389:
3390: sub hashref2str {
3391: my ($hashref)=@_;
1.265 albertel 3392: my $result='__HASH_REF__';
1.800 albertel 3393: foreach my $key (sort(keys(%$hashref))) {
3394: if (ref($key) eq 'ARRAY') {
3395: $result.=&arrayref2str($key).'=';
3396: } elsif (ref($key) eq 'HASH') {
3397: $result.=&hashref2str($key).'=';
3398: } elsif (ref($key)) {
1.265 albertel 3399: $result.='=';
1.800 albertel 3400: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3401: } else {
1.800 albertel 3402: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3403: }
3404:
1.800 albertel 3405: if(ref($hashref->{$key}) eq 'ARRAY') {
3406: $result.=&arrayref2str($hashref->{$key}).'&';
3407: } elsif(ref($hashref->{$key}) eq 'HASH') {
3408: $result.=&hashref2str($hashref->{$key}).'&';
3409: } elsif(ref($hashref->{$key})) {
1.265 albertel 3410: $result.='&';
1.800 albertel 3411: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3412: } else {
1.800 albertel 3413: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3414: }
3415: }
1.168 albertel 3416: $result=~s/\&$//;
1.265 albertel 3417: $result .= '__END_HASH_REF__';
1.168 albertel 3418: return $result;
3419: }
3420:
3421: sub str2hash {
1.265 albertel 3422: my ($string)=@_;
3423: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3424: return %$hash;
3425: }
3426:
3427: sub str2hashref {
1.168 albertel 3428: my ($string) = @_;
1.265 albertel 3429:
3430: my %hash;
3431:
3432: if($string !~ /^__HASH_REF__/) {
3433: if (! ($string eq '' || !defined($string))) {
3434: $hash{'error'}='Not hash reference';
3435: }
3436: return (\%hash, $string);
3437: }
3438:
3439: $string =~ s/^__HASH_REF__//;
3440:
3441: while($string !~ /^__END_HASH_REF__/) {
3442: #key
3443: my $key='';
3444: if($string =~ /^__HASH_REF__/) {
3445: ($key, $string)=&str2hashref($string);
3446: if(defined($key->{'error'})) {
3447: $hash{'error'}='Bad data';
3448: return (\%hash, $string);
3449: }
3450: } elsif($string =~ /^__ARRAY_REF__/) {
3451: ($key, $string)=&str2arrayref($string);
3452: if($key->[0] eq 'Array reference error') {
3453: $hash{'error'}='Bad data';
3454: return (\%hash, $string);
3455: }
3456: } else {
3457: $string =~ s/^(.*?)=//;
1.267 albertel 3458: $key=&unescape($1);
1.265 albertel 3459: }
3460: $string =~ s/^=//;
3461:
3462: #value
3463: my $value='';
3464: if($string =~ /^__HASH_REF__/) {
3465: ($value, $string)=&str2hashref($string);
3466: if(defined($value->{'error'})) {
3467: $hash{'error'}='Bad data';
3468: return (\%hash, $string);
3469: }
3470: } elsif($string =~ /^__ARRAY_REF__/) {
3471: ($value, $string)=&str2arrayref($string);
3472: if($value->[0] eq 'Array reference error') {
3473: $hash{'error'}='Bad data';
3474: return (\%hash, $string);
3475: }
3476: } else {
3477: $value=&get_scalar(\$string,'__END_HASH_REF__');
3478: }
3479: $string =~ s/^&//;
3480:
3481: $hash{$key}=$value;
1.204 albertel 3482: }
1.265 albertel 3483:
3484: $string =~ s/^__END_HASH_REF__//;
3485:
3486: return (\%hash, $string);
1.204 albertel 3487: }
3488:
3489: sub str2array {
1.265 albertel 3490: my ($string)=@_;
3491: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3492: return @$array;
3493: }
3494:
3495: sub str2arrayref {
1.204 albertel 3496: my ($string) = @_;
1.265 albertel 3497: my @array;
3498:
3499: if($string !~ /^__ARRAY_REF__/) {
3500: if (! ($string eq '' || !defined($string))) {
3501: $array[0]='Array reference error';
3502: }
3503: return (\@array, $string);
3504: }
3505:
3506: $string =~ s/^__ARRAY_REF__//;
3507:
3508: while($string !~ /^__END_ARRAY_REF__/) {
3509: my $value='';
3510: if($string =~ /^__HASH_REF__/) {
3511: ($value, $string)=&str2hashref($string);
3512: if(defined($value->{'error'})) {
3513: $array[0] ='Array reference error';
3514: return (\@array, $string);
3515: }
3516: } elsif($string =~ /^__ARRAY_REF__/) {
3517: ($value, $string)=&str2arrayref($string);
3518: if($value->[0] eq 'Array reference error') {
3519: $array[0] ='Array reference error';
3520: return (\@array, $string);
3521: }
3522: } else {
3523: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3524: }
3525: $string =~ s/^&//;
3526:
3527: push(@array, $value);
1.191 harris41 3528: }
1.265 albertel 3529:
3530: $string =~ s/^__END_ARRAY_REF__//;
3531:
3532: return (\@array, $string);
1.168 albertel 3533: }
3534:
1.167 albertel 3535: # -------------------------------------------------------------------Temp Store
3536:
1.168 albertel 3537: sub tmpreset {
3538: my ($symb,$namespace,$domain,$stuname) = @_;
3539: if (!$symb) {
3540: $symb=&symbread();
1.620 albertel 3541: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3542: }
3543: $symb=escape($symb);
3544:
1.620 albertel 3545: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3546: $namespace=~s/\//\_/g;
3547: $namespace=~s/\W//g;
3548:
1.620 albertel 3549: if (!$domain) { $domain=$env{'user.domain'}; }
3550: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3551: if ($domain eq 'public' && $stuname eq 'public') {
3552: $stuname=$ENV{'REMOTE_ADDR'};
3553: }
1.168 albertel 3554: my $path=$perlvar{'lonDaemons'}.'/tmp';
3555: my %hash;
3556: if (tie(%hash,'GDBM_File',
3557: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3558: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3559: foreach my $key (keys(%hash)) {
1.180 albertel 3560: if ($key=~ /:$symb/) {
1.168 albertel 3561: delete($hash{$key});
3562: }
3563: }
3564: }
3565: }
3566:
1.167 albertel 3567: sub tmpstore {
1.168 albertel 3568: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3569:
3570: if (!$symb) {
3571: $symb=&symbread();
1.620 albertel 3572: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3573: }
3574: $symb=escape($symb);
3575:
3576: if (!$namespace) {
3577: # I don't think we would ever want to store this for a course.
3578: # it seems this will only be used if we don't have a course.
1.620 albertel 3579: #$namespace=$env{'request.course.id'};
1.168 albertel 3580: #if (!$namespace) {
1.620 albertel 3581: $namespace=$env{'request.state'};
1.168 albertel 3582: #}
3583: }
3584: $namespace=~s/\//\_/g;
3585: $namespace=~s/\W//g;
1.620 albertel 3586: if (!$domain) { $domain=$env{'user.domain'}; }
3587: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3588: if ($domain eq 'public' && $stuname eq 'public') {
3589: $stuname=$ENV{'REMOTE_ADDR'};
3590: }
1.168 albertel 3591: my $now=time;
3592: my %hash;
3593: my $path=$perlvar{'lonDaemons'}.'/tmp';
3594: if (tie(%hash,'GDBM_File',
3595: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3596: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3597: $hash{"version:$symb"}++;
3598: my $version=$hash{"version:$symb"};
3599: my $allkeys='';
3600: foreach my $key (keys(%$storehash)) {
3601: $allkeys.=$key.':';
1.591 albertel 3602: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3603: }
3604: $hash{"$version:$symb:timestamp"}=$now;
3605: $allkeys.='timestamp';
3606: $hash{"$version:keys:$symb"}=$allkeys;
3607: if (untie(%hash)) {
3608: return 'ok';
3609: } else {
3610: return "error:$!";
3611: }
3612: } else {
3613: return "error:$!";
3614: }
3615: }
1.167 albertel 3616:
1.168 albertel 3617: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3618:
1.168 albertel 3619: sub tmprestore {
3620: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3621:
1.168 albertel 3622: if (!$symb) {
3623: $symb=&symbread();
1.620 albertel 3624: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3625: }
3626: $symb=escape($symb);
3627:
1.620 albertel 3628: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3629:
1.620 albertel 3630: if (!$domain) { $domain=$env{'user.domain'}; }
3631: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3632: if ($domain eq 'public' && $stuname eq 'public') {
3633: $stuname=$ENV{'REMOTE_ADDR'};
3634: }
1.168 albertel 3635: my %returnhash;
3636: $namespace=~s/\//\_/g;
3637: $namespace=~s/\W//g;
3638: my %hash;
3639: my $path=$perlvar{'lonDaemons'}.'/tmp';
3640: if (tie(%hash,'GDBM_File',
3641: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3642: &GDBM_READER(),0640)) {
1.168 albertel 3643: my $version=$hash{"version:$symb"};
3644: $returnhash{'version'}=$version;
3645: my $scope;
3646: for ($scope=1;$scope<=$version;$scope++) {
3647: my $vkeys=$hash{"$scope:keys:$symb"};
3648: my @keys=split(/:/,$vkeys);
3649: my $key;
3650: $returnhash{"$scope:keys"}=$vkeys;
3651: foreach $key (@keys) {
1.591 albertel 3652: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3653: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3654: }
3655: }
1.168 albertel 3656: if (!(untie(%hash))) {
3657: return "error:$!";
3658: }
3659: } else {
3660: return "error:$!";
3661: }
3662: return %returnhash;
1.167 albertel 3663: }
3664:
1.9 www 3665: # ----------------------------------------------------------------------- Store
3666:
3667: sub store {
1.124 www 3668: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3669: my $home='';
3670:
1.168 albertel 3671: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3672:
1.213 www 3673: $symb=&symbclean($symb);
1.122 albertel 3674: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3675:
1.620 albertel 3676: if (!$domain) { $domain=$env{'user.domain'}; }
3677: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3678:
3679: &devalidate($symb,$stuname,$domain);
1.109 www 3680:
3681: $symb=escape($symb);
1.187 www 3682: if (!$namespace) {
1.620 albertel 3683: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3684: return '';
3685: }
3686: }
1.620 albertel 3687: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3688:
3689: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3690: $$storehash{'host'}=$perlvar{'lonHostID'};
3691:
1.12 www 3692: my $namevalue='';
1.800 albertel 3693: foreach my $key (keys(%$storehash)) {
3694: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3695: }
1.12 www 3696: $namevalue=~s/\&$//;
1.187 www 3697: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3698: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3699: }
3700:
1.47 www 3701: # -------------------------------------------------------------- Critical Store
3702:
3703: sub cstore {
1.124 www 3704: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3705: my $home='';
3706:
1.168 albertel 3707: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3708:
1.213 www 3709: $symb=&symbclean($symb);
1.122 albertel 3710: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3711:
1.620 albertel 3712: if (!$domain) { $domain=$env{'user.domain'}; }
3713: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3714:
3715: &devalidate($symb,$stuname,$domain);
1.109 www 3716:
3717: $symb=escape($symb);
1.187 www 3718: if (!$namespace) {
1.620 albertel 3719: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3720: return '';
3721: }
3722: }
1.620 albertel 3723: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3724:
3725: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3726: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3727:
1.47 www 3728: my $namevalue='';
1.800 albertel 3729: foreach my $key (keys(%$storehash)) {
3730: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3731: }
1.47 www 3732: $namevalue=~s/\&$//;
1.187 www 3733: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3734: return critical
3735: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3736: }
3737:
1.9 www 3738: # --------------------------------------------------------------------- Restore
3739:
3740: sub restore {
1.124 www 3741: my ($symb,$namespace,$domain,$stuname) = @_;
3742: my $home='';
3743:
1.168 albertel 3744: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3745:
1.122 albertel 3746: if (!$symb) {
3747: unless ($symb=escape(&symbread())) { return ''; }
3748: } else {
1.213 www 3749: $symb=&escape(&symbclean($symb));
1.122 albertel 3750: }
1.188 www 3751: if (!$namespace) {
1.620 albertel 3752: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3753: return '';
3754: }
3755: }
1.620 albertel 3756: if (!$domain) { $domain=$env{'user.domain'}; }
3757: if (!$stuname) { $stuname=$env{'user.name'}; }
3758: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3759: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3760:
1.12 www 3761: my %returnhash=();
1.800 albertel 3762: foreach my $line (split(/\&/,$answer)) {
3763: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3764: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3765: }
1.75 www 3766: my $version;
3767: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3768: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3769: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3770: }
1.75 www 3771: }
1.13 www 3772: return %returnhash;
1.34 www 3773: }
3774:
3775: # ---------------------------------------------------------- Course Description
3776:
3777: sub coursedescription {
1.731 albertel 3778: my ($courseid,$args)=@_;
1.34 www 3779: $courseid=~s/^\///;
1.49 www 3780: $courseid=~s/\_/\//g;
1.34 www 3781: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3782: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3783: my $normalid=$cdomain.'_'.$cnum;
3784: # need to always cache even if we get errors otherwise we keep
3785: # trying and trying and trying to get the course description.
3786: my %envhash=();
3787: my %returnhash=();
1.731 albertel 3788:
3789: my $expiretime=600;
3790: if ($env{'request.course.id'} eq $normalid) {
3791: $expiretime=120;
3792: }
3793:
3794: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3795: if (!$args->{'freshen_cache'}
3796: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3797: foreach my $key (keys(%env)) {
3798: next if ($key !~ /^\Q$prefix\E(.*)/);
3799: my ($setting) = $1;
3800: $returnhash{$setting} = $env{$key};
3801: }
3802: return %returnhash;
3803: }
3804:
3805: # get the data agin
3806: if (!$args->{'one_time'}) {
3807: $envhash{'course.'.$normalid.'.last_cache'}=time;
3808: }
1.811 albertel 3809:
1.34 www 3810: if ($chome ne 'no_host') {
1.302 albertel 3811: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3812: if (!exists($returnhash{'con_lost'})) {
3813: $returnhash{'home'}= $chome;
3814: $returnhash{'domain'} = $cdomain;
3815: $returnhash{'num'} = $cnum;
1.741 raeburn 3816: if (!defined($returnhash{'type'})) {
3817: $returnhash{'type'} = 'Course';
3818: }
1.130 albertel 3819: while (my ($name,$value) = each %returnhash) {
1.53 www 3820: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3821: }
1.270 www 3822: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3823: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3824: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3825: $envhash{'course.'.$normalid.'.home'}=$chome;
3826: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3827: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3828: }
3829: }
1.731 albertel 3830: if (!$args->{'one_time'}) {
1.949 raeburn 3831: &appenv(\%envhash);
1.731 albertel 3832: }
1.302 albertel 3833: return %returnhash;
1.461 www 3834: }
3835:
3836: # -------------------------------------------------See if a user is privileged
3837:
3838: sub privileged {
3839: my ($username,$domain)=@_;
3840: my $rolesdump=&reply("dump:$domain:$username:roles",
3841: &homeserver($username,$domain));
3842: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3843: my $now=time;
3844: if ($rolesdump ne '') {
1.800 albertel 3845: foreach my $entry (split(/&/,$rolesdump)) {
3846: if ($entry!~/^rolesdef_/) {
3847: my ($area,$role)=split(/=/,$entry);
1.461 www 3848: $area=~s/\_\w\w$//;
3849: my ($trole,$tend,$tstart)=split(/_/,$role);
3850: if (($trole eq 'dc') || ($trole eq 'su')) {
3851: my $active=1;
3852: if ($tend) {
3853: if ($tend<$now) { $active=0; }
3854: }
3855: if ($tstart) {
3856: if ($tstart>$now) { $active=0; }
3857: }
3858: if ($active) { return 1; }
3859: }
3860: }
3861: }
3862: }
3863: return 0;
1.9 www 3864: }
1.1 albertel 3865:
1.103 harris41 3866: # -------------------------------------------------------- Get user privileges
1.11 www 3867:
3868: sub rolesinit {
3869: my ($domain,$username,$authhost)=@_;
1.966 raeburn 3870: my %userroles;
1.11 www 3871: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966 raeburn 3872: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11 www 3873: my %allroles=();
1.678 raeburn 3874: my %allgroups=();
1.11 www 3875: my $now=time;
1.966 raeburn 3876: %userroles = ('user.login.time' => $now);
1.678 raeburn 3877: my $group_privs;
1.11 www 3878:
3879: if ($rolesdump ne '') {
1.800 albertel 3880: foreach my $entry (split(/&/,$rolesdump)) {
3881: if ($entry!~/^rolesdef_/) {
3882: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3883: $area=~s/\_\w\w$//;
1.678 raeburn 3884: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3885: if ($role=~/^cr/) {
1.807 albertel 3886: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3887: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3888: ($tend,$tstart)=split('_',$trest);
3889: } else {
3890: $trole=$role;
3891: }
1.678 raeburn 3892: } elsif ($role =~ m|^gr/|) {
3893: ($trole,$tend,$tstart) = split(/_/,$role);
3894: ($trole,$group_privs) = split(/\//,$trole);
3895: $group_privs = &unescape($group_privs);
1.587 albertel 3896: } else {
3897: ($trole,$tend,$tstart)=split(/_/,$role);
3898: }
1.743 albertel 3899: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3900: $username);
3901: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3902: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3903: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3904: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3905: my $spec=$trole.'.'.$area;
3906: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3907: if ($trole =~ /^cr\//) {
1.567 raeburn 3908: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3909: } elsif ($trole eq 'gr') {
3910: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3911: } else {
1.567 raeburn 3912: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3913: }
1.12 www 3914: }
1.662 raeburn 3915: }
1.191 harris41 3916: }
1.743 albertel 3917: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3918: $userroles{'user.adv'} = $adv;
3919: $userroles{'user.author'} = $author;
1.620 albertel 3920: $env{'user.adv'}=$adv;
1.11 www 3921: }
1.743 albertel 3922: return \%userroles;
1.11 www 3923: }
3924:
1.567 raeburn 3925: sub set_arearole {
3926: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3927: # log the associated role with the area
3928: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3929: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3930: }
3931:
3932: sub custom_roleprivs {
3933: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3934: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3935: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3936: if (&hostname($homsvr) ne '') {
1.567 raeburn 3937: my ($rdummy,$roledef)=
3938: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3939: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3940: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3941: if (defined($syspriv)) {
3942: $$allroles{'cm./'}.=':'.$syspriv;
3943: $$allroles{$spec.'./'}.=':'.$syspriv;
3944: }
3945: if ($tdomain ne '') {
3946: if (defined($dompriv)) {
3947: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3948: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3949: }
3950: if (($trest ne '') && (defined($coursepriv))) {
3951: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3952: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3953: }
3954: }
3955: }
3956: }
3957: }
3958:
1.678 raeburn 3959: sub group_roleprivs {
3960: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3961: my $access = 1;
3962: my $now = time;
3963: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3964: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3965: if ($access) {
1.811 albertel 3966: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3967: $$allgroups{$course}{$group} .=':'.$group_privs;
3968: }
3969: }
1.567 raeburn 3970:
3971: sub standard_roleprivs {
3972: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3973: if (defined($pr{$trole.':s'})) {
3974: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3975: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3976: }
3977: if ($tdomain ne '') {
3978: if (defined($pr{$trole.':d'})) {
3979: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3980: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3981: }
3982: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3983: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3984: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3985: }
3986: }
3987: }
3988:
3989: sub set_userprivs {
1.678 raeburn 3990: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3991: my $author=0;
3992: my $adv=0;
1.678 raeburn 3993: my %grouproles = ();
3994: if (keys(%{$allgroups}) > 0) {
1.1000 raeburn 3995: foreach my $role (keys(%{$allroles})) {
1.681 raeburn 3996: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3997: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3998: $trole = $1;
3999: $area = $2;
1.681 raeburn 4000: $sec = $3;
4001: $extendedarea = $area.$sec;
4002: if (exists($$allgroups{$area})) {
4003: foreach my $group (keys(%{$$allgroups{$area}})) {
4004: my $spec = $trole.'.'.$extendedarea;
4005: $grouproles{$spec.'.'.$area.'/'.$group} =
4006: $$allgroups{$area}{$group};
1.678 raeburn 4007: }
4008: }
4009: }
4010: }
4011: }
1.800 albertel 4012: foreach my $group (keys(%grouproles)) {
4013: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4014: }
1.800 albertel 4015: foreach my $role (keys(%{$allroles})) {
4016: my %thesepriv;
1.941 raeburn 4017: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4018: foreach my $item (split(/:/,$$allroles{$role})) {
4019: if ($item ne '') {
4020: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4021: if ($restrictions eq '') {
4022: $thesepriv{$privilege}='F';
4023: } elsif ($thesepriv{$privilege} ne 'F') {
4024: $thesepriv{$privilege}.=$restrictions;
4025: }
4026: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4027: }
4028: }
4029: my $thesestr='';
1.800 albertel 4030: foreach my $priv (keys(%thesepriv)) {
4031: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4032: }
4033: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4034: }
4035: return ($author,$adv);
4036: }
4037:
1.994 raeburn 4038: sub role_status {
1.1002 raeburn 4039: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4040: my @pwhere = ();
4041: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4042: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4043: unless (!defined($$role) || $$role eq '') {
4044: $$where=join('.',@pwhere);
4045: $$trolecode=$$role.'.'.$$where;
4046: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4047: $$tstatus='is';
4048: if ($$tstart && $$tstart>$then) {
4049: $$tstatus='future';
1.1002 raeburn 4050: if ($$tstart && $$tstart>$refresh) {
4051: if ($$tstart<$now) {
4052: if (($$where ne '') && ($$role ne '')) {
4053: my (%allroles,%allgroups,$group_privs);
4054: my %userroles = (
4055: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4056: );
4057: my $spec=$$role.'.'.$$where;
4058: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4059: if ($$role eq 'gr') {
4060: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4061: $env{'user.name'})=@_;
4062: my ($trole) = split('_',$role,1);
4063: (undef,my $group_privs) = split(/\//,$trole);
4064: $group_privs = &unescape($group_privs);
4065: }
4066: if ($$role =~ /^cr\//) {
4067: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4068: } elsif ($$role eq 'gr') {
4069: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4070: $env{'user.name'});
4071: my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
4072: (undef,my $group_privs) = split(/\//,$trole);
4073: $group_privs = &unescape($group_privs);
4074: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4075: } else {
4076: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4077: }
4078: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
4079: &appenv(\%userroles,[$$role,'cm']);
4080: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4081: $$tstatus = 'is';
4082: }
4083: }
4084: }
1.994 raeburn 4085: }
4086: if ($$tend) {
4087: if ($$tend<$then) {
4088: $$tstatus='expired';
4089: } elsif ($$tend<$now) {
4090: $$tstatus='will_not';
4091: }
4092: }
4093: }
4094: }
4095: }
4096:
4097: sub check_adhoc_privs {
1.1002 raeburn 4098: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4099: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4100: if ($env{$cckey}) {
4101: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4102: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4103: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4104: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4105: }
4106: } else {
4107: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4108: }
4109: }
4110:
4111: sub set_adhoc_privileges {
4112: # role can be cc or ca
4113: my ($dcdom,$pickedcourse,$role) = @_;
4114: my $area = '/'.$dcdom.'/'.$pickedcourse;
4115: my $spec = $role.'.'.$area;
4116: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4117: $env{'user.name'});
4118: my %ccrole = ();
4119: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4120: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4121: &appenv(\%userroles,[$role,'cm']);
4122: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4123: &appenv( {'request.role' => $spec,
4124: 'request.role.domain' => $dcdom,
4125: 'request.course.sec' => ''
4126: }
4127: );
4128: my $tadv=0;
4129: if (&allowed('adv') eq 'F') { $tadv=1; }
4130: &appenv({'request.role.adv' => $tadv});
4131: }
4132:
1.12 www 4133: # --------------------------------------------------------------- get interface
4134:
4135: sub get {
1.131 albertel 4136: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4137: my $items='';
1.800 albertel 4138: foreach my $item (@$storearr) {
4139: $items.=&escape($item).'&';
1.191 harris41 4140: }
1.12 www 4141: $items=~s/\&$//;
1.620 albertel 4142: if (!$udomain) { $udomain=$env{'user.domain'}; }
4143: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4144: my $uhome=&homeserver($uname,$udomain);
4145:
1.133 albertel 4146: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4147: my @pairs=split(/\&/,$rep);
1.273 albertel 4148: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4149: return @pairs;
4150: }
1.15 www 4151: my %returnhash=();
1.42 www 4152: my $i=0;
1.800 albertel 4153: foreach my $item (@$storearr) {
4154: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4155: $i++;
1.191 harris41 4156: }
1.15 www 4157: return %returnhash;
1.27 www 4158: }
4159:
4160: # --------------------------------------------------------------- del interface
4161:
4162: sub del {
1.133 albertel 4163: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4164: my $items='';
1.800 albertel 4165: foreach my $item (@$storearr) {
4166: $items.=&escape($item).'&';
1.191 harris41 4167: }
1.984 neumanie 4168:
1.27 www 4169: $items=~s/\&$//;
1.620 albertel 4170: if (!$udomain) { $udomain=$env{'user.domain'}; }
4171: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4172: my $uhome=&homeserver($uname,$udomain);
4173: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4174: }
4175:
4176: # -------------------------------------------------------------- dump interface
4177:
4178: sub dump {
1.755 albertel 4179: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4180: if (!$udomain) { $udomain=$env{'user.domain'}; }
4181: if (!$uname) { $uname=$env{'user.name'}; }
4182: my $uhome=&homeserver($uname,$udomain);
4183: if ($regexp) {
4184: $regexp=&escape($regexp);
4185: } else {
4186: $regexp='.';
4187: }
4188: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4189: my @pairs=split(/\&/,$rep);
4190: my %returnhash=();
4191: foreach my $item (@pairs) {
4192: my ($key,$value)=split(/=/,$item,2);
4193: $key = &unescape($key);
4194: next if ($key =~ /^error: 2 /);
4195: $returnhash{$key}=&thaw_unescape($value);
4196: }
4197: return %returnhash;
1.407 www 4198: }
4199:
1.717 albertel 4200: # --------------------------------------------------------- dumpstore interface
4201:
4202: sub dumpstore {
4203: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4204: if (!$udomain) { $udomain=$env{'user.domain'}; }
4205: if (!$uname) { $uname=$env{'user.name'}; }
4206: my $uhome=&homeserver($uname,$udomain);
4207: if ($regexp) {
4208: $regexp=&escape($regexp);
4209: } else {
4210: $regexp='.';
4211: }
4212: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4213: my @pairs=split(/\&/,$rep);
4214: my %returnhash=();
4215: foreach my $item (@pairs) {
4216: my ($key,$value)=split(/=/,$item,2);
4217: next if ($key =~ /^error: 2 /);
4218: $returnhash{$key}=&thaw_unescape($value);
4219: }
4220: return %returnhash;
1.717 albertel 4221: }
4222:
1.407 www 4223: # -------------------------------------------------------------- keys interface
4224:
4225: sub getkeys {
4226: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4227: if (!$udomain) { $udomain=$env{'user.domain'}; }
4228: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4229: my $uhome=&homeserver($uname,$udomain);
4230: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4231: my @keyarray=();
1.800 albertel 4232: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4233: next if ($key =~ /^error: 2 /);
1.800 albertel 4234: push(@keyarray,&unescape($key));
1.407 www 4235: }
4236: return @keyarray;
1.318 matthew 4237: }
4238:
1.319 matthew 4239: # --------------------------------------------------------------- currentdump
4240: sub currentdump {
1.328 matthew 4241: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4242: $courseid = $env{'request.course.id'} if (! defined($courseid));
4243: $sdom = $env{'user.domain'} if (! defined($sdom));
4244: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4245: my $uhome = &homeserver($sname,$sdom);
4246: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4247: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4248: #
1.318 matthew 4249: my %returnhash=();
1.319 matthew 4250: #
4251: if ($rep eq "unknown_cmd") {
4252: # an old lond will not know currentdump
4253: # Do a dump and make it look like a currentdump
1.822 albertel 4254: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4255: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4256: my %hash = @tmp;
4257: @tmp=();
1.424 matthew 4258: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4259: } else {
4260: my @pairs=split(/\&/,$rep);
1.800 albertel 4261: foreach my $pair (@pairs) {
4262: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4263: my ($symb,$param) = split(/:/,$key);
4264: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4265: &thaw_unescape($value);
1.319 matthew 4266: }
1.191 harris41 4267: }
1.12 www 4268: return %returnhash;
1.424 matthew 4269: }
4270:
4271: sub convert_dump_to_currentdump{
4272: my %hash = %{shift()};
4273: my %returnhash;
4274: # Code ripped from lond, essentially. The only difference
4275: # here is the unescaping done by lonnet::dump(). Conceivably
4276: # we might run in to problems with parameter names =~ /^v\./
4277: while (my ($key,$value) = each(%hash)) {
4278: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4279: $symb = &unescape($symb);
4280: $param = &unescape($param);
1.424 matthew 4281: next if ($v eq 'version' || $symb eq 'keys');
4282: next if (exists($returnhash{$symb}) &&
4283: exists($returnhash{$symb}->{$param}) &&
4284: $returnhash{$symb}->{'v.'.$param} > $v);
4285: $returnhash{$symb}->{$param}=$value;
4286: $returnhash{$symb}->{'v.'.$param}=$v;
4287: }
4288: #
4289: # Remove all of the keys in the hashes which keep track of
4290: # the version of the parameter.
4291: while (my ($symb,$param_hash) = each(%returnhash)) {
4292: # use a foreach because we are going to delete from the hash.
4293: foreach my $key (keys(%$param_hash)) {
4294: delete($param_hash->{$key}) if ($key =~ /^v\./);
4295: }
4296: }
4297: return \%returnhash;
1.12 www 4298: }
4299:
1.627 albertel 4300: # ------------------------------------------------------ critical inc interface
4301:
4302: sub cinc {
4303: return &inc(@_,'critical');
4304: }
4305:
1.449 matthew 4306: # --------------------------------------------------------------- inc interface
4307:
4308: sub inc {
1.627 albertel 4309: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4310: if (!$udomain) { $udomain=$env{'user.domain'}; }
4311: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4312: my $uhome=&homeserver($uname,$udomain);
4313: my $items='';
4314: if (! ref($store)) {
4315: # got a single value, so use that instead
4316: $items = &escape($store).'=&';
4317: } elsif (ref($store) eq 'SCALAR') {
4318: $items = &escape($$store).'=&';
4319: } elsif (ref($store) eq 'ARRAY') {
4320: $items = join('=&',map {&escape($_);} @{$store});
4321: } elsif (ref($store) eq 'HASH') {
4322: while (my($key,$value) = each(%{$store})) {
4323: $items.= &escape($key).'='.&escape($value).'&';
4324: }
4325: }
4326: $items=~s/\&$//;
1.627 albertel 4327: if ($critical) {
4328: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4329: } else {
4330: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4331: }
1.449 matthew 4332: }
4333:
1.12 www 4334: # --------------------------------------------------------------- put interface
4335:
4336: sub put {
1.134 albertel 4337: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4338: if (!$udomain) { $udomain=$env{'user.domain'}; }
4339: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4340: my $uhome=&homeserver($uname,$udomain);
1.12 www 4341: my $items='';
1.800 albertel 4342: foreach my $item (keys(%$storehash)) {
4343: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4344: }
1.12 www 4345: $items=~s/\&$//;
1.134 albertel 4346: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4347: }
4348:
1.631 albertel 4349: # ------------------------------------------------------------ newput interface
4350:
4351: sub newput {
4352: my ($namespace,$storehash,$udomain,$uname)=@_;
4353: if (!$udomain) { $udomain=$env{'user.domain'}; }
4354: if (!$uname) { $uname=$env{'user.name'}; }
4355: my $uhome=&homeserver($uname,$udomain);
4356: my $items='';
4357: foreach my $key (keys(%$storehash)) {
4358: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4359: }
4360: $items=~s/\&$//;
4361: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4362: }
4363:
4364: # --------------------------------------------------------- putstore interface
4365:
1.524 raeburn 4366: sub putstore {
1.715 albertel 4367: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4368: if (!$udomain) { $udomain=$env{'user.domain'}; }
4369: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4370: my $uhome=&homeserver($uname,$udomain);
4371: my $items='';
1.715 albertel 4372: foreach my $key (keys(%$storehash)) {
4373: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4374: }
1.715 albertel 4375: $items=~s/\&$//;
1.716 albertel 4376: my $esc_symb=&escape($symb);
4377: my $esc_v=&escape($version);
1.715 albertel 4378: my $reply =
1.716 albertel 4379: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4380: $uhome);
4381: if ($reply eq 'unknown_cmd') {
1.716 albertel 4382: # gfall back to way things use to be done
1.715 albertel 4383: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4384: $uname);
1.524 raeburn 4385: }
1.715 albertel 4386: return $reply;
4387: }
4388:
4389: sub old_putstore {
1.716 albertel 4390: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4391: if (!$udomain) { $udomain=$env{'user.domain'}; }
4392: if (!$uname) { $uname=$env{'user.name'}; }
4393: my $uhome=&homeserver($uname,$udomain);
4394: my %newstorehash;
1.800 albertel 4395: foreach my $item (keys(%$storehash)) {
4396: my $key = $version.':'.&escape($symb).':'.$item;
4397: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4398: }
4399: my $items='';
4400: my %allitems = ();
1.800 albertel 4401: foreach my $item (keys(%newstorehash)) {
4402: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4403: my $key = $1.':keys:'.$2;
4404: $allitems{$key} .= $3.':';
4405: }
1.800 albertel 4406: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4407: }
1.800 albertel 4408: foreach my $item (keys(%allitems)) {
4409: $allitems{$item} =~ s/\:$//;
4410: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4411: }
4412: $items=~s/\&$//;
4413: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4414: }
4415:
1.47 www 4416: # ------------------------------------------------------ critical put interface
4417:
4418: sub cput {
1.134 albertel 4419: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4420: if (!$udomain) { $udomain=$env{'user.domain'}; }
4421: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4422: my $uhome=&homeserver($uname,$udomain);
1.47 www 4423: my $items='';
1.800 albertel 4424: foreach my $item (keys(%$storehash)) {
4425: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4426: }
1.47 www 4427: $items=~s/\&$//;
1.134 albertel 4428: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4429: }
4430:
4431: # -------------------------------------------------------------- eget interface
4432:
4433: sub eget {
1.133 albertel 4434: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4435: my $items='';
1.800 albertel 4436: foreach my $item (@$storearr) {
4437: $items.=&escape($item).'&';
1.191 harris41 4438: }
1.12 www 4439: $items=~s/\&$//;
1.620 albertel 4440: if (!$udomain) { $udomain=$env{'user.domain'}; }
4441: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4442: my $uhome=&homeserver($uname,$udomain);
4443: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4444: my @pairs=split(/\&/,$rep);
4445: my %returnhash=();
1.42 www 4446: my $i=0;
1.800 albertel 4447: foreach my $item (@$storearr) {
4448: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4449: $i++;
1.191 harris41 4450: }
1.12 www 4451: return %returnhash;
4452: }
4453:
1.667 albertel 4454: # ------------------------------------------------------------ tmpput interface
4455: sub tmpput {
1.802 raeburn 4456: my ($storehash,$server,$context)=@_;
1.667 albertel 4457: my $items='';
1.800 albertel 4458: foreach my $item (keys(%$storehash)) {
4459: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4460: }
4461: $items=~s/\&$//;
1.802 raeburn 4462: if (defined($context)) {
4463: $items .= ':'.&escape($context);
4464: }
1.667 albertel 4465: return &reply("tmpput:$items",$server);
4466: }
4467:
4468: # ------------------------------------------------------------ tmpget interface
4469: sub tmpget {
1.688 albertel 4470: my ($token,$server)=@_;
4471: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4472: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4473: my %returnhash;
4474: foreach my $item (split(/\&/,$rep)) {
4475: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4476: next if ($key =~ /^error: 2 /);
1.667 albertel 4477: $returnhash{&unescape($key)}=&thaw_unescape($value);
4478: }
4479: return %returnhash;
4480: }
4481:
1.688 albertel 4482: # ------------------------------------------------------------ tmpget interface
4483: sub tmpdel {
4484: my ($token,$server)=@_;
4485: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4486: return &reply("tmpdel:$token",$server);
4487: }
4488:
1.765 albertel 4489: # -------------------------------------------------- portfolio access checking
4490:
4491: sub portfolio_access {
1.766 albertel 4492: my ($requrl) = @_;
1.765 albertel 4493: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4494: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4495: if ($result) {
4496: my %setters;
4497: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4498: my ($startblock,$endblock) =
4499: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4500: if ($startblock && $endblock) {
4501: return 'B';
4502: }
4503: } else {
4504: my ($startblock,$endblock) =
4505: &Apache::loncommon::blockcheck(\%setters,'port');
4506: if ($startblock && $endblock) {
4507: return 'B';
4508: }
4509: }
4510: }
1.765 albertel 4511: if ($result eq 'ok') {
1.766 albertel 4512: return 'F';
1.765 albertel 4513: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4514: return 'A';
1.765 albertel 4515: }
1.766 albertel 4516: return '';
1.765 albertel 4517: }
4518:
4519: sub get_portfolio_access {
1.767 albertel 4520: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4521:
4522: if (!ref($access_hash)) {
4523: my $current_perms = &get_portfile_permissions($udom,$unum);
4524: my %access_controls = &get_access_controls($current_perms,$group,
4525: $file_name);
4526: $access_hash = $access_controls{$file_name};
4527: }
4528:
1.765 albertel 4529: my ($public,$guest,@domains,@users,@courses,@groups);
4530: my $now = time;
4531: if (ref($access_hash) eq 'HASH') {
4532: foreach my $key (keys(%{$access_hash})) {
4533: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4534: if ($start > $now) {
4535: next;
4536: }
4537: if ($end && $end<$now) {
4538: next;
4539: }
4540: if ($scope eq 'public') {
4541: $public = $key;
4542: last;
4543: } elsif ($scope eq 'guest') {
4544: $guest = $key;
4545: } elsif ($scope eq 'domains') {
4546: push(@domains,$key);
4547: } elsif ($scope eq 'users') {
4548: push(@users,$key);
4549: } elsif ($scope eq 'course') {
4550: push(@courses,$key);
4551: } elsif ($scope eq 'group') {
4552: push(@groups,$key);
4553: }
4554: }
4555: if ($public) {
4556: return 'ok';
4557: }
4558: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4559: if ($guest) {
4560: return $guest;
4561: }
4562: } else {
4563: if (@domains > 0) {
4564: foreach my $domkey (@domains) {
4565: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4566: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4567: return 'ok';
4568: }
4569: }
4570: }
4571: }
4572: if (@users > 0) {
4573: foreach my $userkey (@users) {
1.865 raeburn 4574: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4575: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4576: if (ref($item) eq 'HASH') {
4577: if (($item->{'uname'} eq $env{'user.name'}) &&
4578: ($item->{'udom'} eq $env{'user.domain'})) {
4579: return 'ok';
4580: }
4581: }
4582: }
4583: }
1.765 albertel 4584: }
4585: }
4586: my %roleshash;
4587: my @courses_and_groups = @courses;
4588: push(@courses_and_groups,@groups);
4589: if (@courses_and_groups > 0) {
4590: my (%allgroups,%allroles);
4591: my ($start,$end,$role,$sec,$group);
4592: foreach my $envkey (%env) {
1.811 albertel 4593: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4594: my $cid = $2.'_'.$3;
4595: if ($1 eq 'gr') {
4596: $group = $4;
4597: $allgroups{$cid}{$group} = $env{$envkey};
4598: } else {
4599: if ($4 eq '') {
4600: $sec = 'none';
4601: } else {
4602: $sec = $4;
4603: }
4604: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4605: }
1.811 albertel 4606: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4607: my $cid = $2.'_'.$3;
4608: if ($4 eq '') {
4609: $sec = 'none';
4610: } else {
4611: $sec = $4;
4612: }
4613: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4614: }
4615: }
4616: if (keys(%allroles) == 0) {
4617: return;
4618: }
4619: foreach my $key (@courses_and_groups) {
4620: my %content = %{$$access_hash{$key}};
4621: my $cnum = $content{'number'};
4622: my $cdom = $content{'domain'};
4623: my $cid = $cdom.'_'.$cnum;
4624: if (!exists($allroles{$cid})) {
4625: next;
4626: }
4627: foreach my $role_id (keys(%{$content{'roles'}})) {
4628: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4629: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4630: my @status = @{$content{'roles'}{$role_id}{'access'}};
4631: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4632: foreach my $role (keys(%{$allroles{$cid}})) {
4633: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4634: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4635: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4636: if (grep/^all$/,@sections) {
4637: return 'ok';
4638: } else {
4639: if (grep/^$sec$/,@sections) {
4640: return 'ok';
4641: }
4642: }
4643: }
4644: }
4645: if (keys(%{$allgroups{$cid}}) == 0) {
4646: if (grep/^none$/,@groups) {
4647: return 'ok';
4648: }
4649: } else {
4650: if (grep/^all$/,@groups) {
4651: return 'ok';
4652: }
4653: foreach my $group (keys(%{$allgroups{$cid}})) {
4654: if (grep/^$group$/,@groups) {
4655: return 'ok';
4656: }
4657: }
4658: }
4659: }
4660: }
4661: }
4662: }
4663: }
4664: if ($guest) {
4665: return $guest;
4666: }
4667: }
4668: }
4669: return;
4670: }
4671:
4672: sub course_group_datechecker {
4673: my ($dates,$now,$status) = @_;
4674: my ($start,$end) = split(/\./,$dates);
4675: if (!$start && !$end) {
4676: return 'ok';
4677: }
4678: if (grep/^active$/,@{$status}) {
4679: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4680: return 'ok';
4681: }
4682: }
4683: if (grep/^previous$/,@{$status}) {
4684: if ($end > $now ) {
4685: return 'ok';
4686: }
4687: }
4688: if (grep/^future$/,@{$status}) {
4689: if ($start > $now) {
4690: return 'ok';
4691: }
4692: }
4693: return;
4694: }
4695:
4696: sub parse_portfolio_url {
4697: my ($url) = @_;
4698:
4699: my ($type,$udom,$unum,$group,$file_name);
4700:
1.823 albertel 4701: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4702: $type = 1;
4703: $udom = $1;
4704: $unum = $2;
4705: $file_name = $3;
1.823 albertel 4706: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4707: $type = 2;
4708: $udom = $1;
4709: $unum = $2;
4710: $group = $3;
4711: $file_name = $3.'/'.$4;
4712: }
4713: if (wantarray) {
4714: return ($type,$udom,$unum,$file_name,$group);
4715: }
4716: return $type;
4717: }
4718:
4719: sub is_portfolio_url {
4720: my ($url) = @_;
4721: return scalar(&parse_portfolio_url($url));
4722: }
4723:
1.798 raeburn 4724: sub is_portfolio_file {
4725: my ($file) = @_;
1.820 raeburn 4726: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4727: return 1;
4728: }
4729: return;
4730: }
4731:
1.976 raeburn 4732: sub usertools_access {
1.985 raeburn 4733: my ($uname,$udom,$tool,$action,$context) = @_;
4734: my ($access,%tools);
4735: if ($context eq '') {
4736: $context = 'tools';
4737: }
4738: if ($context eq 'requestcourses') {
4739: %tools = (
4740: official => 1,
4741: unofficial => 1,
1.1006 raeburn 4742: community => 1,
1.985 raeburn 4743: );
4744: } else {
4745: %tools = (
4746: aboutme => 1,
4747: blog => 1,
4748: portfolio => 1,
4749: );
4750: }
1.976 raeburn 4751: return if (!defined($tools{$tool}));
4752:
4753: if ((!defined($udom)) || (!defined($uname))) {
4754: $udom = $env{'user.domain'};
4755: $uname = $env{'user.name'};
4756: }
4757:
1.978 raeburn 4758: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4759: if ($action ne 'reload') {
1.985 raeburn 4760: if ($context eq 'requestcourses') {
4761: return $env{'environment.canrequest.'.$tool};
4762: } else {
4763: return $env{'environment.availabletools.'.$tool};
4764: }
4765: }
1.976 raeburn 4766: }
4767:
4768: my ($toolstatus,$inststatus);
4769:
1.985 raeburn 4770: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4771: ($action ne 'reload')) {
4772: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4773: $inststatus = $env{'environment.inststatus'};
4774: } else {
1.985 raeburn 4775: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
4776: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4777: $inststatus = $userenv{'inststatus'};
4778: }
4779:
4780: if ($toolstatus ne '') {
4781: if ($toolstatus) {
4782: $access = 1;
4783: } else {
4784: $access = 0;
4785: }
4786: return $access;
4787: }
4788:
4789: my $is_adv = &is_advanced_user($udom,$uname);
4790: my %domdef = &get_domain_defaults($udom);
4791: if (ref($domdef{$tool}) eq 'HASH') {
4792: if ($is_adv) {
4793: if ($domdef{$tool}{'_LC_adv'} ne '') {
4794: if ($domdef{$tool}{'_LC_adv'}) {
4795: $access = 1;
4796: } else {
4797: $access = 0;
4798: }
4799: return $access;
4800: }
4801: }
4802: if ($inststatus ne '') {
4803: my ($hasaccess,$hasnoaccess);
4804: foreach my $affiliation (split(/:/,$inststatus)) {
4805: if ($domdef{$tool}{$affiliation} ne '') {
4806: if ($domdef{$tool}{$affiliation}) {
4807: $hasaccess = 1;
4808: } else {
4809: $hasnoaccess = 1;
4810: }
4811: }
4812: }
4813: if ($hasaccess || $hasnoaccess) {
4814: if ($hasaccess) {
4815: $access = 1;
4816: } elsif ($hasnoaccess) {
4817: $access = 0;
4818: }
4819: return $access;
4820: }
4821: } else {
4822: if ($domdef{$tool}{'default'} ne '') {
4823: if ($domdef{$tool}{'default'}) {
4824: $access = 1;
4825: } elsif ($domdef{$tool}{'default'} == 0) {
4826: $access = 0;
4827: }
4828: return $access;
4829: }
4830: }
4831: } else {
1.985 raeburn 4832: if ($context eq 'tools') {
4833: $access = 1;
4834: } else {
4835: $access = 0;
4836: }
1.976 raeburn 4837: return $access;
4838: }
4839: }
4840:
4841: sub is_advanced_user {
4842: my ($udom,$uname) = @_;
4843: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4844: my %allroles;
4845: my $is_adv;
4846: foreach my $role (keys(%roleshash)) {
4847: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4848: my $area = '/'.$tdomain.'/'.$trest;
4849: if ($sec ne '') {
4850: $area .= '/'.$sec;
4851: }
4852: if (($area ne '') && ($trole ne '')) {
4853: my $spec=$trole.'.'.$area;
4854: if ($trole =~ /^cr\//) {
4855: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4856: } elsif ($trole ne 'gr') {
4857: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4858: }
4859: }
4860: }
4861: foreach my $role (keys(%allroles)) {
4862: last if ($is_adv);
4863: foreach my $item (split(/:/,$allroles{$role})) {
4864: if ($item ne '') {
4865: my ($privilege,$restrictions)=split(/&/,$item);
4866: if ($privilege eq 'adv') {
4867: $is_adv = 1;
4868: last;
4869: }
4870: }
4871: }
4872: }
4873: return $is_adv;
4874: }
1.798 raeburn 4875:
1.341 www 4876: # ---------------------------------------------- Custom access rule evaluation
4877:
4878: sub customaccess {
4879: my ($priv,$uri)=@_;
1.807 albertel 4880: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4881: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4882: $udom = &LONCAPA::clean_domain($udom);
4883: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4884: my $access=0;
1.800 albertel 4885: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4886: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4887: if ($type eq 'user') {
4888: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4889: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4890: if ($tdom) {
4891: if ($tdom ne $env{'user.domain'}) { next; }
4892: }
1.896 albertel 4893: if ($tuname) {
4894: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4895: }
4896: $access=($effect eq 'allow');
4897: last;
4898: }
4899: } else {
4900: if ($role) {
4901: if ($role ne $urole) { next; }
4902: }
4903: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4904: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4905: if ($tdom) {
4906: if ($tdom ne $udom) { next; }
4907: }
4908: if ($tcrs) {
4909: if ($tcrs ne $ucrs) { next; }
4910: }
4911: if ($tsec) {
4912: if ($tsec ne $usec) { next; }
4913: }
4914: $access=($effect eq 'allow');
4915: last;
4916: }
4917: if ($realm eq '' && $role eq '') {
4918: $access=($effect eq 'allow');
4919: }
1.402 bowersj2 4920: }
1.341 www 4921: }
4922: return $access;
4923: }
4924:
1.103 harris41 4925: # ------------------------------------------------- Check for a user privilege
1.12 www 4926:
4927: sub allowed {
1.810 raeburn 4928: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4929: my $ver_orguri=$uri;
1.439 www 4930: $uri=&deversion($uri);
1.152 www 4931: my $orguri=$uri;
1.52 www 4932: $uri=&declutter($uri);
1.809 raeburn 4933:
1.810 raeburn 4934: if ($priv eq 'evb') {
4935: # Evade communication block restrictions for specified role in a course
4936: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4937: return $1;
4938: } else {
4939: return;
4940: }
4941: }
4942:
1.620 albertel 4943: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4944: # Free bre access to adm and meta resources
1.775 albertel 4945: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4946: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4947: && ($priv eq 'bre')) {
1.14 www 4948: return 'F';
1.159 www 4949: }
4950:
1.545 banghart 4951: # Free bre access to user's own portfolio contents
1.714 raeburn 4952: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4953: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4954: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4955: my %setters;
4956: my ($startblock,$endblock) =
4957: &Apache::loncommon::blockcheck(\%setters,'port');
4958: if ($startblock && $endblock) {
4959: return 'B';
4960: } else {
4961: return 'F';
4962: }
1.545 banghart 4963: }
4964:
1.762 raeburn 4965: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4966: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4967: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4968: if (exists($env{'request.course.id'})) {
4969: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4970: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4971: if (($domain eq $cdom) && ($name eq $cnum)) {
4972: my $courseprivid=$env{'request.course.id'};
4973: $courseprivid=~s/\_/\//;
4974: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4975: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4976: return $1;
1.762 raeburn 4977: } else {
4978: if ($env{'request.course.sec'}) {
4979: $courseprivid.='/'.$env{'request.course.sec'};
4980: }
4981: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4982: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4983: return $2;
4984: }
1.714 raeburn 4985: }
4986: }
4987: }
4988: }
4989:
1.159 www 4990: # Free bre to public access
4991:
4992: if ($priv eq 'bre') {
1.238 www 4993: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4994: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4995: return 'F';
4996: }
1.238 www 4997: if ($copyright eq 'priv') {
4998: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4999: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5000: return '';
5001: }
5002: }
5003: if ($copyright eq 'domain') {
5004: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5005: unless (($env{'user.domain'} eq $1) ||
5006: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5007: return '';
5008: }
1.262 matthew 5009: }
1.620 albertel 5010: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5011: # Library role, so allow browsing of resources in this domain.
5012: return 'F';
1.238 www 5013: }
1.341 www 5014: if ($copyright eq 'custom') {
5015: unless (&customaccess($priv,$uri)) { return ''; }
5016: }
1.14 www 5017: }
1.264 matthew 5018: # Domain coordinator is trying to create a course
1.620 albertel 5019: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5020: # uri is the requested domain in this case.
5021: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5022: # a role of dc for the domain in question.
1.620 albertel 5023: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5024: }
1.29 www 5025:
1.52 www 5026: my $thisallowed='';
5027: my $statecond=0;
5028: my $courseprivid='';
5029:
5030: # Course
5031:
1.620 albertel 5032: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5033: $thisallowed.=$1;
5034: }
1.29 www 5035:
1.52 www 5036: # Domain
5037:
1.620 albertel 5038: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5039: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 5040: $thisallowed.=$1;
5041: }
1.52 www 5042:
5043: # Course: uri itself is a course
1.66 www 5044: my $courseuri=$uri;
5045: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5046: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5047:
1.620 albertel 5048: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5049: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 5050: $thisallowed.=$1;
5051: }
1.29 www 5052:
1.665 albertel 5053: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5054: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5055: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5056: $thisallowed='';
1.671 raeburn 5057: my ($match)=&is_on_map($uri);
5058: if ($match) {
5059: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5060: =~/\Q$priv\E\&([^\:]*)/) {
5061: $thisallowed.=$1;
5062: }
5063: } else {
1.705 albertel 5064: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5065: if ($refuri) {
5066: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5067: $thisallowed='F';
1.671 raeburn 5068: } else {
5069: $refuri=&declutter($refuri);
5070: my ($match) = &is_on_map($refuri);
5071: if ($match) {
5072: $thisallowed='F';
5073: }
1.669 raeburn 5074: }
1.671 raeburn 5075: }
5076: }
1.314 www 5077: }
1.492 albertel 5078:
1.766 albertel 5079: if ($priv eq 'bre'
5080: && $thisallowed ne 'F'
5081: && $thisallowed ne '2'
5082: && &is_portfolio_url($uri)) {
5083: $thisallowed = &portfolio_access($uri);
5084: }
5085:
1.52 www 5086: # Full access at system, domain or course-wide level? Exit.
1.29 www 5087: if ($thisallowed=~/F/) {
5088: return 'F';
5089: }
5090:
1.52 www 5091: # If this is generating or modifying users, exit with special codes
1.29 www 5092:
1.643 www 5093: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5094: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5095: my ($audom,$auname)=split('/',$uri);
1.643 www 5096: # no author name given, so this just checks on the general right to make a co-author in this domain
5097: unless ($auname) { return $thisallowed; }
5098: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5099: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5100: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5101: ($audom ne $env{'request.role.domain'}))) { return ''; }
5102: }
1.52 www 5103: return $thisallowed;
5104: }
5105: #
1.103 harris41 5106: # Gathered so far: system, domain and course wide privileges
1.52 www 5107: #
5108: # Course: See if uri or referer is an individual resource that is part of
5109: # the course
5110:
1.620 albertel 5111: if ($env{'request.course.id'}) {
1.232 www 5112:
1.620 albertel 5113: $courseprivid=$env{'request.course.id'};
5114: if ($env{'request.course.sec'}) {
5115: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5116: }
5117: $courseprivid=~s/\_/\//;
5118: my $checkreferer=1;
1.232 www 5119: my ($match,$cond)=&is_on_map($uri);
5120: if ($match) {
5121: $statecond=$cond;
1.620 albertel 5122: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5123: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5124: $thisallowed.=$1;
5125: $checkreferer=0;
5126: }
1.29 www 5127: }
1.83 www 5128:
1.148 www 5129: if ($checkreferer) {
1.620 albertel 5130: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5131: unless ($refuri) {
1.800 albertel 5132: foreach my $key (keys(%env)) {
5133: if ($key=~/^httpref\..*\*/) {
5134: my $pattern=$key;
1.156 www 5135: $pattern=~s/^httpref\.\/res\///;
1.148 www 5136: $pattern=~s/\*/\[\^\/\]\+/g;
5137: $pattern=~s/\//\\\//g;
1.152 www 5138: if ($orguri=~/$pattern/) {
1.800 albertel 5139: $refuri=$env{$key};
1.148 www 5140: }
5141: }
1.191 harris41 5142: }
1.148 www 5143: }
1.232 www 5144:
1.148 www 5145: if ($refuri) {
1.152 www 5146: $refuri=&declutter($refuri);
1.232 www 5147: my ($match,$cond)=&is_on_map($refuri);
5148: if ($match) {
5149: my $refstatecond=$cond;
1.620 albertel 5150: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5151: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5152: $thisallowed.=$1;
1.53 www 5153: $uri=$refuri;
5154: $statecond=$refstatecond;
1.52 www 5155: }
5156: }
1.148 www 5157: }
1.29 www 5158: }
1.52 www 5159: }
1.29 www 5160:
1.52 www 5161: #
1.103 harris41 5162: # Gathered now: all privileges that could apply, and condition number
1.52 www 5163: #
5164: #
5165: # Full or no access?
5166: #
1.29 www 5167:
1.52 www 5168: if ($thisallowed=~/F/) {
5169: return 'F';
5170: }
1.29 www 5171:
1.52 www 5172: unless ($thisallowed) {
5173: return '';
5174: }
1.29 www 5175:
1.52 www 5176: # Restrictions exist, deal with them
5177: #
5178: # C:according to course preferences
5179: # R:according to resource settings
5180: # L:unless locked
5181: # X:according to user session state
5182: #
5183:
5184: # Possibly locked functionality, check all courses
1.54 www 5185: # Locks might take effect only after 10 minutes cache expiration for other
5186: # courses, and 2 minutes for current course
1.52 www 5187:
5188: my $envkey;
5189: if ($thisallowed=~/L/) {
1.1000 raeburn 5190: foreach $envkey (keys(%env)) {
1.54 www 5191: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5192: my $courseid=$2;
5193: my $roleid=$1.'.'.$2;
1.92 www 5194: $courseid=~s/^\///;
1.54 www 5195: my $expiretime=600;
1.620 albertel 5196: if ($env{'request.role'} eq $roleid) {
1.54 www 5197: $expiretime=120;
5198: }
5199: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5200: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5201: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5202: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5203: }
1.620 albertel 5204: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5205: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5206: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5207: &log($env{'user.domain'},$env{'user.name'},
5208: $env{'user.home'},
1.57 www 5209: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5210: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5211: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5212: return '';
5213: }
5214: }
1.620 albertel 5215: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5216: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5217: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5218: &log($env{'user.domain'},$env{'user.name'},
5219: $env{'user.home'},
1.57 www 5220: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5221: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5222: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5223: return '';
5224: }
5225: }
5226: }
1.29 www 5227: }
1.52 www 5228: }
5229:
5230: #
5231: # Rest of the restrictions depend on selected course
5232: #
5233:
1.620 albertel 5234: unless ($env{'request.course.id'}) {
1.766 albertel 5235: if ($thisallowed eq 'A') {
5236: return 'A';
1.814 raeburn 5237: } elsif ($thisallowed eq 'B') {
5238: return 'B';
1.766 albertel 5239: } else {
5240: return '1';
5241: }
1.52 www 5242: }
1.29 www 5243:
1.52 www 5244: #
5245: # Now user is definitely in a course
5246: #
1.53 www 5247:
5248:
5249: # Course preferences
5250:
5251: if ($thisallowed=~/C/) {
1.620 albertel 5252: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5253: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5254: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5255: =~/\Q$rolecode\E/) {
1.689 albertel 5256: if ($priv ne 'pch') {
5257: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5258: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5259: $env{'request.course.id'});
5260: }
1.237 www 5261: return '';
5262: }
5263:
1.620 albertel 5264: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5265: =~/\Q$unamedom\E/) {
1.689 albertel 5266: if ($priv ne 'pch') {
5267: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5268: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5269: $env{'request.course.id'});
5270: }
1.54 www 5271: return '';
5272: }
1.53 www 5273: }
5274:
5275: # Resource preferences
5276:
5277: if ($thisallowed=~/R/) {
1.620 albertel 5278: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5279: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5280: if ($priv ne 'pch') {
5281: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5282: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5283: }
5284: return '';
1.54 www 5285: }
1.53 www 5286: }
1.30 www 5287:
1.246 www 5288: # Restricted by state or randomout?
1.30 www 5289:
1.52 www 5290: if ($thisallowed=~/X/) {
1.620 albertel 5291: if ($env{'acc.randomout'}) {
1.579 albertel 5292: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5293: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5294: return '';
5295: }
1.247 www 5296: }
5297: if (&condval($statecond)) {
1.52 www 5298: return '2';
5299: } else {
5300: return '';
5301: }
5302: }
1.30 www 5303:
1.766 albertel 5304: if ($thisallowed eq 'A') {
5305: return 'A';
1.814 raeburn 5306: } elsif ($thisallowed eq 'B') {
5307: return 'B';
1.766 albertel 5308: }
1.52 www 5309: return 'F';
1.232 www 5310: }
5311:
1.710 albertel 5312: sub split_uri_for_cond {
5313: my $uri=&deversion(&declutter(shift));
5314: my @uriparts=split(/\//,$uri);
5315: my $filename=pop(@uriparts);
5316: my $pathname=join('/',@uriparts);
5317: return ($pathname,$filename);
5318: }
1.232 www 5319: # --------------------------------------------------- Is a resource on the map?
5320:
5321: sub is_on_map {
1.710 albertel 5322: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5323: #Trying to find the conditional for the file
1.620 albertel 5324: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5325: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5326: if ($match) {
1.289 bowersj2 5327: return (1,$1);
5328: } else {
1.434 www 5329: return (0,0);
1.289 bowersj2 5330: }
1.12 www 5331: }
5332:
1.427 www 5333: # --------------------------------------------------------- Get symb from alias
5334:
5335: sub get_symb_from_alias {
5336: my $symb=shift;
5337: my ($map,$resid,$url)=&decode_symb($symb);
5338: # Already is a symb
5339: if ($url) { return $symb; }
5340: # Must be an alias
5341: my $aliassymb='';
5342: my %bighash;
1.620 albertel 5343: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5344: &GDBM_READER(),0640)) {
5345: my $rid=$bighash{'mapalias_'.$symb};
5346: if ($rid) {
5347: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5348: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5349: $resid,$bighash{'src_'.$rid});
1.427 www 5350: }
5351: untie %bighash;
5352: }
5353: return $aliassymb;
5354: }
5355:
1.12 www 5356: # ----------------------------------------------------------------- Define Role
5357:
5358: sub definerole {
5359: if (allowed('mcr','/')) {
5360: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5361: foreach my $role (split(':',$sysrole)) {
5362: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5363: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5364: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5365: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5366: return "refused:s:$crole&$cqual";
5367: }
5368: }
1.191 harris41 5369: }
1.800 albertel 5370: foreach my $role (split(':',$domrole)) {
5371: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5372: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5373: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5374: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5375: return "refused:d:$crole&$cqual";
5376: }
5377: }
1.191 harris41 5378: }
1.800 albertel 5379: foreach my $role (split(':',$courole)) {
5380: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5381: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5382: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5383: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5384: return "refused:c:$crole&$cqual";
5385: }
5386: }
1.191 harris41 5387: }
1.620 albertel 5388: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5389: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5390: "rolesdef_$rolename=".
5391: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5392: return reply($command,$env{'user.home'});
1.12 www 5393: } else {
5394: return 'refused';
5395: }
1.105 harris41 5396: }
5397:
5398: # ---------------- Make a metadata query against the network of library servers
5399:
5400: sub metadata_query {
1.244 matthew 5401: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5402: my %rhash;
1.845 albertel 5403: my %libserv = &all_library();
1.244 matthew 5404: my @server_list = (defined($server_array) ? @$server_array
5405: : keys(%libserv) );
5406: for my $server (@server_list) {
1.118 harris41 5407: unless ($custom or $customshow) {
5408: my $reply=&reply("querysend:".&escape($query),$server);
5409: $rhash{$server}=$reply;
5410: }
5411: else {
5412: my $reply=&reply("querysend:".&escape($query).':'.
5413: &escape($custom).':'.&escape($customshow),
5414: $server);
5415: $rhash{$server}=$reply;
5416: }
1.112 harris41 5417: }
1.118 harris41 5418: return \%rhash;
1.240 www 5419: }
5420:
5421: # ----------------------------------------- Send log queries and wait for reply
5422:
5423: sub log_query {
5424: my ($uname,$udom,$query,%filters)=@_;
5425: my $uhome=&homeserver($uname,$udom);
5426: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5427: my $uhost=&hostname($uhome);
1.800 albertel 5428: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5429: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5430: $uhome);
1.479 albertel 5431: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5432: return get_query_reply($queryid);
5433: }
5434:
1.818 raeburn 5435: # -------------------------- Update MySQL table for portfolio file
5436:
5437: sub update_portfolio_table {
1.821 raeburn 5438: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5439: if ($group ne '') {
5440: $file_name =~s /^\Q$group\E//;
5441: }
1.818 raeburn 5442: my $homeserver = &homeserver($uname,$udom);
5443: my $queryid=
1.821 raeburn 5444: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5445: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5446: my $reply = &get_query_reply($queryid);
5447: return $reply;
5448: }
5449:
1.899 raeburn 5450: # -------------------------- Update MySQL allusers table
5451:
5452: sub update_allusers_table {
5453: my ($uname,$udom,$names) = @_;
5454: my $homeserver = &homeserver($uname,$udom);
5455: my $queryid=
5456: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5457: 'lastname='.&escape($names->{'lastname'}).'%%'.
5458: 'firstname='.&escape($names->{'firstname'}).'%%'.
5459: 'middlename='.&escape($names->{'middlename'}).'%%'.
5460: 'generation='.&escape($names->{'generation'}).'%%'.
5461: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5462: 'id='.&escape($names->{'id'}),$homeserver);
5463: my $reply = &get_query_reply($queryid);
5464: return $reply;
5465: }
5466:
1.508 raeburn 5467: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5468:
5469: sub fetch_enrollment_query {
1.511 raeburn 5470: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5471: my $homeserver;
1.547 raeburn 5472: my $maxtries = 1;
1.508 raeburn 5473: if ($context eq 'automated') {
5474: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5475: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5476: } else {
5477: $homeserver = &homeserver($cnum,$dom);
5478: }
1.838 albertel 5479: my $host=&hostname($homeserver);
1.506 raeburn 5480: my $cmd = '';
1.1000 raeburn 5481: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5482: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5483: }
5484: $cmd =~ s/%%$//;
5485: $cmd = &escape($cmd);
5486: my $query = 'fetchenrollment';
1.620 albertel 5487: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5488: unless ($queryid=~/^\Q$host\E\_/) {
5489: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5490: return 'error: '.$queryid;
5491: }
1.506 raeburn 5492: my $reply = &get_query_reply($queryid);
1.547 raeburn 5493: my $tries = 1;
5494: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5495: $reply = &get_query_reply($queryid);
5496: $tries ++;
5497: }
1.526 raeburn 5498: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5499: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5500: } else {
1.901 albertel 5501: my @responses = split(/:/,$reply);
1.515 raeburn 5502: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5503: foreach my $line (@responses) {
5504: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5505: $$replyref{$key} = $value;
5506: }
5507: } else {
1.506 raeburn 5508: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5509: foreach my $line (@responses) {
5510: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5511: $$replyref{$key} = $value;
5512: if ($value > 0) {
1.800 albertel 5513: foreach my $item (@{$$affiliatesref{$key}}) {
5514: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5515: my $destname = $pathname.'/'.$filename;
5516: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5517: if ($xml_classlist =~ /^error/) {
5518: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5519: } else {
1.506 raeburn 5520: if ( open(FILE,">$destname") ) {
5521: print FILE &unescape($xml_classlist);
5522: close(FILE);
1.526 raeburn 5523: } else {
5524: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5525: }
5526: }
5527: }
5528: }
5529: }
5530: }
5531: return 'ok';
5532: }
5533: return 'error';
5534: }
5535:
1.242 www 5536: sub get_query_reply {
5537: my $queryid=shift;
1.240 www 5538: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5539: my $reply='';
5540: for (1..100) {
5541: sleep 2;
5542: if (-e $replyfile.'.end') {
1.448 albertel 5543: if (open(my $fh,$replyfile)) {
1.904 albertel 5544: $reply = join('',<$fh>);
5545: close($fh);
1.240 www 5546: } else { return 'error: reply_file_error'; }
1.242 www 5547: return &unescape($reply);
5548: }
1.240 www 5549: }
1.242 www 5550: return 'timeout:'.$queryid;
1.240 www 5551: }
5552:
5553: sub courselog_query {
1.241 www 5554: #
5555: # possible filters:
5556: # url: url or symb
5557: # username
5558: # domain
5559: # action: view, submit, grade
5560: # start: timestamp
5561: # end: timestamp
5562: #
1.240 www 5563: my (%filters)=@_;
1.620 albertel 5564: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5565: if ($filters{'url'}) {
5566: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5567: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5568: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5569: }
1.620 albertel 5570: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5571: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5572: return &log_query($cname,$cdom,'courselog',%filters);
5573: }
5574:
5575: sub userlog_query {
1.858 raeburn 5576: #
5577: # possible filters:
5578: # action: log check role
5579: # start: timestamp
5580: # end: timestamp
5581: #
1.240 www 5582: my ($uname,$udom,%filters)=@_;
5583: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5584: }
5585:
1.506 raeburn 5586: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5587:
5588: sub auto_run {
1.508 raeburn 5589: my ($cnum,$cdom) = @_;
1.876 raeburn 5590: my $response = 0;
5591: my $settings;
5592: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5593: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5594: $settings = $domconfig{'autoenroll'};
5595: if ($settings->{'run'} eq '1') {
5596: $response = 1;
5597: }
5598: } else {
1.934 raeburn 5599: my $homeserver;
5600: if (&is_course($cdom,$cnum)) {
5601: $homeserver = &homeserver($cnum,$cdom);
5602: } else {
5603: $homeserver = &domain($cdom,'primary');
5604: }
5605: if ($homeserver ne 'no_host') {
5606: $response = &reply('autorun:'.$cdom,$homeserver);
5607: }
1.876 raeburn 5608: }
1.506 raeburn 5609: return $response;
5610: }
1.776 albertel 5611:
1.506 raeburn 5612: sub auto_get_sections {
1.508 raeburn 5613: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5614: my $homeserver;
5615: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5616: $homeserver = &homeserver($cnum,$cdom);
5617: }
5618: if (!defined($homeserver)) {
5619: if ($cdom =~ /^$match_domain$/) {
5620: $homeserver = &domain($cdom,'primary');
5621: }
5622: }
5623: my @secs;
5624: if (defined($homeserver)) {
5625: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5626: unless ($response eq 'refused') {
5627: @secs = split(/:/,$response);
5628: }
1.506 raeburn 5629: }
5630: return @secs;
5631: }
1.776 albertel 5632:
1.506 raeburn 5633: sub auto_new_course {
1.508 raeburn 5634: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5635: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5636: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5637: return $response;
5638: }
1.776 albertel 5639:
1.506 raeburn 5640: sub auto_validate_courseID {
1.508 raeburn 5641: my ($cnum,$cdom,$inst_course_id) = @_;
5642: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5643: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5644: return $response;
5645: }
1.776 albertel 5646:
1.1007 raeburn 5647: sub auto_validate_instcode {
5648: my ($cnum,$cdom,$instcode,$owner) = @_;
5649: my ($homeserver,$response);
5650: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5651: $homeserver = &homeserver($cnum,$cdom);
5652: }
5653: if (!defined($homeserver)) {
5654: if ($cdom =~ /^$match_domain$/) {
5655: $homeserver = &domain($cdom,'primary');
5656: }
5657: }
5658: my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5659: &escape($instcode).':'.&escape($owner),$homeserver));
5660: return $response;
5661: }
5662:
1.506 raeburn 5663: sub auto_create_password {
1.873 raeburn 5664: my ($cnum,$cdom,$authparam,$udom) = @_;
5665: my ($homeserver,$response);
1.506 raeburn 5666: my $create_passwd = 0;
5667: my $authchk = '';
1.873 raeburn 5668: if ($udom =~ /^$match_domain$/) {
5669: $homeserver = &domain($udom,'primary');
5670: }
5671: if ($homeserver eq '') {
5672: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5673: $homeserver = &homeserver($cnum,$cdom);
5674: }
5675: }
5676: if ($homeserver eq '') {
5677: $authchk = 'nodomain';
1.506 raeburn 5678: } else {
1.873 raeburn 5679: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5680: if ($response eq 'refused') {
5681: $authchk = 'refused';
5682: } else {
1.901 albertel 5683: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5684: }
1.506 raeburn 5685: }
5686: return ($authparam,$create_passwd,$authchk);
5687: }
5688:
1.706 raeburn 5689: sub auto_photo_permission {
5690: my ($cnum,$cdom,$students) = @_;
5691: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5692: my ($outcome,$perm_reqd,$conditions) =
5693: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5694: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5695: return (undef,undef);
5696: }
1.706 raeburn 5697: return ($outcome,$perm_reqd,$conditions);
5698: }
5699:
5700: sub auto_checkphotos {
5701: my ($uname,$udom,$pid) = @_;
5702: my $homeserver = &homeserver($uname,$udom);
5703: my ($result,$resulttype);
5704: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5705: &escape($uname).':'.&escape($pid),
5706: $homeserver));
1.709 albertel 5707: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5708: return (undef,undef);
5709: }
1.706 raeburn 5710: if ($outcome) {
5711: ($result,$resulttype) = split(/:/,$outcome);
5712: }
5713: return ($result,$resulttype);
5714: }
5715:
5716: sub auto_photochoice {
5717: my ($cnum,$cdom) = @_;
5718: my $homeserver = &homeserver($cnum,$cdom);
5719: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5720: &escape($cdom),
5721: $homeserver)));
1.709 albertel 5722: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5723: return (undef,undef);
5724: }
1.706 raeburn 5725: return ($update,$comment);
5726: }
5727:
5728: sub auto_photoupdate {
5729: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5730: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5731: my $host=&hostname($homeserver);
1.706 raeburn 5732: my $cmd = '';
5733: my $maxtries = 1;
1.800 albertel 5734: foreach my $affiliate (keys(%{$affiliatesref})) {
5735: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5736: }
5737: $cmd =~ s/%%$//;
5738: $cmd = &escape($cmd);
5739: my $query = 'institutionalphotos';
5740: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5741: unless ($queryid=~/^\Q$host\E\_/) {
5742: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5743: return 'error: '.$queryid;
5744: }
5745: my $reply = &get_query_reply($queryid);
5746: my $tries = 1;
5747: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5748: $reply = &get_query_reply($queryid);
5749: $tries ++;
5750: }
5751: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5752: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5753: } else {
5754: my @responses = split(/:/,$reply);
5755: my $outcome = shift(@responses);
5756: foreach my $item (@responses) {
5757: my ($key,$value) = split(/=/,$item);
5758: $$photo{$key} = $value;
5759: }
5760: return $outcome;
5761: }
5762: return 'error';
5763: }
5764:
1.521 raeburn 5765: sub auto_instcode_format {
1.793 albertel 5766: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5767: $cat_order) = @_;
1.521 raeburn 5768: my $courses = '';
1.772 raeburn 5769: my @homeservers;
1.521 raeburn 5770: if ($caller eq 'global') {
1.841 albertel 5771: my %servers = &get_servers($codedom,'library');
5772: foreach my $tryserver (keys(%servers)) {
5773: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5774: push(@homeservers,$tryserver);
5775: }
1.584 raeburn 5776: }
1.521 raeburn 5777: } else {
1.772 raeburn 5778: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5779: }
1.793 albertel 5780: foreach my $code (keys(%{$instcodes})) {
5781: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5782: }
5783: chop($courses);
1.772 raeburn 5784: my $ok_response = 0;
5785: my $response;
5786: while (@homeservers > 0 && $ok_response == 0) {
5787: my $server = shift(@homeservers);
5788: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5789: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5790: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5791: split(/:/,$response);
1.772 raeburn 5792: %{$codes} = (%{$codes},&str2hash($codes_str));
5793: push(@{$codetitles},&str2array($codetitles_str));
5794: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5795: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5796: $ok_response = 1;
5797: }
5798: }
5799: if ($ok_response) {
1.521 raeburn 5800: return 'ok';
1.772 raeburn 5801: } else {
5802: return $response;
1.521 raeburn 5803: }
5804: }
5805:
1.792 raeburn 5806: sub auto_instcode_defaults {
5807: my ($domain,$returnhash,$code_order) = @_;
5808: my @homeservers;
1.841 albertel 5809:
5810: my %servers = &get_servers($domain,'library');
5811: foreach my $tryserver (keys(%servers)) {
5812: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5813: push(@homeservers,$tryserver);
5814: }
1.792 raeburn 5815: }
1.841 albertel 5816:
1.792 raeburn 5817: my $response;
1.841 albertel 5818: foreach my $server (@homeservers) {
1.792 raeburn 5819: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5820: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5821:
5822: foreach my $pair (split(/\&/,$response)) {
5823: my ($name,$value)=split(/\=/,$pair);
5824: if ($name eq 'code_order') {
5825: @{$code_order} = split(/\&/,&unescape($value));
5826: } else {
5827: $returnhash->{&unescape($name)}=&unescape($value);
5828: }
5829: }
5830: return 'ok';
1.792 raeburn 5831: }
1.841 albertel 5832:
5833: return $response;
1.1003 raeburn 5834: }
5835:
5836: sub auto_possible_instcodes {
1.1007 raeburn 5837: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
5838: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
5839: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
5840: return;
5841: }
1.1003 raeburn 5842: my (@homeservers,$uhome);
5843: if (defined(&domain($domain,'primary'))) {
5844: $uhome=&domain($domain,'primary');
5845: push(@homeservers,&domain($domain,'primary'));
5846: } else {
5847: my %servers = &get_servers($domain,'library');
5848: foreach my $tryserver (keys(%servers)) {
5849: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5850: push(@homeservers,$tryserver);
5851: }
5852: }
5853: }
5854: my $response;
5855: foreach my $server (@homeservers) {
5856: $response=&reply('autopossibleinstcodes:'.$domain,$server);
5857: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 5858: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
5859: split(':',$response);
5860: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
5861: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 5862: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 5863: my ($name,$value)=split('=',$item);
5864: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5865: }
5866: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 5867: my ($name,$value)=split('=',$item);
5868: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5869: }
5870: return 'ok';
5871: }
5872: return $response;
5873: }
1.792 raeburn 5874:
1.1010 raeburn 5875: sub auto_courserequest_checks {
5876: my ($dom) = @_;
5877: my %validations;
5878: return %validations;
5879: }
5880:
1.1013 raeburn 5881: sub auto_courserequest_validation {
5882: my ($dom,$details,$inststatuses,$message) = @_;
5883: return 'pending';
5884: }
5885:
1.777 albertel 5886: sub auto_validate_class_sec {
1.918 raeburn 5887: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5888: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5889: my $ownerlist;
5890: if (ref($owners) eq 'ARRAY') {
5891: $ownerlist = join(',',@{$owners});
5892: } else {
5893: $ownerlist = $owners;
5894: }
1.773 raeburn 5895: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5896: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5897: return $response;
5898: }
5899:
1.679 raeburn 5900: # ------------------------------------------------------- Course Group routines
5901:
5902: sub get_coursegroups {
1.809 raeburn 5903: my ($cdom,$cnum,$group,$namespace) = @_;
5904: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5905: }
5906:
1.679 raeburn 5907: sub modify_coursegroup {
5908: my ($cdom,$cnum,$groupsettings) = @_;
5909: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5910: }
5911:
1.809 raeburn 5912: sub toggle_coursegroup_status {
5913: my ($cdom,$cnum,$group,$action) = @_;
5914: my ($from_namespace,$to_namespace);
5915: if ($action eq 'delete') {
5916: $from_namespace = 'coursegroups';
5917: $to_namespace = 'deleted_groups';
5918: } else {
5919: $from_namespace = 'deleted_groups';
5920: $to_namespace = 'coursegroups';
5921: }
5922: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5923: if (my $tmp = &error(%curr_group)) {
5924: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5925: return ('read error',$tmp);
5926: } else {
5927: my %savedsettings = %curr_group;
1.809 raeburn 5928: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5929: my $deloutcome;
5930: if ($result eq 'ok') {
1.809 raeburn 5931: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5932: } else {
5933: return ('write error',$result);
5934: }
5935: if ($deloutcome eq 'ok') {
5936: return 'ok';
5937: } else {
5938: return ('delete error',$deloutcome);
5939: }
5940: }
5941: }
5942:
1.679 raeburn 5943: sub modify_group_roles {
1.957 raeburn 5944: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 5945: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5946: my $role = 'gr/'.&escape($userprivs);
5947: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 5948: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 5949: if ($result eq 'ok') {
5950: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5951: }
1.679 raeburn 5952: return $result;
5953: }
5954:
5955: sub modify_coursegroup_membership {
5956: my ($cdom,$cnum,$membership) = @_;
5957: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5958: return $result;
5959: }
5960:
1.682 raeburn 5961: sub get_active_groups {
5962: my ($udom,$uname,$cdom,$cnum) = @_;
5963: my $now = time;
5964: my %groups = ();
5965: foreach my $key (keys(%env)) {
1.811 albertel 5966: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5967: my ($start,$end) = split(/\./,$env{$key});
5968: if (($end!=0) && ($end<$now)) { next; }
5969: if (($start!=0) && ($start>$now)) { next; }
5970: if ($1 eq $cdom && $2 eq $cnum) {
5971: $groups{$3} = $env{$key} ;
5972: }
5973: }
5974: }
5975: return %groups;
5976: }
5977:
1.683 raeburn 5978: sub get_group_membership {
5979: my ($cdom,$cnum,$group) = @_;
5980: return(&dump('groupmembership',$cdom,$cnum,$group));
5981: }
5982:
5983: sub get_users_groups {
5984: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5985: my @usersgroups;
1.683 raeburn 5986: my $cachetime=1800;
5987:
5988: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5989: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5990: if (defined($cached)) {
1.734 albertel 5991: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5992: } else {
5993: $grouplist = '';
1.816 raeburn 5994: my $courseurl = &courseid_to_courseurl($courseid);
5995: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5996: my $access_end = $env{'course.'.$courseid.
5997: '.default_enrollment_end_date'};
5998: my $now = time;
5999: foreach my $key (keys(%roleshash)) {
6000: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6001: my $group = $1;
6002: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6003: my $start = $2;
6004: my $end = $1;
6005: if ($start == -1) { next; } # deleted from group
6006: if (($start!=0) && ($start>$now)) { next; }
6007: if (($end!=0) && ($end<$now)) {
6008: if ($access_end && $access_end < $now) {
6009: if ($access_end - $end < 86400) {
6010: push(@usersgroups,$group);
1.733 raeburn 6011: }
6012: }
1.817 raeburn 6013: next;
1.733 raeburn 6014: }
1.817 raeburn 6015: push(@usersgroups,$group);
1.683 raeburn 6016: }
6017: }
6018: }
1.817 raeburn 6019: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6020: $grouplist = join(':',@usersgroups);
6021: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6022: }
1.733 raeburn 6023: return @usersgroups;
1.683 raeburn 6024: }
6025:
6026: sub devalidate_getgroups_cache {
6027: my ($udom,$uname,$cdom,$cnum)=@_;
6028: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6029:
1.683 raeburn 6030: my $hashid="$udom:$uname:$courseid";
6031: &devalidate_cache_new('getgroups',$hashid);
6032: }
6033:
1.12 www 6034: # ------------------------------------------------------------------ Plain Text
6035:
6036: sub plaintext {
1.988 raeburn 6037: my ($short,$type,$cid,$forcedefault) = @_;
1.758 albertel 6038: if ($short =~ /^cr/) {
6039: return (split('/',$short))[-1];
6040: }
1.742 raeburn 6041: if (!defined($cid)) {
6042: $cid = $env{'request.course.id'};
6043: }
1.988 raeburn 6044: if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
6045: unless ($forcedefault) {
6046: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6047: &Apache::lonlocal::mt_escape(\$roletext);
6048: return &Apache::lonlocal::mt($roletext);
6049: }
1.742 raeburn 6050: }
6051: my %rolenames = (
1.1008 raeburn 6052: Course => 'std',
6053: Community => 'alt1',
1.742 raeburn 6054: );
6055: if (defined($type) &&
6056: defined($rolenames{$type}) &&
6057: defined($prp{$short}{$rolenames{$type}})) {
6058: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
6059: } else {
6060: return &Apache::lonlocal::mt($prp{$short}{'std'});
6061: }
1.12 www 6062: }
6063:
6064: # ----------------------------------------------------------------- Assign Role
6065:
6066: sub assignrole {
1.957 raeburn 6067: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6068: $context)=@_;
1.21 www 6069: my $mrole;
6070: if ($role =~ /^cr\//) {
1.393 www 6071: my $cwosec=$url;
1.811 albertel 6072: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6073: unless (&allowed('ccr',$cwosec)) {
1.104 www 6074: &logthis('Refused custom assignrole: '.
6075: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 6076: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 6077: return 'refused';
6078: }
1.21 www 6079: $mrole='cr';
1.678 raeburn 6080: } elsif ($role =~ /^gr\//) {
6081: my $cwogrp=$url;
1.811 albertel 6082: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6083: unless (&allowed('mdg',$cwogrp)) {
6084: &logthis('Refused group assignrole: '.
6085: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6086: $env{'user.name'}.' at '.$env{'user.domain'});
6087: return 'refused';
6088: }
6089: $mrole='gr';
1.21 www 6090: } else {
1.82 www 6091: my $cwosec=$url;
1.811 albertel 6092: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6093: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6094: my $refused;
6095: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6096: if (!(&allowed('c'.$role,$url))) {
6097: $refused = 1;
6098: }
6099: } else {
6100: $refused = 1;
6101: }
1.947 raeburn 6102: if ($refused) {
6103: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6104: $refused = '';
6105: } else {
6106: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6107: ' '.$role.' '.$end.' '.$start.' by '.
6108: $env{'user.name'}.' at '.$env{'user.domain'});
6109: return 'refused';
6110: }
1.932 raeburn 6111: }
1.104 www 6112: }
1.21 www 6113: $mrole=$role;
6114: }
1.620 albertel 6115: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6116: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6117: if ($end) { $command.='_'.$end; }
1.21 www 6118: if ($start) {
6119: if ($end) {
1.81 www 6120: $command.='_'.$start;
1.21 www 6121: } else {
1.81 www 6122: $command.='_0_'.$start;
1.21 www 6123: }
6124: }
1.739 raeburn 6125: my $origstart = $start;
6126: my $origend = $end;
1.957 raeburn 6127: my $delflag;
1.357 www 6128: # actually delete
6129: if ($deleteflag) {
1.373 www 6130: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6131: # modify command to delete the role
1.620 albertel 6132: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6133: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6134: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6135: # set start and finish to negative values for userrolelog
6136: $start=-1;
6137: $end=-1;
1.957 raeburn 6138: $delflag = 1;
1.357 www 6139: }
6140: }
6141: # send command
1.349 www 6142: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6143: # log new user role if status is ok
1.349 www 6144: if ($answer eq 'ok') {
1.663 raeburn 6145: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6146: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6147: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6148: unless ($role =~ /^gr/) {
6149: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6150: $origstart,$selfenroll,$context);
1.739 raeburn 6151: }
1.349 www 6152: }
6153: return $answer;
1.169 harris41 6154: }
6155:
6156: # -------------------------------------------------- Modify user authentication
1.197 www 6157: # Overrides without validation
6158:
1.169 harris41 6159: sub modifyuserauth {
6160: my ($udom,$uname,$umode,$upass)=@_;
6161: my $uhome=&homeserver($uname,$udom);
1.197 www 6162: unless (&allowed('mau',$udom)) { return 'refused'; }
6163: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6164: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6165: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6166: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6167: &escape($upass),$uhome);
1.620 albertel 6168: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6169: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6170: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6171: &log($udom,,$uname,$uhome,
1.620 albertel 6172: 'Authentication changed by '.$env{'user.domain'}.', '.
6173: $env{'user.name'}.', '.$umode.
1.197 www 6174: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6175: unless ($reply eq 'ok') {
1.197 www 6176: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6177: return 'error: '.$reply;
6178: }
1.170 harris41 6179: return 'ok';
1.80 www 6180: }
6181:
1.81 www 6182: # --------------------------------------------------------------- Modify a user
1.80 www 6183:
1.81 www 6184: sub modifyuser {
1.206 matthew 6185: my ($udom, $uname, $uid,
6186: $umode, $upass, $first,
6187: $middle, $last, $gene,
1.963 raeburn 6188: $forceid, $desiredhome, $email, $inststatus)=@_;
1.807 albertel 6189: $udom= &LONCAPA::clean_domain($udom);
6190: $uname=&LONCAPA::clean_username($uname);
1.81 www 6191: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6192: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 6193: $last.', '.$gene.'(forceid: '.$forceid.')'.
6194: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6195: ' desiredhome not specified').
1.620 albertel 6196: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6197: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6198: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 6199: # ----------------------------------------------------------------- Create User
1.406 albertel 6200: if (($uhome eq 'no_host') &&
6201: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6202: my $unhome='';
1.844 albertel 6203: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6204: $unhome = $desiredhome;
1.620 albertel 6205: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6206: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6207: } else { # load balancing routine for determining $unhome
1.81 www 6208: my $loadm=10000000;
1.841 albertel 6209: my %servers = &get_servers($udom,'library');
6210: foreach my $tryserver (keys(%servers)) {
6211: my $answer=reply('load',$tryserver);
6212: if (($answer=~/\d+/) && ($answer<$loadm)) {
6213: $loadm=$answer;
6214: $unhome=$tryserver;
6215: }
1.80 www 6216: }
6217: }
6218: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6219: return 'error: unable to find a home server for '.$uname.
6220: ' in domain '.$udom;
1.80 www 6221: }
6222: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6223: &escape($upass),$unhome);
6224: unless ($reply eq 'ok') {
6225: return 'error: '.$reply;
6226: }
1.230 stredwic 6227: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6228: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6229: return 'error: unable verify users home machine.';
1.80 www 6230: }
1.209 matthew 6231: } # End of creation of new user
1.80 www 6232: # ---------------------------------------------------------------------- Add ID
6233: if ($uid) {
6234: $uid=~tr/A-Z/a-z/;
6235: my %uidhash=&idrget($udom,$uname);
1.196 www 6236: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6237: && (!$forceid)) {
1.80 www 6238: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6239: return 'error: user id "'.$uid.'" does not match '.
6240: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6241: }
6242: } else {
6243: &idput($udom,($uname => $uid));
6244: }
6245: }
6246: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6247: my @tmp=&get('environment',
1.899 raeburn 6248: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6249: 'permanentemail','inststatus'],
1.134 albertel 6250: $udom,$uname);
1.313 matthew 6251: my %names;
6252: if ($tmp[0] =~ m/^error:.*/) {
6253: %names=();
6254: } else {
6255: %names = @tmp;
6256: }
1.388 www 6257: #
6258: # Make sure to not trash student environment if instructor does not bother
6259: # to supply name and email information
6260: #
6261: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6262: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6263: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6264: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6265: if ($email) {
6266: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6267: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6268: }
1.899 raeburn 6269: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6270: if (defined($inststatus)) {
6271: $names{'inststatus'} = '';
6272: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6273: if (ref($usertypes) eq 'HASH') {
6274: my @okstatuses;
6275: foreach my $item (split(/:/,$inststatus)) {
6276: if (defined($usertypes->{$item})) {
6277: push(@okstatuses,$item);
6278: }
6279: }
6280: if (@okstatuses) {
6281: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6282: }
6283: }
6284: }
1.134 albertel 6285: my $reply = &put('environment', \%names, $udom,$uname);
6286: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 6287: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 6288: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 6289: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6290: $umode.', '.$first.', '.$middle.', '.
6291: $last.', '.$gene.', '.$email.', '.$inststatus;
6292: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6293: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6294: } else {
6295: $logmsg .= ' during self creation';
6296: }
6297: &logthis($logmsg);
1.134 albertel 6298: return 'ok';
1.80 www 6299: }
6300:
1.81 www 6301: # -------------------------------------------------------------- Modify student
1.80 www 6302:
1.81 www 6303: sub modifystudent {
6304: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6305: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6306: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6307: if (!$cid) {
1.620 albertel 6308: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6309: return 'not_in_class';
6310: }
1.80 www 6311: }
6312: # --------------------------------------------------------------- Make the user
1.81 www 6313: my $reply=&modifyuser
1.209 matthew 6314: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6315: $desiredhome,$email,$inststatus);
1.80 www 6316: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6317: # This will cause &modify_student_enrollment to get the uid from the
6318: # students environment
6319: $uid = undef if (!$forceid);
1.455 albertel 6320: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6321: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6322: return $reply;
6323: }
6324:
6325: sub modify_student_enrollment {
1.957 raeburn 6326: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6327: my ($cdom,$cnum,$chome);
6328: if (!$cid) {
1.620 albertel 6329: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6330: return 'not_in_class';
6331: }
1.620 albertel 6332: $cdom=$env{'course.'.$cid.'.domain'};
6333: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6334: } else {
6335: ($cdom,$cnum)=split(/_/,$cid);
6336: }
1.620 albertel 6337: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6338: if (!$chome) {
1.457 raeburn 6339: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6340: }
1.455 albertel 6341: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6342: # Make sure the user exists
1.81 www 6343: my $uhome=&homeserver($uname,$udom);
6344: if (($uhome eq '') || ($uhome eq 'no_host')) {
6345: return 'error: no such user';
6346: }
1.297 matthew 6347: # Get student data if we were not given enough information
6348: if (!defined($first) || $first eq '' ||
6349: !defined($last) || $last eq '' ||
6350: !defined($uid) || $uid eq '' ||
6351: !defined($middle) || $middle eq '' ||
6352: !defined($gene) || $gene eq '') {
1.294 matthew 6353: # They did not supply us with enough data to enroll the student, so
6354: # we need to pick up more information.
1.297 matthew 6355: my %tmp = &get('environment',
1.294 matthew 6356: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6357: ,$udom,$uname);
6358:
1.800 albertel 6359: #foreach my $key (keys(%tmp)) {
6360: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6361: #}
1.294 matthew 6362: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6363: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6364: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6365: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6366: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6367: }
1.556 albertel 6368: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6369: my $reply=cput('classlist',
6370: {"$uname:$udom" =>
1.515 raeburn 6371: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6372: $cdom,$cnum);
1.81 www 6373: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6374: return 'error: '.$reply;
1.652 albertel 6375: } else {
6376: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6377: }
1.297 matthew 6378: # Add student role to user
1.83 www 6379: my $uurl='/'.$cid;
1.81 www 6380: $uurl=~s/\_/\//g;
6381: if ($usec) {
6382: $uurl.='/'.$usec;
6383: }
1.957 raeburn 6384: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6385: }
6386:
1.556 albertel 6387: sub format_name {
6388: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6389: my $name;
6390: if ($first ne 'lastname') {
6391: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6392: } else {
6393: if ($lastname=~/\S/) {
6394: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6395: $name=~s/\s+,/,/;
6396: } else {
6397: $name.= $firstname.' '.$middlename.' '.$generation;
6398: }
6399: }
6400: $name=~s/^\s+//;
6401: $name=~s/\s+$//;
6402: $name=~s/\s+/ /g;
6403: return $name;
6404: }
6405:
1.84 www 6406: # ------------------------------------------------- Write to course preferences
6407:
6408: sub writecoursepref {
6409: my ($courseid,%prefs)=@_;
6410: $courseid=~s/^\///;
6411: $courseid=~s/\_/\//g;
6412: my ($cdomain,$cnum)=split(/\//,$courseid);
6413: my $chome=homeserver($cnum,$cdomain);
6414: if (($chome eq '') || ($chome eq 'no_host')) {
6415: return 'error: no such course';
6416: }
6417: my $cstring='';
1.800 albertel 6418: foreach my $pref (keys(%prefs)) {
6419: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6420: }
1.84 www 6421: $cstring=~s/\&$//;
6422: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6423: }
6424:
6425: # ---------------------------------------------------------- Make/modify course
6426:
6427: sub createcourse {
1.741 raeburn 6428: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1011 raeburn 6429: $course_owner,$crstype,$cnum)=@_;
1.84 www 6430: $url=&declutter($url);
6431: my $cid='';
1.264 matthew 6432: unless (&allowed('ccc',$udom)) {
1.84 www 6433: return 'refused';
6434: }
1.1011 raeburn 6435: # --------------------------------------------------------------- Get Unique ID
6436: my $uname;
6437: if ($cnum =~ /^$match_courseid$/) {
6438: my $chome=&homeserver($cnum,$udom,'true');
6439: if (($chome eq '') || ($chome eq 'no_host')) {
6440: $uname = $cnum;
6441: } else {
6442: $uname = &generate_coursenum($udom);
6443: }
6444: } else {
6445: $uname = &generate_coursenum($udom);
6446: }
6447: return $uname if ($uname =~ /^error/);
6448: # -------------------------------------------------- Check supplied server name
1.620 albertel 6449: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 6450: if (! &is_library($course_server)) {
1.264 matthew 6451: return 'error:bad server name '.$course_server;
6452: }
1.84 www 6453: # ------------------------------------------------------------- Make the course
6454: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6455: $course_server);
1.84 www 6456: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 6457: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6458: if (($uhome eq '') || ($uhome eq 'no_host')) {
6459: return 'error: no such course';
6460: }
1.271 www 6461: # ----------------------------------------------------------------- Course made
1.516 raeburn 6462: # log existence
1.918 raeburn 6463: my $newcourse = {
6464: $udom.'_'.$uname => {
1.921 raeburn 6465: description => $description,
6466: inst_code => $inst_code,
6467: owner => $course_owner,
6468: type => $crstype,
1.918 raeburn 6469: },
6470: };
1.921 raeburn 6471: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6472: # set toplevel url
1.271 www 6473: my $topurl=$url;
6474: unless ($nonstandard) {
6475: # ------------------------------------------ For standard courses, make top url
6476: my $mapurl=&clutter($url);
1.278 www 6477: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6478: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6479: <map>
6480: <resource id="1" type="start"></resource>
6481: <resource id="2" src="$mapurl"></resource>
6482: <resource id="3" type="finish"></resource>
6483: <link index="1" from="1" to="2"></link>
6484: <link index="2" from="2" to="3"></link>
6485: </map>
6486: ENDINITMAP
6487: $topurl=&declutter(
1.638 albertel 6488: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6489: );
6490: }
6491: # ----------------------------------------------------------- Write preferences
1.84 www 6492: &writecoursepref($udom.'_'.$uname,
6493: ('description' => $description,
1.271 www 6494: 'url' => $topurl));
1.84 www 6495: return '/'.$udom.'/'.$uname;
6496: }
6497:
1.1011 raeburn 6498: # ------------------------------------------------------------------- Create ID
6499: sub generate_coursenum {
6500: my ($udom) = @_;
6501: my $domdesc = &domain($udom);
6502: return 'error: invalid domain' if ($domdesc eq '');
6503: my $uname=int(1+rand(9)).
6504: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6505: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6506: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6507: # ----------------------------------------------- Make sure that does not exist
6508: my $uhome=&homeserver($uname,$udom,'true');
6509: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6510: $uname=int(1+rand(9)).
6511: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6512: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6513: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6514: $uhome=&homeserver($uname,$udom,'true');
6515: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6516: return 'error: unable to generate unique course-ID';
6517: }
6518: }
6519: return $uname;
6520: }
6521:
1.813 albertel 6522: sub is_course {
6523: my ($cdom,$cnum) = @_;
6524: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6525: undef,'.');
1.813 albertel 6526: if (exists($courses{$cdom.'_'.$cnum})) {
6527: return 1;
6528: }
6529: return 0;
6530: }
6531:
1.1015 ! raeburn 6532: sub store_userdata {
! 6533: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 6534: my $result;
1.1015 ! raeburn 6535: if $datakey ne '') {
1.1013 raeburn 6536: if (ref($storehash) eq 'HASH') {
6537: my $uhome=&homeserver();
6538: if (($uhome eq '') || ($uhome eq 'no_host')) {
6539: $result = 'error: no_host';
6540: } else {
6541: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
6542: $storehash->{'host'} = $perlvar{'lonHostID'};
6543:
6544: my $namevalue='';
6545: foreach my $key (keys(%{$storehash})) {
6546: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6547: }
6548: $namevalue=~s/\&$//;
6549: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 ! raeburn 6550: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 6551: }
6552: } else {
6553: $result = 'error: data to store was not a hash reference';
6554: }
6555: } else {
6556: $result= 'error: invalid requestkey';
6557: }
6558: return $result;
6559: }
6560:
1.21 www 6561: # ---------------------------------------------------------- Assign Custom Role
6562:
6563: sub assigncustomrole {
1.957 raeburn 6564: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6565: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6566: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6567: }
6568:
6569: # ----------------------------------------------------------------- Revoke Role
6570:
6571: sub revokerole {
1.957 raeburn 6572: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6573: my $now=time;
1.965 raeburn 6574: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6575: }
6576:
6577: # ---------------------------------------------------------- Revoke Custom Role
6578:
6579: sub revokecustomrole {
1.957 raeburn 6580: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6581: my $now=time;
1.357 www 6582: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6583: $deleteflag,$selfenroll,$context);
1.17 www 6584: }
6585:
1.533 banghart 6586: # ------------------------------------------------------------ Disk usage
1.535 albertel 6587: sub diskusage {
1.955 raeburn 6588: my ($udom,$uname,$directorypath,$getpropath)=@_;
6589: $directorypath =~ s/\/$//;
6590: my $listing=&reply('du2:'.&escape($directorypath).':'
6591: .&escape($getpropath).':'.&escape($uname).':'
6592: .&escape($udom),homeserver($uname,$udom));
6593: if ($listing eq 'unknown_cmd') {
6594: if ($getpropath) {
6595: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6596: }
6597: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6598: }
1.514 albertel 6599: return $listing;
1.512 banghart 6600: }
6601:
1.566 banghart 6602: sub is_locked {
6603: my ($file_name, $domain, $user) = @_;
6604: my @check;
6605: my $is_locked;
6606: push @check, $file_name;
1.613 albertel 6607: my %locked = &get('file_permissions',\@check,
1.620 albertel 6608: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6609: my ($tmp)=keys(%locked);
6610: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6611:
1.566 banghart 6612: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6613: $is_locked = 'false';
6614: foreach my $entry (@{$locked{$file_name}}) {
6615: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6616: $is_locked = 'true';
6617: last;
1.745 raeburn 6618: }
6619: }
1.566 banghart 6620: } else {
6621: $is_locked = 'false';
6622: }
6623: }
6624:
1.759 albertel 6625: sub declutter_portfile {
6626: my ($file) = @_;
1.833 albertel 6627: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6628: return $file;
6629: }
6630:
1.559 banghart 6631: # ------------------------------------------------------------- Mark as Read Only
6632:
6633: sub mark_as_readonly {
6634: my ($domain,$user,$files,$what) = @_;
1.613 albertel 6635: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6636: my ($tmp)=keys(%current_permissions);
6637: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 6638: foreach my $file (@{$files}) {
1.759 albertel 6639: $file = &declutter_portfile($file);
1.561 banghart 6640: push(@{$current_permissions{$file}},$what);
1.559 banghart 6641: }
1.613 albertel 6642: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6643: return;
6644: }
6645:
1.572 banghart 6646: # ------------------------------------------------------------Save Selected Files
6647:
6648: sub save_selected_files {
6649: my ($user, $path, @files) = @_;
6650: my $filename = $user."savedfiles";
1.573 banghart 6651: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 6652: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 6653: foreach my $file (@files) {
1.620 albertel 6654: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 6655: }
6656: foreach my $file (@other_files) {
1.574 banghart 6657: print (OUT $file."\n");
1.572 banghart 6658: }
1.574 banghart 6659: close (OUT);
1.572 banghart 6660: return 'ok';
6661: }
6662:
1.574 banghart 6663: sub clear_selected_files {
6664: my ($user) = @_;
6665: my $filename = $user."savedfiles";
6666: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6667: print (OUT undef);
6668: close (OUT);
6669: return ("ok");
6670: }
6671:
1.572 banghart 6672: sub files_in_path {
6673: my ($user, $path) = @_;
6674: my $filename = $user."savedfiles";
6675: my %return_files;
1.574 banghart 6676: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 6677: while (my $line_in = <IN>) {
1.574 banghart 6678: chomp ($line_in);
6679: my @paths_and_file = split (m!/!, $line_in);
6680: my $file_part = pop (@paths_and_file);
6681: my $path_part = join ('/', @paths_and_file);
1.573 banghart 6682: $path_part.='/';
6683: my $path_and_file = $path_part.$file_part;
6684: if ($path_part eq $path) {
6685: $return_files{$file_part}= 'selected';
6686: }
6687: }
1.574 banghart 6688: close (IN);
6689: return (\%return_files);
1.572 banghart 6690: }
6691:
6692: # called in portfolio select mode, to show files selected NOT in current directory
6693: sub files_not_in_path {
6694: my ($user, $path) = @_;
6695: my $filename = $user."savedfiles";
6696: my @return_files;
6697: my $path_part;
1.800 albertel 6698: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6699: while (my $line = <IN>) {
1.572 banghart 6700: #ok, I know it's clunky, but I want it to work
1.800 albertel 6701: my @paths_and_file = split(m|/|, $line);
6702: my $file_part = pop(@paths_and_file);
6703: chomp($file_part);
6704: my $path_part = join('/', @paths_and_file);
1.572 banghart 6705: $path_part .= '/';
6706: my $path_and_file = $path_part.$file_part;
6707: if ($path_part ne $path) {
1.800 albertel 6708: push(@return_files, ($path_and_file));
1.572 banghart 6709: }
6710: }
1.800 albertel 6711: close(OUT);
1.574 banghart 6712: return (@return_files);
1.572 banghart 6713: }
6714:
1.745 raeburn 6715: #----------------------------------------------Get portfolio file permissions
1.629 banghart 6716:
1.745 raeburn 6717: sub get_portfile_permissions {
6718: my ($domain,$user) = @_;
1.613 albertel 6719: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6720: my ($tmp)=keys(%current_permissions);
6721: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6722: return \%current_permissions;
6723: }
6724:
6725: #---------------------------------------------Get portfolio file access controls
6726:
1.749 raeburn 6727: sub get_access_controls {
1.745 raeburn 6728: my ($current_permissions,$group,$file) = @_;
1.769 albertel 6729: my %access;
6730: my $real_file = $file;
6731: $file =~ s/\.meta$//;
1.745 raeburn 6732: if (defined($file)) {
1.749 raeburn 6733: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6734: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 6735: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 6736: }
6737: }
1.745 raeburn 6738: } else {
1.749 raeburn 6739: foreach my $key (keys(%{$current_permissions})) {
6740: if ($key =~ /\0accesscontrol$/) {
6741: if (defined($group)) {
6742: if ($key !~ m-^\Q$group\E/-) {
6743: next;
6744: }
6745: }
6746: my ($fullpath) = split(/\0/,$key);
6747: if (ref($$current_permissions{$key}) eq 'HASH') {
6748: foreach my $control (keys(%{$$current_permissions{$key}})) {
6749: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6750: }
6751: }
6752: }
6753: }
6754: }
6755: return %access;
6756: }
6757:
6758: sub modify_access_controls {
6759: my ($file_name,$changes,$domain,$user)=@_;
6760: my ($outcome,$deloutcome);
6761: my %store_permissions;
6762: my %new_values;
6763: my %new_control;
6764: my %translation;
6765: my @deletions = ();
6766: my $now = time;
6767: if (exists($$changes{'activate'})) {
6768: if (ref($$changes{'activate'}) eq 'HASH') {
6769: my @newitems = sort(keys(%{$$changes{'activate'}}));
6770: my $numnew = scalar(@newitems);
6771: for (my $i=0; $i<$numnew; $i++) {
6772: my $newkey = $newitems[$i];
6773: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 6774: if ($newkey =~ /^\d+:/) {
6775: $newkey =~ s/^(\d+)/$newid/;
6776: $translation{$1} = $newid;
6777: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6778: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6779: $translation{$1} = $newid;
6780: }
1.749 raeburn 6781: $new_values{$file_name."\0".$newkey} =
6782: $$changes{'activate'}{$newitems[$i]};
6783: $new_control{$newkey} = $now;
6784: }
6785: }
6786: }
6787: my %todelete;
6788: my %changed_items;
6789: foreach my $action ('delete','update') {
6790: if (exists($$changes{$action})) {
6791: if (ref($$changes{$action}) eq 'HASH') {
6792: foreach my $key (keys(%{$$changes{$action}})) {
6793: my ($itemnum) = ($key =~ /^([^:]+):/);
6794: if ($action eq 'delete') {
6795: $todelete{$itemnum} = 1;
6796: } else {
6797: $changed_items{$itemnum} = $key;
6798: }
6799: }
1.745 raeburn 6800: }
6801: }
1.749 raeburn 6802: }
6803: # get lock on access controls for file.
6804: my $lockhash = {
6805: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6806: ':'.$env{'user.domain'},
6807: };
6808: my $tries = 0;
6809: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6810:
6811: while (($gotlock ne 'ok') && $tries <3) {
6812: $tries ++;
6813: sleep 1;
6814: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6815: }
6816: if ($gotlock eq 'ok') {
6817: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6818: my ($tmp)=keys(%curr_permissions);
6819: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6820: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6821: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6822: if (ref($curr_controls) eq 'HASH') {
6823: foreach my $control_item (keys(%{$curr_controls})) {
6824: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6825: if (defined($todelete{$itemnum})) {
6826: push(@deletions,$file_name."\0".$control_item);
6827: } else {
6828: if (defined($changed_items{$itemnum})) {
6829: $new_control{$changed_items{$itemnum}} = $now;
6830: push(@deletions,$file_name."\0".$control_item);
6831: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6832: } else {
6833: $new_control{$control_item} = $$curr_controls{$control_item};
6834: }
6835: }
1.745 raeburn 6836: }
6837: }
6838: }
1.970 raeburn 6839: my ($group);
6840: if (&is_course($domain,$user)) {
6841: ($group,my $file) = split(/\//,$file_name,2);
6842: }
1.749 raeburn 6843: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6844: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6845: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6846: # remove lock
6847: my @del_lock = ($file_name."\0".'locked_access_records');
6848: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 6849: my $sqlresult =
1.970 raeburn 6850: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 6851: $group);
1.749 raeburn 6852: } else {
6853: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 6854: }
1.749 raeburn 6855: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 6856: }
6857:
1.827 raeburn 6858: sub make_public_indefinitely {
6859: my ($requrl) = @_;
6860: my $now = time;
6861: my $action = 'activate';
6862: my $aclnum = 0;
6863: if (&is_portfolio_url($requrl)) {
6864: my (undef,$udom,$unum,$file_name,$group) =
6865: &parse_portfolio_url($requrl);
6866: my $current_perms = &get_portfile_permissions($udom,$unum);
6867: my %access_controls = &get_access_controls($current_perms,
6868: $group,$file_name);
6869: foreach my $key (keys(%{$access_controls{$file_name}})) {
6870: my ($num,$scope,$end,$start) =
6871: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6872: if ($scope eq 'public') {
6873: if ($start <= $now && $end == 0) {
6874: $action = 'none';
6875: } else {
6876: $action = 'update';
6877: $aclnum = $num;
6878: }
6879: last;
6880: }
6881: }
6882: if ($action eq 'none') {
6883: return 'ok';
6884: } else {
6885: my %changes;
6886: my $newend = 0;
6887: my $newstart = $now;
6888: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6889: $changes{$action}{$newkey} = {
6890: type => 'public',
6891: time => {
6892: start => $newstart,
6893: end => $newend,
6894: },
6895: };
6896: my ($outcome,$deloutcome,$new_values,$translation) =
6897: &modify_access_controls($file_name,\%changes,$udom,$unum);
6898: return $outcome;
6899: }
6900: } else {
6901: return 'invalid';
6902: }
6903: }
6904:
1.745 raeburn 6905: #------------------------------------------------------Get Marked as Read Only
6906:
6907: sub get_marked_as_readonly {
6908: my ($domain,$user,$what,$group) = @_;
6909: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 6910: my @readonly_files;
1.629 banghart 6911: my $cmp1=$what;
6912: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 6913: while (my ($file_name,$value) = each(%{$current_permissions})) {
6914: if (defined($group)) {
6915: if ($file_name !~ m-^\Q$group\E/-) {
6916: next;
6917: }
6918: }
1.561 banghart 6919: if (ref($value) eq "ARRAY"){
6920: foreach my $stored_what (@{$value}) {
1.629 banghart 6921: my $cmp2=$stored_what;
1.759 albertel 6922: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 6923: $cmp2=join('',@{$stored_what});
1.745 raeburn 6924: }
1.629 banghart 6925: if ($cmp1 eq $cmp2) {
1.561 banghart 6926: push(@readonly_files, $file_name);
1.745 raeburn 6927: last;
1.563 banghart 6928: } elsif (!defined($what)) {
6929: push(@readonly_files, $file_name);
1.745 raeburn 6930: last;
1.561 banghart 6931: }
6932: }
1.745 raeburn 6933: }
1.561 banghart 6934: }
6935: return @readonly_files;
6936: }
1.577 banghart 6937: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 6938:
1.577 banghart 6939: sub get_marked_as_readonly_hash {
1.745 raeburn 6940: my ($current_permissions,$group,$what) = @_;
1.577 banghart 6941: my %readonly_files;
1.745 raeburn 6942: while (my ($file_name,$value) = each(%{$current_permissions})) {
6943: if (defined($group)) {
6944: if ($file_name !~ m-^\Q$group\E/-) {
6945: next;
6946: }
6947: }
1.577 banghart 6948: if (ref($value) eq "ARRAY"){
6949: foreach my $stored_what (@{$value}) {
1.745 raeburn 6950: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6951: foreach my $lock_descriptor(@{$stored_what}) {
6952: if ($lock_descriptor eq 'graded') {
6953: $readonly_files{$file_name} = 'graded';
6954: } elsif ($lock_descriptor eq 'handback') {
6955: $readonly_files{$file_name} = 'handback';
6956: } else {
6957: if (!exists($readonly_files{$file_name})) {
6958: $readonly_files{$file_name} = 'locked';
6959: }
6960: }
1.745 raeburn 6961: }
1.750 banghart 6962: }
1.577 banghart 6963: }
6964: }
6965: }
6966: return %readonly_files;
6967: }
1.559 banghart 6968: # ------------------------------------------------------------ Unmark as Read Only
6969:
6970: sub unmark_as_readonly {
1.629 banghart 6971: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6972: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6973: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6974: $file_name = &declutter_portfile($file_name);
1.634 albertel 6975: my $symb_crs = $what;
6976: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6977: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6978: my ($tmp)=keys(%current_permissions);
6979: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6980: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6981: foreach my $file (@readonly_files) {
1.759 albertel 6982: my $clean_file = &declutter_portfile($file);
6983: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6984: my $current_locks = $current_permissions{$file};
1.563 banghart 6985: my @new_locks;
6986: my @del_keys;
6987: if (ref($current_locks) eq "ARRAY"){
6988: foreach my $locker (@{$current_locks}) {
1.632 albertel 6989: my $compare=$locker;
1.749 raeburn 6990: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6991: $compare=join('',@{$locker});
1.746 raeburn 6992: if ($compare ne $symb_crs) {
6993: push(@new_locks, $locker);
6994: }
1.563 banghart 6995: }
6996: }
1.650 albertel 6997: if (scalar(@new_locks) > 0) {
1.563 banghart 6998: $current_permissions{$file} = \@new_locks;
6999: } else {
7000: push(@del_keys, $file);
1.613 albertel 7001: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7002: delete($current_permissions{$file});
1.563 banghart 7003: }
7004: }
1.561 banghart 7005: }
1.613 albertel 7006: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7007: return;
7008: }
1.512 banghart 7009:
1.17 www 7010: # ------------------------------------------------------------ Directory lister
7011:
7012: sub dirlist {
1.955 raeburn 7013: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7014: $uri=~s/^\///;
7015: $uri=~s/\/$//;
1.253 stredwic 7016: my ($udom, $uname);
1.955 raeburn 7017: if ($getuserdir) {
1.253 stredwic 7018: $udom = $userdomain;
7019: $uname = $username;
1.955 raeburn 7020: } else {
7021: (undef,$udom,$uname)=split(/\//,$uri);
7022: if(defined($userdomain)) {
7023: $udom = $userdomain;
7024: }
7025: if(defined($username)) {
7026: $uname = $username;
7027: }
1.253 stredwic 7028: }
1.955 raeburn 7029: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7030:
1.955 raeburn 7031: $dirRoot = $perlvar{'lonDocRoot'};
7032: if (defined($getpropath)) {
7033: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7034: $dirRoot =~ s/\/$//;
1.955 raeburn 7035: } elsif (defined($getuserdir)) {
7036: my $subdir=$uname.'__';
7037: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7038: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7039: ."/$udom/$subdir/$uname";
7040: } elsif (defined($alternateRoot)) {
7041: $dirRoot = $alternateRoot;
1.751 banghart 7042: }
1.253 stredwic 7043:
7044: if($udom) {
7045: if($uname) {
1.955 raeburn 7046: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7047: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7048: .':'.&escape($uname).':'.&escape($udom),
7049: &homeserver($uname,$udom));
7050: if ($listing eq 'unknown_cmd') {
7051: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7052: &homeserver($uname,$udom));
7053: } else {
7054: @listing_results = map { &unescape($_); } split(/:/,$listing);
7055: }
1.605 matthew 7056: if ($listing eq 'unknown_cmd') {
1.800 albertel 7057: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7058: &homeserver($uname,$udom));
1.605 matthew 7059: @listing_results = split(/:/,$listing);
7060: } else {
7061: @listing_results = map { &unescape($_); } split(/:/,$listing);
7062: }
7063: return @listing_results;
1.955 raeburn 7064: } elsif(!$alternateRoot) {
1.800 albertel 7065: my %allusers;
1.841 albertel 7066: my %servers = &get_servers($udom,'library');
1.955 raeburn 7067: foreach my $tryserver (keys(%servers)) {
7068: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7069: &escape($udom),$tryserver);
7070: if ($listing eq 'unknown_cmd') {
7071: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7072: $udom, $tryserver);
7073: } else {
7074: @listing_results = map { &unescape($_); } split(/:/,$listing);
7075: }
1.841 albertel 7076: if ($listing eq 'unknown_cmd') {
7077: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7078: $udom, $tryserver);
7079: @listing_results = split(/:/,$listing);
7080: } else {
7081: @listing_results =
7082: map { &unescape($_); } split(/:/,$listing);
7083: }
7084: if ($listing_results[0] ne 'no_such_dir' &&
7085: $listing_results[0] ne 'empty' &&
7086: $listing_results[0] ne 'con_lost') {
7087: foreach my $line (@listing_results) {
7088: my ($entry) = split(/&/,$line,2);
7089: $allusers{$entry} = 1;
7090: }
7091: }
1.253 stredwic 7092: }
7093: my $alluserstr='';
1.800 albertel 7094: foreach my $user (sort(keys(%allusers))) {
7095: $alluserstr.=$user.'&user:';
1.253 stredwic 7096: }
7097: $alluserstr=~s/:$//;
7098: return split(/:/,$alluserstr);
7099: } else {
1.800 albertel 7100: return ('missing user name');
1.253 stredwic 7101: }
1.955 raeburn 7102: } elsif(!defined($getpropath)) {
1.841 albertel 7103: my @all_domains = sort(&all_domains());
1.955 raeburn 7104: foreach my $domain (@all_domains) {
7105: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7106: }
7107: return @all_domains;
7108: } else {
1.800 albertel 7109: return ('missing domain');
1.275 stredwic 7110: }
7111: }
7112:
7113: # --------------------------------------------- GetFileTimestamp
7114: # This function utilizes dirlist and returns the date stamp for
7115: # when it was last modified. It will also return an error of -1
7116: # if an error occurs
7117:
7118: sub GetFileTimestamp {
1.955 raeburn 7119: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7120: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7121: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7122: my ($fileStat) =
7123: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7124: undef,$getuserdir);
1.275 stredwic 7125: my @stats = split('&', $fileStat);
7126: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7127: # @stats contains first the filename, then the stat output
7128: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7129: } else {
7130: return -1;
1.253 stredwic 7131: }
1.26 www 7132: }
7133:
1.712 albertel 7134: sub stat_file {
7135: my ($uri) = @_;
1.787 albertel 7136: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7137:
1.955 raeburn 7138: my ($udom,$uname,$file);
1.712 albertel 7139: if ($uri =~ m-^/(uploaded|editupload)/-) {
7140: ($udom,$uname,$file) =
1.811 albertel 7141: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7142: $file = 'userfiles/'.$file;
7143: }
7144: if ($uri =~ m-^/res/-) {
7145: ($udom,$uname) =
1.807 albertel 7146: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7147: $file = $uri;
7148: }
7149:
7150: if (!$udom || !$uname || !$file) {
7151: # unable to handle the uri
7152: return ();
7153: }
1.956 raeburn 7154: my $getpropath;
7155: if ($file =~ /^userfiles\//) {
7156: $getpropath = 1;
7157: }
1.955 raeburn 7158: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7159: my @stats = split('&', $result);
1.721 banghart 7160:
1.712 albertel 7161: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7162: shift(@stats); #filename is first
7163: return @stats;
7164: }
7165: return ();
7166: }
7167:
1.26 www 7168: # -------------------------------------------------------- Value of a Condition
7169:
1.713 albertel 7170: # gets the value of a specific preevaluated condition
7171: # stored in the string $env{user.state.<cid>}
7172: # or looks up a condition reference in the bighash and if if hasn't
7173: # already been evaluated recurses into docondval to get the value of
7174: # the condition, then memoizing it to
7175: # $env{user.state.<cid>.<condition>}
1.40 www 7176: sub directcondval {
7177: my $number=shift;
1.620 albertel 7178: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7179: &Apache::lonuserstate::evalstate();
7180: }
1.713 albertel 7181: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7182: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7183: } elsif ($number =~ /^_/) {
7184: my $sub_condition;
7185: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7186: &GDBM_READER(),0640)) {
7187: $sub_condition=$bighash{'conditions'.$number};
7188: untie(%bighash);
7189: }
7190: my $value = &docondval($sub_condition);
1.949 raeburn 7191: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7192: return $value;
7193: }
1.620 albertel 7194: if ($env{'user.state.'.$env{'request.course.id'}}) {
7195: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7196: } else {
7197: return 2;
7198: }
7199: }
7200:
1.713 albertel 7201: # get the collection of conditions for this resource
1.26 www 7202: sub condval {
7203: my $condidx=shift;
1.54 www 7204: my $allpathcond='';
1.713 albertel 7205: foreach my $cond (split(/\|/,$condidx)) {
7206: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7207: $allpathcond.=
7208: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7209: }
1.191 harris41 7210: }
1.54 www 7211: $allpathcond=~s/\|$//;
1.713 albertel 7212: return &docondval($allpathcond);
7213: }
7214:
7215: #evaluates an expression of conditions
7216: sub docondval {
7217: my ($allpathcond) = @_;
7218: my $result=0;
7219: if ($env{'request.course.id'}
7220: && defined($allpathcond)) {
7221: my $operand='|';
7222: my @stack;
7223: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7224: if ($chunk eq '(') {
7225: push @stack,($operand,$result);
7226: } elsif ($chunk eq ')') {
7227: my $before=pop @stack;
7228: if (pop @stack eq '&') {
7229: $result=$result>$before?$before:$result;
7230: } else {
7231: $result=$result>$before?$result:$before;
7232: }
7233: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7234: $operand=$chunk;
7235: } else {
7236: my $new=directcondval($chunk);
7237: if ($operand eq '&') {
7238: $result=$result>$new?$new:$result;
7239: } else {
7240: $result=$result>$new?$result:$new;
7241: }
7242: }
7243: }
1.26 www 7244: }
7245: return $result;
1.421 albertel 7246: }
7247:
7248: # ---------------------------------------------------- Devalidate courseresdata
7249:
7250: sub devalidatecourseresdata {
7251: my ($coursenum,$coursedomain)=@_;
7252: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7253: &devalidate_cache_new('courseres',$hashid);
1.28 www 7254: }
7255:
1.763 www 7256:
1.200 www 7257: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7258: #
7259: # Parameters:
7260: # $coursenum - Number of the course.
7261: # $coursedomain - Domain at which the course was created.
7262: # Returns:
7263: # A hash of the course parameters along (I think) with timestamps
7264: # and version info.
1.877 foxr 7265:
1.624 albertel 7266: sub get_courseresdata {
7267: my ($coursenum,$coursedomain)=@_;
1.200 www 7268: my $coursehom=&homeserver($coursenum,$coursedomain);
7269: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7270: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7271: my %dumpreply;
1.417 albertel 7272: unless (defined($cached)) {
1.624 albertel 7273: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7274: $result=\%dumpreply;
1.251 albertel 7275: my ($tmp) = keys(%dumpreply);
7276: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7277: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7278: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7279: return $tmp;
1.416 albertel 7280: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7281: $result=undef;
1.599 albertel 7282: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7283: }
7284: }
1.624 albertel 7285: return $result;
7286: }
7287:
1.633 albertel 7288: sub devalidateuserresdata {
7289: my ($uname,$udom)=@_;
7290: my $hashid="$udom:$uname";
7291: &devalidate_cache_new('userres',$hashid);
7292: }
7293:
1.624 albertel 7294: sub get_userresdata {
7295: my ($uname,$udom)=@_;
7296: #most student don\'t have any data set, check if there is some data
7297: if (&EXT_cache_status($udom,$uname)) { return undef; }
7298:
7299: my $hashid="$udom:$uname";
7300: my ($result,$cached)=&is_cached_new('userres',$hashid);
7301: if (!defined($cached)) {
7302: my %resourcedata=&dump('resourcedata',$udom,$uname);
7303: $result=\%resourcedata;
7304: &do_cache_new('userres',$hashid,$result,600);
7305: }
7306: my ($tmp)=keys(%$result);
7307: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7308: return $result;
7309: }
7310: #error 2 occurs when the .db doesn't exist
7311: if ($tmp!~/error: 2 /) {
1.672 albertel 7312: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7313: " Trying to get resource data for ".
7314: $uname." at ".$udom.": ".
7315: $tmp."</font>");
7316: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7317: #&EXT_cache_set($udom,$uname);
7318: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7319: undef($tmp); # not really an error so don't send it back
1.624 albertel 7320: }
7321: return $tmp;
7322: }
1.879 foxr 7323: #----------------------------------------------- resdata - return resource data
7324: # Purpose:
7325: # Return resource data for either users or for a course.
7326: # Parameters:
7327: # $name - Course/user name.
7328: # $domain - Name of the domain the user/course is registered on.
7329: # $type - Type of thing $name is (must be 'course' or 'user'
7330: # @which - Array of names of resources desired.
7331: # Returns:
7332: # The value of the first reasource in @which that is found in the
7333: # resource hash.
7334: # Exceptional Conditions:
7335: # If the $type passed in is not valid (not the string 'course' or
7336: # 'user', an undefined reference is returned.
7337: # If none of the resources are found, an undef is returned
1.624 albertel 7338: sub resdata {
7339: my ($name,$domain,$type,@which)=@_;
7340: my $result;
7341: if ($type eq 'course') {
7342: $result=&get_courseresdata($name,$domain);
7343: } elsif ($type eq 'user') {
7344: $result=&get_userresdata($name,$domain);
7345: }
7346: if (!ref($result)) { return $result; }
1.251 albertel 7347: foreach my $item (@which) {
1.927 albertel 7348: if (defined($result->{$item->[0]})) {
7349: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7350: }
1.250 albertel 7351: }
1.291 albertel 7352: return undef;
1.200 www 7353: }
7354:
1.379 matthew 7355: #
7356: # EXT resource caching routines
7357: #
7358:
7359: sub clear_EXT_cache_status {
1.383 albertel 7360: &delenv('cache.EXT.');
1.379 matthew 7361: }
7362:
7363: sub EXT_cache_status {
7364: my ($target_domain,$target_user) = @_;
1.383 albertel 7365: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7366: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7367: # We know already the user has no data
7368: return 1;
7369: } else {
7370: return 0;
7371: }
7372: }
7373:
7374: sub EXT_cache_set {
7375: my ($target_domain,$target_user) = @_;
1.383 albertel 7376: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7377: #&appenv({$cachename => time});
1.379 matthew 7378: }
7379:
1.28 www 7380: # --------------------------------------------------------- Value of a Variable
1.58 www 7381: sub EXT {
1.715 albertel 7382:
1.395 albertel 7383: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7384: unless ($varname) { return ''; }
1.218 albertel 7385: #get real user name/domain, courseid and symb
7386: my $courseid;
1.359 albertel 7387: my $publicuser;
1.427 www 7388: if ($symbparm) {
7389: $symbparm=&get_symb_from_alias($symbparm);
7390: }
1.218 albertel 7391: if (!($uname && $udom)) {
1.790 albertel 7392: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7393: if (!$symbparm) { $symbparm=$cursymb; }
7394: } else {
1.620 albertel 7395: $courseid=$env{'request.course.id'};
1.218 albertel 7396: }
1.48 www 7397: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7398: my $rest;
1.320 albertel 7399: if (defined($therest[0])) {
1.48 www 7400: $rest=join('.',@therest);
7401: } else {
7402: $rest='';
7403: }
1.320 albertel 7404:
1.57 www 7405: my $qualifierrest=$qualifier;
7406: if ($rest) { $qualifierrest.='.'.$rest; }
7407: my $spacequalifierrest=$space;
7408: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7409: if ($realm eq 'user') {
1.48 www 7410: # --------------------------------------------------------------- user.resource
7411: if ($space eq 'resource') {
1.651 albertel 7412: if ( (defined($Apache::lonhomework::parsing_a_problem)
7413: || defined($Apache::lonhomework::parsing_a_task))
7414: &&
1.744 albertel 7415: ($symbparm eq &symbread()) ) {
7416: # if we are in the middle of processing the resource the
7417: # get the value we are planning on committing
7418: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7419: return $Apache::lonhomework::results{$qualifierrest};
7420: } else {
7421: return $Apache::lonhomework::history{$qualifierrest};
7422: }
1.335 albertel 7423: } else {
1.359 albertel 7424: my %restored;
1.620 albertel 7425: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 7426: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7427: } else {
7428: %restored=&restore($symbparm,$courseid,$udom,$uname);
7429: }
1.335 albertel 7430: return $restored{$qualifierrest};
7431: }
1.48 www 7432: # ----------------------------------------------------------------- user.access
7433: } elsif ($space eq 'access') {
1.218 albertel 7434: # FIXME - not supporting calls for a specific user
1.48 www 7435: return &allowed($qualifier,$rest);
7436: # ------------------------------------------ user.preferences, user.environment
7437: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7438: if (($uname eq $env{'user.name'}) &&
7439: ($udom eq $env{'user.domain'})) {
7440: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7441: } else {
1.359 albertel 7442: my %returnhash;
7443: if (!$publicuser) {
7444: %returnhash=&userenvironment($udom,$uname,
7445: $qualifierrest);
7446: }
1.218 albertel 7447: return $returnhash{$qualifierrest};
7448: }
1.48 www 7449: # ----------------------------------------------------------------- user.course
7450: } elsif ($space eq 'course') {
1.218 albertel 7451: # FIXME - not supporting calls for a specific user
1.620 albertel 7452: return $env{join('.',('request.course',$qualifier))};
1.48 www 7453: # ------------------------------------------------------------------- user.role
7454: } elsif ($space eq 'role') {
1.218 albertel 7455: # FIXME - not supporting calls for a specific user
1.620 albertel 7456: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7457: if ($qualifier eq 'value') {
7458: return $role;
7459: } elsif ($qualifier eq 'extent') {
7460: return $where;
7461: }
7462: # ----------------------------------------------------------------- user.domain
7463: } elsif ($space eq 'domain') {
1.218 albertel 7464: return $udom;
1.48 www 7465: # ------------------------------------------------------------------- user.name
7466: } elsif ($space eq 'name') {
1.218 albertel 7467: return $uname;
1.48 www 7468: # ---------------------------------------------------- Any other user namespace
1.29 www 7469: } else {
1.359 albertel 7470: my %reply;
7471: if (!$publicuser) {
7472: %reply=&get($space,[$qualifierrest],$udom,$uname);
7473: }
7474: return $reply{$qualifierrest};
1.48 www 7475: }
1.236 www 7476: } elsif ($realm eq 'query') {
7477: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7478: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7479: [$spacequalifierrest]);
1.620 albertel 7480: return $env{'form.'.$spacequalifierrest};
1.236 www 7481: } elsif ($realm eq 'request') {
1.48 www 7482: # ------------------------------------------------------------- request.browser
7483: if ($space eq 'browser') {
1.430 www 7484: if ($qualifier eq 'textremote') {
1.676 albertel 7485: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7486: return 1;
7487: } else {
7488: return 0;
7489: }
7490: } else {
1.620 albertel 7491: return $env{'browser.'.$qualifier};
1.430 www 7492: }
1.57 www 7493: # ------------------------------------------------------------ request.filename
7494: } else {
1.620 albertel 7495: return $env{'request.'.$spacequalifierrest};
1.29 www 7496: }
1.28 www 7497: } elsif ($realm eq 'course') {
1.48 www 7498: # ---------------------------------------------------------- course.description
1.620 albertel 7499: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7500: } elsif ($realm eq 'resource') {
1.165 www 7501:
1.620 albertel 7502: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7503: if (!$symbparm) { $symbparm=&symbread(); }
7504: }
1.693 albertel 7505:
7506: if ($space eq 'title') {
7507: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7508: return &gettitle($symbparm);
7509: }
7510:
7511: if ($space eq 'map') {
7512: my ($map) = &decode_symb($symbparm);
7513: return &symbread($map);
7514: }
1.905 albertel 7515: if ($space eq 'filename') {
7516: if ($symbparm) {
7517: return &clutter((&decode_symb($symbparm))[2]);
7518: }
7519: return &hreflocation('',$env{'request.filename'});
7520: }
1.693 albertel 7521:
7522: my ($section, $group, @groups);
1.593 albertel 7523: my ($courselevelm,$courselevel);
1.539 albertel 7524: if ($symbparm && defined($courseid) &&
1.620 albertel 7525: $courseid eq $env{'request.course.id'}) {
1.165 www 7526:
1.218 albertel 7527: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7528:
1.60 www 7529: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7530: my $symbp=$symbparm;
1.735 albertel 7531: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7532:
7533: my $symbparm=$symbp.'.'.$spacequalifierrest;
7534: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7535:
1.620 albertel 7536: if (($env{'user.name'} eq $uname) &&
7537: ($env{'user.domain'} eq $udom)) {
7538: $section=$env{'request.course.sec'};
1.733 raeburn 7539: @groups = split(/:/,$env{'request.course.groups'});
7540: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7541: } else {
1.539 albertel 7542: if (! defined($usection)) {
1.551 albertel 7543: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7544: } else {
7545: $section = $usection;
7546: }
1.733 raeburn 7547: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7548: }
7549:
7550: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7551: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7552: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7553:
1.593 albertel 7554: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7555: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7556: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7557:
1.60 www 7558: # ----------------------------------------------------------- first, check user
1.624 albertel 7559:
7560: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7561: ([$courselevelr,'resource'],
7562: [$courselevelm,'map' ],
7563: [$courselevel, 'course' ]));
1.931 albertel 7564: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7565:
1.594 albertel 7566: # ------------------------------------------------ second, check some of course
1.684 raeburn 7567: my $coursereply;
1.691 raeburn 7568: if (@groups > 0) {
7569: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7570: $mapparm,$spacequalifierrest);
1.927 albertel 7571: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7572: }
1.96 www 7573:
1.684 raeburn 7574: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7575: $env{'course.'.$courseid.'.domain'},
7576: 'course',
7577: ([$seclevelr, 'resource'],
7578: [$seclevelm, 'map' ],
7579: [$seclevel, 'course' ],
7580: [$courselevelr,'resource']));
7581: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7582:
1.60 www 7583: # ------------------------------------------------------ third, check map parms
1.218 albertel 7584: my %parmhash=();
7585: my $thisparm='';
7586: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7587: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7588: &GDBM_READER(),0640)) {
1.218 albertel 7589: $thisparm=$parmhash{$symbparm};
7590: untie(%parmhash);
7591: }
1.927 albertel 7592: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7593: }
1.594 albertel 7594: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7595:
1.218 albertel 7596: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7597: my $filename;
7598: if (!$symbparm) { $symbparm=&symbread(); }
7599: if ($symbparm) {
1.409 www 7600: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7601: } else {
1.620 albertel 7602: $filename=$env{'request.filename'};
1.282 albertel 7603: }
7604: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7605: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7606: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7607: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7608:
1.927 albertel 7609: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7610: if ($symbparm && defined($courseid) &&
1.620 albertel 7611: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7612: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7613: $env{'course.'.$courseid.'.domain'},
7614: 'course',
1.927 albertel 7615: ([$courselevelm,'map' ],
7616: [$courselevel, 'course']));
7617: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7618: }
1.145 www 7619: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7620: unless ($space eq '0') {
1.336 albertel 7621: my @parts=split(/_/,$space);
7622: my $id=pop(@parts);
7623: my $part=join('_',@parts);
7624: if ($part eq '') { $part='0'; }
1.927 albertel 7625: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7626: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7627: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7628: }
1.395 albertel 7629: if ($recurse) { return undef; }
7630: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 7631: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 7632: # ---------------------------------------------------- Any other user namespace
7633: } elsif ($realm eq 'environment') {
7634: # ----------------------------------------------------------------- environment
1.620 albertel 7635: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7636: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 7637: } else {
1.770 albertel 7638: if ($uname eq 'anonymous' && $udom eq '') {
7639: return '';
7640: }
1.219 albertel 7641: my %returnhash=&userenvironment($udom,$uname,
7642: $spacequalifierrest);
7643: return $returnhash{$spacequalifierrest};
7644: }
1.28 www 7645: } elsif ($realm eq 'system') {
1.48 www 7646: # ----------------------------------------------------------------- system.time
7647: if ($space eq 'time') {
7648: return time;
7649: }
1.696 albertel 7650: } elsif ($realm eq 'server') {
7651: # ----------------------------------------------------------------- system.time
7652: if ($space eq 'name') {
7653: return $ENV{'SERVER_NAME'};
7654: }
1.28 www 7655: }
1.48 www 7656: return '';
1.61 www 7657: }
7658:
1.927 albertel 7659: sub get_reply {
7660: my ($reply_value) = @_;
1.940 raeburn 7661: if (ref($reply_value) eq 'ARRAY') {
7662: if (wantarray) {
7663: return @$reply_value;
7664: }
7665: return $reply_value->[0];
7666: } else {
7667: return $reply_value;
1.927 albertel 7668: }
7669: }
7670:
1.691 raeburn 7671: sub check_group_parms {
7672: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7673: my @groupitems = ();
7674: my $resultitem;
1.927 albertel 7675: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 7676: foreach my $group (@{$groups}) {
7677: foreach my $level (@levels) {
1.927 albertel 7678: my $item = $courseid.'.['.$group.'].'.$level->[0];
7679: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 7680: }
7681: }
7682: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7683: $env{'course.'.$courseid.'.domain'},
7684: 'course',@groupitems);
7685: return $coursereply;
7686: }
7687:
7688: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 7689: my ($courseid,@groups) = @_;
7690: @groups = sort(@groups);
1.691 raeburn 7691: return @groups;
7692: }
7693:
1.395 albertel 7694: sub packages_tab_default {
7695: my ($uri,$varname)=@_;
7696: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 7697:
7698: my (@extension,@specifics,$do_default);
7699: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 7700: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 7701: if ($pack_type eq 'default') {
7702: $do_default=1;
7703: } elsif ($pack_type eq 'extension') {
7704: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 7705: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 7706: # only look at packages defaults for packages that this id is
1.738 albertel 7707: push(@specifics,[$package,$pack_type,$pack_part]);
7708: }
7709: }
7710: # first look for a package that matches the requested part id
7711: foreach my $package (@specifics) {
7712: my (undef,$pack_type,$pack_part)=@{$package};
7713: next if ($pack_part ne $part);
7714: if (defined($packagetab{"$pack_type&$name&default"})) {
7715: return $packagetab{"$pack_type&$name&default"};
7716: }
7717: }
7718: # look for any possible matching non extension_ package
7719: foreach my $package (@specifics) {
7720: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 7721: if (defined($packagetab{"$pack_type&$name&default"})) {
7722: return $packagetab{"$pack_type&$name&default"};
7723: }
1.585 albertel 7724: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 7725: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7726: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 7727: }
7728: }
1.738 albertel 7729: # look for any posible extension_ match
7730: foreach my $package (@extension) {
7731: my ($package,$pack_type)=@{$package};
7732: if (defined($packagetab{"$pack_type&$name&default"})) {
7733: return $packagetab{"$pack_type&$name&default"};
7734: }
7735: if (defined($packagetab{$package."&$name&default"})) {
7736: return $packagetab{$package."&$name&default"};
7737: }
7738: }
7739: # look for a global default setting
7740: if ($do_default && defined($packagetab{"default&$name&default"})) {
7741: return $packagetab{"default&$name&default"};
7742: }
1.395 albertel 7743: return undef;
7744: }
7745:
1.334 albertel 7746: sub add_prefix_and_part {
7747: my ($prefix,$part)=@_;
7748: my $keyroot;
7749: if (defined($prefix) && $prefix !~ /^__/) {
7750: # prefix that has a part already
7751: $keyroot=$prefix;
7752: } elsif (defined($prefix)) {
7753: # prefix that is missing a part
7754: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7755: } else {
7756: # no prefix at all
7757: if (defined($part)) { $keyroot='_'.$part; }
7758: }
7759: return $keyroot;
7760: }
7761:
1.71 www 7762: # ---------------------------------------------------------------- Get metadata
7763:
1.599 albertel 7764: my %metaentry;
1.71 www 7765: sub metadata {
1.176 www 7766: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 7767: $uri=&declutter($uri);
1.288 albertel 7768: # if it is a non metadata possible uri return quickly
1.529 albertel 7769: if (($uri eq '') ||
7770: (($uri =~ m|^/*adm/|) &&
1.698 albertel 7771: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 7772: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7773: return undef;
7774: }
7775: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7776: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 7777: return undef;
1.288 albertel 7778: }
1.73 www 7779: my $filename=$uri;
7780: $uri=~s/\.meta$//;
1.172 www 7781: #
7782: # Is the metadata already cached?
1.177 www 7783: # Look at timestamp of caching
1.172 www 7784: # Everything is cached by the main uri, libraries are never directly cached
7785: #
1.428 albertel 7786: if (!defined($liburi)) {
1.599 albertel 7787: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 7788: if (defined($cached)) { return $result->{':'.$what}; }
7789: }
7790: {
1.172 www 7791: #
7792: # Is this a recursive call for a library?
7793: #
1.599 albertel 7794: # if (! exists($metacache{$uri})) {
7795: # $metacache{$uri}={};
7796: # }
1.924 albertel 7797: my $cachetime = 60*60;
1.171 www 7798: if ($liburi) {
7799: $liburi=&declutter($liburi);
7800: $filename=$liburi;
1.401 bowersj2 7801: } else {
1.599 albertel 7802: &devalidate_cache_new('meta',$uri);
7803: undef(%metaentry);
1.401 bowersj2 7804: }
1.140 www 7805: my %metathesekeys=();
1.73 www 7806: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 7807: my $metastring;
1.924 albertel 7808: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 7809: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 7810: $metastring =
1.929 albertel 7811: &Apache::lonnet::ssi_body($which,
1.924 albertel 7812: ('grade_target' => 'meta'));
7813: $cachetime = 1; # only want this cached in the child not long term
7814: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 7815: my $file=&filelocation('',&clutter($filename));
1.599 albertel 7816: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 7817: $metastring=&getfile($file);
1.489 albertel 7818: }
1.208 albertel 7819: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 7820: my $token;
1.140 www 7821: undef %metathesekeys;
1.71 www 7822: while ($token=$parser->get_token) {
1.339 albertel 7823: if ($token->[0] eq 'S') {
7824: if (defined($token->[2]->{'package'})) {
1.172 www 7825: #
7826: # This is a package - get package info
7827: #
1.339 albertel 7828: my $package=$token->[2]->{'package'};
7829: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7830: if (defined($token->[2]->{'id'})) {
7831: $keyroot.='_'.$token->[2]->{'id'};
7832: }
1.599 albertel 7833: if ($metaentry{':packages'}) {
7834: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 7835: } else {
1.599 albertel 7836: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 7837: }
1.736 albertel 7838: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 7839: my $part=$keyroot;
7840: $part=~s/^\_//;
1.736 albertel 7841: if ($pack_entry=~/^\Q$package\E\&/ ||
7842: $pack_entry=~/^\Q$package\E_0\&/) {
7843: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 7844: # ignore package.tab specified default values
7845: # here &package_tab_default() will fetch those
7846: if ($subp eq 'default') { next; }
1.736 albertel 7847: my $value=$packagetab{$pack_entry};
1.432 albertel 7848: my $unikey;
7849: if ($pack =~ /_0$/) {
7850: $unikey='parameter_0_'.$name;
7851: $part=0;
7852: } else {
7853: $unikey='parameter'.$keyroot.'_'.$name;
7854: }
1.339 albertel 7855: if ($subp eq 'display') {
7856: $value.=' [Part: '.$part.']';
7857: }
1.599 albertel 7858: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 7859: $metathesekeys{$unikey}=1;
1.599 albertel 7860: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7861: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 7862: }
1.599 albertel 7863: if (defined($metaentry{':'.$unikey.'.default'})) {
7864: $metaentry{':'.$unikey}=
7865: $metaentry{':'.$unikey.'.default'};
1.356 albertel 7866: }
1.339 albertel 7867: }
7868: }
7869: } else {
1.172 www 7870: #
7871: # This is not a package - some other kind of start tag
1.339 albertel 7872: #
7873: my $entry=$token->[1];
7874: my $unikey;
7875: if ($entry eq 'import') {
7876: $unikey='';
7877: } else {
7878: $unikey=$entry;
7879: }
7880: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7881:
7882: if (defined($token->[2]->{'id'})) {
7883: $unikey.='_'.$token->[2]->{'id'};
7884: }
1.175 www 7885:
1.339 albertel 7886: if ($entry eq 'import') {
1.175 www 7887: #
7888: # Importing a library here
1.339 albertel 7889: #
7890: if ($depthcount<20) {
7891: my $location=$parser->get_text('/import');
7892: my $dir=$filename;
7893: $dir=~s|[^/]*$||;
7894: $location=&filelocation($dir,$location);
1.736 albertel 7895: my $metadata =
7896: &metadata($uri,'keys', $location,$unikey,
7897: $depthcount+1);
7898: foreach my $meta (split(',',$metadata)) {
7899: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7900: $metathesekeys{$meta}=1;
1.339 albertel 7901: }
7902: }
7903: } else {
7904:
7905: if (defined($token->[2]->{'name'})) {
7906: $unikey.='_'.$token->[2]->{'name'};
7907: }
7908: $metathesekeys{$unikey}=1;
1.736 albertel 7909: foreach my $param (@{$token->[3]}) {
7910: $metaentry{':'.$unikey.'.'.$param} =
7911: $token->[2]->{$param};
1.339 albertel 7912: }
7913: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 7914: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 7915: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7916: # only ws inside the tag, and not in default, so use default
7917: # as value
1.599 albertel 7918: $metaentry{':'.$unikey}=$default;
1.908 albertel 7919: } elsif ( $internaltext =~ /\S/ ) {
7920: # something interesting inside the tag
7921: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 7922: } else {
1.908 albertel 7923: # no interesting values, don't set a default
1.339 albertel 7924: }
1.172 www 7925: # end of not-a-package not-a-library import
1.339 albertel 7926: }
1.172 www 7927: # end of not-a-package start tag
1.339 albertel 7928: }
1.172 www 7929: # the next is the end of "start tag"
1.339 albertel 7930: }
7931: }
1.483 albertel 7932: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 7933: $extension = lc($extension);
7934: if ($extension eq 'htm') { $extension='html'; }
7935:
1.737 albertel 7936: foreach my $key (keys(%packagetab)) {
1.483 albertel 7937: #no specific packages #how's our extension
7938: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 7939: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 7940: \%metathesekeys);
7941: }
1.883 albertel 7942:
7943: if (!exists($metaentry{':packages'})
7944: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 7945: foreach my $key (keys(%packagetab)) {
1.483 albertel 7946: #no specific packages well let's get default then
7947: if ($key!~/^default&/) { next; }
1.488 albertel 7948: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 7949: \%metathesekeys);
7950: }
7951: }
1.338 www 7952: # are there custom rights to evaluate
1.599 albertel 7953: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 7954:
1.338 www 7955: #
7956: # Importing a rights file here
1.339 albertel 7957: #
7958: unless ($depthcount) {
1.599 albertel 7959: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 7960: my $dir=$filename;
7961: $dir=~s|[^/]*$||;
7962: $location=&filelocation($dir,$location);
1.736 albertel 7963: my $rights_metadata =
7964: &metadata($uri,'keys',$location,'_rights',
7965: $depthcount+1);
7966: foreach my $rights (split(',',$rights_metadata)) {
7967: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7968: $metathesekeys{$rights}=1;
1.339 albertel 7969: }
7970: }
7971: }
1.737 albertel 7972: # uniqifiy package listing
7973: my %seen;
7974: my @uniq_packages =
7975: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7976: $metaentry{':packages'} = join(',',@uniq_packages);
7977:
7978: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 7979: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7980: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 7981: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 7982: # this is the end of "was not already recently cached
1.71 www 7983: }
1.599 albertel 7984: return $metaentry{':'.$what};
1.261 albertel 7985: }
7986:
1.488 albertel 7987: sub metadata_create_package_def {
1.483 albertel 7988: my ($uri,$key,$package,$metathesekeys)=@_;
7989: my ($pack,$name,$subp)=split(/\&/,$key);
7990: if ($subp eq 'default') { next; }
7991:
1.599 albertel 7992: if (defined($metaentry{':packages'})) {
7993: $metaentry{':packages'}.=','.$package;
1.483 albertel 7994: } else {
1.599 albertel 7995: $metaentry{':packages'}=$package;
1.483 albertel 7996: }
7997: my $value=$packagetab{$key};
7998: my $unikey;
7999: $unikey='parameter_0_'.$name;
1.599 albertel 8000: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8001: $$metathesekeys{$unikey}=1;
1.599 albertel 8002: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8003: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8004: }
1.599 albertel 8005: if (defined($metaentry{':'.$unikey.'.default'})) {
8006: $metaentry{':'.$unikey}=
8007: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8008: }
8009: }
8010:
1.261 albertel 8011: sub metadata_generate_part0 {
8012: my ($metadata,$metacache,$uri) = @_;
8013: my %allnames;
1.737 albertel 8014: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8015: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8016: my $part=$$metacache{':'.$metakey.'.part'};
8017: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8018: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8019: $allnames{$name}=$part;
8020: }
8021: }
8022: }
8023: foreach my $name (keys(%allnames)) {
8024: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8025: my $key=":parameter_0_$name";
1.261 albertel 8026: $$metacache{"$key.part"}='0';
8027: $$metacache{"$key.name"}=$name;
1.428 albertel 8028: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8029: $allnames{$name}.'_'.$name.
8030: '.type'};
1.428 albertel 8031: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8032: '.display'};
1.644 www 8033: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8034: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8035: $$metacache{"$key.display"}=$olddis;
8036: }
1.71 www 8037: }
8038:
1.764 albertel 8039: # ------------------------------------------------------ Devalidate title cache
8040:
8041: sub devalidate_title_cache {
8042: my ($url)=@_;
8043: if (!$env{'request.course.id'}) { return; }
8044: my $symb=&symbread($url);
8045: if (!$symb) { return; }
8046: my $key=$env{'request.course.id'}."\0".$symb;
8047: &devalidate_cache_new('title',$key);
8048: }
8049:
1.1014 droeschl 8050: # ------------------------------------------------- Get the title of a course
8051:
8052: sub current_course_title {
8053: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8054: }
1.301 www 8055: # ------------------------------------------------- Get the title of a resource
8056:
8057: sub gettitle {
8058: my $urlsymb=shift;
8059: my $symb=&symbread($urlsymb);
1.534 albertel 8060: if ($symb) {
1.620 albertel 8061: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8062: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8063: if (defined($cached)) {
8064: return $result;
8065: }
1.534 albertel 8066: my ($map,$resid,$url)=&decode_symb($symb);
8067: my $title='';
1.907 albertel 8068: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8069: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8070: } else {
8071: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8072: &GDBM_READER(),0640)) {
8073: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8074: $title=$bighash{'title_'.$mapid.'.'.$resid};
8075: untie(%bighash);
8076: }
1.534 albertel 8077: }
8078: $title=~s/\&colon\;/\:/gs;
8079: if ($title) {
1.599 albertel 8080: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8081: }
8082: $urlsymb=$url;
8083: }
8084: my $title=&metadata($urlsymb,'title');
8085: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8086: return $title;
1.301 www 8087: }
1.613 albertel 8088:
1.614 albertel 8089: sub get_slot {
8090: my ($which,$cnum,$cdom)=@_;
8091: if (!$cnum || !$cdom) {
1.790 albertel 8092: (undef,my $courseid)=&whichuser();
1.620 albertel 8093: $cdom=$env{'course.'.$courseid.'.domain'};
8094: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8095: }
1.703 albertel 8096: my $key=join("\0",'slots',$cdom,$cnum,$which);
8097: my %slotinfo;
8098: if (exists($remembered{$key})) {
8099: $slotinfo{$which} = $remembered{$key};
8100: } else {
8101: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8102: &Apache::lonhomework::showhash(%slotinfo);
8103: my ($tmp)=keys(%slotinfo);
8104: if ($tmp=~/^error:/) { return (); }
8105: $remembered{$key} = $slotinfo{$which};
8106: }
1.616 albertel 8107: if (ref($slotinfo{$which}) eq 'HASH') {
8108: return %{$slotinfo{$which}};
8109: }
8110: return $slotinfo{$which};
1.614 albertel 8111: }
1.31 www 8112: # ------------------------------------------------- Update symbolic store links
8113:
8114: sub symblist {
8115: my ($mapname,%newhash)=@_;
1.438 www 8116: $mapname=&deversion(&declutter($mapname));
1.31 www 8117: my %hash;
1.620 albertel 8118: if (($env{'request.course.fn'}) && (%newhash)) {
8119: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8120: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8121: foreach my $url (keys(%newhash)) {
1.711 albertel 8122: next if ($url eq 'last_known'
8123: && $env{'form.no_update_last_known'});
8124: $hash{declutter($url)}=&encode_symb($mapname,
8125: $newhash{$url}->[1],
8126: $newhash{$url}->[0]);
1.191 harris41 8127: }
1.31 www 8128: if (untie(%hash)) {
8129: return 'ok';
8130: }
8131: }
8132: }
8133: return 'error';
1.212 www 8134: }
8135:
8136: # --------------------------------------------------------------- Verify a symb
8137:
8138: sub symbverify {
1.510 www 8139: my ($symb,$thisurl)=@_;
8140: my $thisfn=$thisurl;
1.439 www 8141: $thisfn=&declutter($thisfn);
1.215 www 8142: # direct jump to resource in page or to a sequence - will construct own symbs
8143: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8144: # check URL part
1.409 www 8145: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8146:
1.431 www 8147: unless ($url eq $thisfn) { return 0; }
1.213 www 8148:
1.216 www 8149: $symb=&symbclean($symb);
1.510 www 8150: $thisurl=&deversion($thisurl);
1.439 www 8151: $thisfn=&deversion($thisfn);
1.213 www 8152:
8153: my %bighash;
8154: my $okay=0;
1.431 www 8155:
1.620 albertel 8156: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8157: &GDBM_READER(),0640)) {
1.510 www 8158: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8159: unless ($ids) {
1.510 www 8160: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8161: }
8162: if ($ids) {
8163: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8164: foreach my $id (split(/\,/,$ids)) {
8165: my ($mapid,$resid)=split(/\./,$id);
1.216 www 8166: if (
8167: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8168: eq $symb) {
1.620 albertel 8169: if (($env{'request.role.adv'}) ||
1.800 albertel 8170: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8171: $okay=1;
8172: }
8173: }
1.216 www 8174: }
8175: }
1.213 www 8176: untie(%bighash);
8177: }
8178: return $okay;
1.31 www 8179: }
8180:
1.210 www 8181: # --------------------------------------------------------------- Clean-up symb
8182:
8183: sub symbclean {
8184: my $symb=shift;
1.568 albertel 8185: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8186: # remove version from map
8187: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8188:
1.210 www 8189: # remove version from URL
8190: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8191:
1.507 www 8192: # remove wrapper
8193:
1.510 www 8194: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8195: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8196: return $symb;
1.409 www 8197: }
8198:
8199: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8200:
8201: sub encode_symb {
8202: my ($map,$resid,$url)=@_;
8203: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8204: }
1.409 www 8205:
8206: sub decode_symb {
1.568 albertel 8207: my $symb=shift;
8208: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8209: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8210: return (&fixversion($map),$resid,&fixversion($url));
8211: }
8212:
8213: sub fixversion {
8214: my $fn=shift;
1.609 banghart 8215: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8216: my %bighash;
8217: my $uri=&clutter($fn);
1.620 albertel 8218: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8219: # is this cached?
1.599 albertel 8220: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8221: if (defined($cached)) { return $result; }
8222: # unfortunately not cached, or expired
1.620 albertel 8223: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8224: &GDBM_READER(),0640)) {
8225: if ($bighash{'version_'.$uri}) {
8226: my $version=$bighash{'version_'.$uri};
1.444 www 8227: unless (($version eq 'mostrecent') ||
8228: ($version==&getversion($uri))) {
1.440 www 8229: $uri=~s/\.(\w+)$/\.$version\.$1/;
8230: }
8231: }
8232: untie %bighash;
1.413 www 8233: }
1.599 albertel 8234: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8235: }
8236:
8237: sub deversion {
8238: my $url=shift;
8239: $url=~s/\.\d+\.(\w+)$/\.$1/;
8240: return $url;
1.210 www 8241: }
8242:
1.31 www 8243: # ------------------------------------------------------ Return symb list entry
8244:
8245: sub symbread {
1.249 www 8246: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8247: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8248: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8249: # no filename provided? try from environment
1.44 www 8250: unless ($thisfn) {
1.620 albertel 8251: if ($env{'request.symb'}) {
8252: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8253: }
1.620 albertel 8254: $thisfn=$env{'request.filename'};
1.44 www 8255: }
1.569 albertel 8256: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8257: # is that filename actually a symb? Verify, clean, and return
8258: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8259: if (&symbverify($thisfn,$1)) {
1.620 albertel 8260: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8261: }
1.242 www 8262: }
1.44 www 8263: $thisfn=declutter($thisfn);
1.31 www 8264: my %hash;
1.37 www 8265: my %bighash;
8266: my $syval='';
1.620 albertel 8267: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8268: my $targetfn = $thisfn;
1.609 banghart 8269: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8270: $targetfn = 'adm/wrapper/'.$thisfn;
8271: }
1.687 albertel 8272: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8273: $targetfn=$1;
8274: }
1.620 albertel 8275: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8276: &GDBM_READER(),0640)) {
1.481 raeburn 8277: $syval=$hash{$targetfn};
1.37 www 8278: untie(%hash);
8279: }
8280: # ---------------------------------------------------------- There was an entry
8281: if ($syval) {
1.601 albertel 8282: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8283: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8284: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8285: #return $env{$cache_str}='';
1.601 albertel 8286: #}
8287: #$syval.=$1;
8288: #}
1.37 www 8289: } else {
8290: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8291: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8292: &GDBM_READER(),0640)) {
1.37 www 8293: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8294: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8295: unless ($ids) {
8296: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8297: }
8298: unless ($ids) {
8299: # alias?
8300: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8301: }
1.37 www 8302: if ($ids) {
8303: # ------------------------------------------------------------------- Has ID(s)
8304: my @possibilities=split(/\,/,$ids);
1.39 www 8305: if ($#possibilities==0) {
8306: # ----------------------------------------------- There is only one possibility
1.37 www 8307: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8308: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8309: $resid,$thisfn);
1.249 www 8310: } elsif (!$donotrecurse) {
1.39 www 8311: # ------------------------------------------ There is more than one possibility
8312: my $realpossible=0;
1.800 albertel 8313: foreach my $id (@possibilities) {
8314: my $file=$bighash{'src_'.$id};
1.39 www 8315: if (&allowed('bre',$file)) {
1.800 albertel 8316: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8317: if ($bighash{'map_type_'.$mapid} ne 'page') {
8318: $realpossible++;
1.626 albertel 8319: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8320: $resid,$thisfn);
1.39 www 8321: }
8322: }
1.191 harris41 8323: }
1.39 www 8324: if ($realpossible!=1) { $syval=''; }
1.249 www 8325: } else {
8326: $syval='';
1.37 www 8327: }
8328: }
8329: untie(%bighash)
1.481 raeburn 8330: }
1.31 www 8331: }
1.62 www 8332: if ($syval) {
1.620 albertel 8333: return $env{$cache_str}=$syval;
1.62 www 8334: }
1.31 www 8335: }
1.949 raeburn 8336: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8337: return $env{$cache_str}='';
1.31 www 8338: }
8339:
8340: # ---------------------------------------------------------- Return random seed
8341:
1.32 www 8342: sub numval {
8343: my $txt=shift;
8344: $txt=~tr/A-J/0-9/;
8345: $txt=~tr/a-j/0-9/;
8346: $txt=~tr/K-T/0-9/;
8347: $txt=~tr/k-t/0-9/;
8348: $txt=~tr/U-Z/0-5/;
8349: $txt=~tr/u-z/0-5/;
8350: $txt=~s/\D//g;
1.564 albertel 8351: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8352: return int($txt);
1.368 albertel 8353: }
8354:
1.484 albertel 8355: sub numval2 {
8356: my $txt=shift;
8357: $txt=~tr/A-J/0-9/;
8358: $txt=~tr/a-j/0-9/;
8359: $txt=~tr/K-T/0-9/;
8360: $txt=~tr/k-t/0-9/;
8361: $txt=~tr/U-Z/0-5/;
8362: $txt=~tr/u-z/0-5/;
8363: $txt=~s/\D//g;
8364: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8365: my $total;
8366: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8367: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 8368: return int($total);
8369: }
8370:
1.575 albertel 8371: sub numval3 {
8372: use integer;
8373: my $txt=shift;
8374: $txt=~tr/A-J/0-9/;
8375: $txt=~tr/a-j/0-9/;
8376: $txt=~tr/K-T/0-9/;
8377: $txt=~tr/k-t/0-9/;
8378: $txt=~tr/U-Z/0-5/;
8379: $txt=~tr/u-z/0-5/;
8380: $txt=~s/\D//g;
8381: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8382: my $total;
8383: foreach my $val (@txts) { $total+=$val; }
8384: if ($_64bit) { $total=(($total<<32)>>32); }
8385: return $total;
8386: }
8387:
1.675 albertel 8388: sub digest {
8389: my ($data)=@_;
8390: my $digest=&Digest::MD5::md5($data);
8391: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8392: my ($e,$f);
8393: {
8394: use integer;
8395: $e=($a+$b);
8396: $f=($c+$d);
8397: if ($_64bit) {
8398: $e=(($e<<32)>>32);
8399: $f=(($f<<32)>>32);
8400: }
8401: }
8402: if (wantarray) {
8403: return ($e,$f);
8404: } else {
8405: my $g;
8406: {
8407: use integer;
8408: $g=($e+$f);
8409: if ($_64bit) {
8410: $g=(($g<<32)>>32);
8411: }
8412: }
8413: return $g;
8414: }
8415: }
8416:
1.368 albertel 8417: sub latest_rnd_algorithm_id {
1.675 albertel 8418: return '64bit5';
1.366 albertel 8419: }
1.32 www 8420:
1.503 albertel 8421: sub get_rand_alg {
8422: my ($courseid)=@_;
1.790 albertel 8423: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 8424: if ($courseid) {
1.620 albertel 8425: return $env{"course.$courseid.rndseed"};
1.503 albertel 8426: }
8427: return &latest_rnd_algorithm_id();
8428: }
8429:
1.562 albertel 8430: sub validCODE {
8431: my ($CODE)=@_;
8432: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8433: return 0;
8434: }
8435:
1.491 albertel 8436: sub getCODE {
1.620 albertel 8437: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 8438: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8439: defined($Apache::lonhomework::parsing_a_task) ) &&
8440: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 8441: return $Apache::lonhomework::history{'resource.CODE'};
8442: }
8443: return undef;
8444: }
8445:
1.31 www 8446: sub rndseed {
1.155 albertel 8447: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8448: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8449: if (!defined($symb)) {
1.366 albertel 8450: unless ($symb=$wsymb) { return time; }
8451: }
8452: if (!$courseid) { $courseid=$wcourseid; }
8453: if (!$domain) { $domain=$wdomain; }
8454: if (!$username) { $username=$wusername }
1.503 albertel 8455: my $which=&get_rand_alg();
1.803 albertel 8456:
1.491 albertel 8457: if (defined(&getCODE())) {
1.675 albertel 8458: if ($which eq '64bit5') {
8459: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8460: } elsif ($which eq '64bit4') {
1.575 albertel 8461: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8462: } else {
8463: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8464: }
1.675 albertel 8465: } elsif ($which eq '64bit5') {
8466: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8467: } elsif ($which eq '64bit4') {
8468: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8469: } elsif ($which eq '64bit3') {
8470: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8471: } elsif ($which eq '64bit2') {
8472: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8473: } elsif ($which eq '64bit') {
8474: return &rndseed_64bit($symb,$courseid,$domain,$username);
8475: }
8476: return &rndseed_32bit($symb,$courseid,$domain,$username);
8477: }
8478:
8479: sub rndseed_32bit {
8480: my ($symb,$courseid,$domain,$username)=@_;
8481: {
8482: use integer;
8483: my $symbchck=unpack("%32C*",$symb) << 27;
8484: my $symbseed=numval($symb) << 22;
8485: my $namechck=unpack("%32C*",$username) << 17;
8486: my $nameseed=numval($username) << 12;
8487: my $domainseed=unpack("%32C*",$domain) << 7;
8488: my $courseseed=unpack("%32C*",$courseid);
8489: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8490: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8491: #&logthis("rndseed :$num:$symb");
1.564 albertel 8492: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8493: return $num;
8494: }
8495: }
8496:
8497: sub rndseed_64bit {
8498: my ($symb,$courseid,$domain,$username)=@_;
8499: {
8500: use integer;
8501: my $symbchck=unpack("%32S*",$symb) << 21;
8502: my $symbseed=numval($symb) << 10;
8503: my $namechck=unpack("%32S*",$username);
8504:
8505: my $nameseed=numval($username) << 21;
8506: my $domainseed=unpack("%32S*",$domain) << 10;
8507: my $courseseed=unpack("%32S*",$courseid);
8508:
8509: my $num1=$symbchck+$symbseed+$namechck;
8510: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8511: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8512: #&logthis("rndseed :$num:$symb");
1.564 albertel 8513: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8514: return "$num1,$num2";
1.155 albertel 8515: }
1.366 albertel 8516: }
8517:
1.443 albertel 8518: sub rndseed_64bit2 {
8519: my ($symb,$courseid,$domain,$username)=@_;
8520: {
8521: use integer;
8522: # strings need to be an even # of cahracters long, it it is odd the
8523: # last characters gets thrown away
8524: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8525: my $symbseed=numval($symb) << 10;
8526: my $namechck=unpack("%32S*",$username.' ');
8527:
8528: my $nameseed=numval($username) << 21;
1.501 albertel 8529: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8530: my $courseseed=unpack("%32S*",$courseid.' ');
8531:
8532: my $num1=$symbchck+$symbseed+$namechck;
8533: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8534: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8535: #&logthis("rndseed :$num:$symb");
1.803 albertel 8536: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8537: return "$num1,$num2";
8538: }
8539: }
8540:
8541: sub rndseed_64bit3 {
8542: my ($symb,$courseid,$domain,$username)=@_;
8543: {
8544: use integer;
8545: # strings need to be an even # of cahracters long, it it is odd the
8546: # last characters gets thrown away
8547: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8548: my $symbseed=numval2($symb) << 10;
8549: my $namechck=unpack("%32S*",$username.' ');
8550:
8551: my $nameseed=numval2($username) << 21;
1.443 albertel 8552: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8553: my $courseseed=unpack("%32S*",$courseid.' ');
8554:
8555: my $num1=$symbchck+$symbseed+$namechck;
8556: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8557: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8558: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8559: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8560:
1.503 albertel 8561: return "$num1:$num2";
1.443 albertel 8562: }
8563: }
8564:
1.575 albertel 8565: sub rndseed_64bit4 {
8566: my ($symb,$courseid,$domain,$username)=@_;
8567: {
8568: use integer;
8569: # strings need to be an even # of cahracters long, it it is odd the
8570: # last characters gets thrown away
8571: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8572: my $symbseed=numval3($symb) << 10;
8573: my $namechck=unpack("%32S*",$username.' ');
8574:
8575: my $nameseed=numval3($username) << 21;
8576: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8577: my $courseseed=unpack("%32S*",$courseid.' ');
8578:
8579: my $num1=$symbchck+$symbseed+$namechck;
8580: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8581: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8582: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 8583: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8584:
8585: return "$num1:$num2";
8586: }
8587: }
8588:
1.675 albertel 8589: sub rndseed_64bit5 {
8590: my ($symb,$courseid,$domain,$username)=@_;
8591: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8592: return "$num1:$num2";
8593: }
8594:
1.366 albertel 8595: sub rndseed_CODE_64bit {
8596: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 8597: {
1.366 albertel 8598: use integer;
1.443 albertel 8599: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 8600: my $symbseed=numval2($symb);
1.491 albertel 8601: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8602: my $CODEseed=numval(&getCODE());
1.443 albertel 8603: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 8604: my $num1=$symbseed+$CODEchck;
8605: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8606: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8607: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 8608: if ($_64bit) { $num1=(($num1<<32)>>32); }
8609: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 8610: return "$num1:$num2";
1.366 albertel 8611: }
8612: }
8613:
1.575 albertel 8614: sub rndseed_CODE_64bit4 {
8615: my ($symb,$courseid,$domain,$username)=@_;
8616: {
8617: use integer;
8618: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8619: my $symbseed=numval3($symb);
8620: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8621: my $CODEseed=numval3(&getCODE());
8622: my $courseseed=unpack("%32S*",$courseid.' ');
8623: my $num1=$symbseed+$CODEchck;
8624: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8625: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8626: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 8627: if ($_64bit) { $num1=(($num1<<32)>>32); }
8628: if ($_64bit) { $num2=(($num2<<32)>>32); }
8629: return "$num1:$num2";
8630: }
8631: }
8632:
1.675 albertel 8633: sub rndseed_CODE_64bit5 {
8634: my ($symb,$courseid,$domain,$username)=@_;
8635: my $code = &getCODE();
8636: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8637: return "$num1:$num2";
8638: }
8639:
1.366 albertel 8640: sub setup_random_from_rndseed {
8641: my ($rndseed)=@_;
1.503 albertel 8642: if ($rndseed =~/([,:])/) {
8643: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 8644: &Math::Random::random_set_seed(abs($num1),abs($num2));
8645: } else {
8646: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 8647: }
1.36 albertel 8648: }
8649:
1.474 albertel 8650: sub latest_receipt_algorithm_id {
1.835 albertel 8651: return 'receipt3';
1.474 albertel 8652: }
8653:
1.480 www 8654: sub recunique {
8655: my $fucourseid=shift;
8656: my $unique;
1.835 albertel 8657: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8658: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8659: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 8660: } else {
8661: $unique=$perlvar{'lonReceipt'};
8662: }
8663: return unpack("%32C*",$unique);
8664: }
8665:
8666: sub recprefix {
8667: my $fucourseid=shift;
8668: my $prefix;
1.835 albertel 8669: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8670: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8671: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 8672: } else {
8673: $prefix=$perlvar{'lonHostID'};
8674: }
8675: return unpack("%32C*",$prefix);
8676: }
8677:
1.76 www 8678: sub ireceipt {
1.474 albertel 8679: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 8680:
8681: my $return =&recprefix($fucourseid).'-';
8682:
8683: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8684: $env{'request.state'} eq 'construct') {
8685: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8686: return $return;
8687: }
8688:
1.76 www 8689: my $cuname=unpack("%32C*",$funame);
8690: my $cudom=unpack("%32C*",$fudom);
8691: my $cucourseid=unpack("%32C*",$fucourseid);
8692: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 8693: my $cunique=&recunique($fucourseid);
1.474 albertel 8694: my $cpart=unpack("%32S*",$part);
1.835 albertel 8695: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8696:
1.790 albertel 8697: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 8698:
8699: $return.= ($cunique%$cuname+
8700: $cunique%$cudom+
8701: $cusymb%$cuname+
8702: $cusymb%$cudom+
8703: $cucourseid%$cuname+
8704: $cucourseid%$cudom+
8705: $cpart%$cuname+
8706: $cpart%$cudom);
8707: } else {
8708: $return.= ($cunique%$cuname+
8709: $cunique%$cudom+
8710: $cusymb%$cuname+
8711: $cusymb%$cudom+
8712: $cucourseid%$cuname+
8713: $cucourseid%$cudom);
8714: }
8715: return $return;
1.76 www 8716: }
8717:
8718: sub receipt {
1.474 albertel 8719: my ($part)=@_;
1.790 albertel 8720: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 8721: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 8722: }
1.260 ng 8723:
1.790 albertel 8724: sub whichuser {
8725: my ($passedsymb)=@_;
8726: my ($symb,$courseid,$domain,$name,$publicuser);
8727: if (defined($env{'form.grade_symb'})) {
8728: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8729: my $allowed=&allowed('vgr',$tmp_courseid);
8730: if (!$allowed &&
8731: exists($env{'request.course.sec'}) &&
8732: $env{'request.course.sec'} !~ /^\s*$/) {
8733: $allowed=&allowed('vgr',$tmp_courseid.
8734: '/'.$env{'request.course.sec'});
8735: }
8736: if ($allowed) {
8737: ($symb)=&get_env_multiple('form.grade_symb');
8738: $courseid=$tmp_courseid;
8739: ($domain)=&get_env_multiple('form.grade_domain');
8740: ($name)=&get_env_multiple('form.grade_username');
8741: return ($symb,$courseid,$domain,$name,$publicuser);
8742: }
8743: }
8744: if (!$passedsymb) {
8745: $symb=&symbread();
8746: } else {
8747: $symb=$passedsymb;
8748: }
8749: $courseid=$env{'request.course.id'};
8750: $domain=$env{'user.domain'};
8751: $name=$env{'user.name'};
8752: if ($name eq 'public' && $domain eq 'public') {
8753: if (!defined($env{'form.username'})) {
8754: $env{'form.username'}.=time.rand(10000000);
8755: }
8756: $name.=$env{'form.username'};
8757: }
8758: return ($symb,$courseid,$domain,$name,$publicuser);
8759:
8760: }
8761:
1.36 albertel 8762: # ------------------------------------------------------------ Serves up a file
1.472 albertel 8763: # returns either the contents of the file or
8764: # -1 if the file doesn't exist
1.481 raeburn 8765: #
8766: # if the target is a file that was uploaded via DOCS,
8767: # a check will be made to see if a current copy exists on the local server,
8768: # if it does this will be served, otherwise a copy will be retrieved from
8769: # the home server for the course and stored in /home/httpd/html/userfiles on
8770: # the local server.
1.472 albertel 8771:
1.36 albertel 8772: sub getfile {
1.538 albertel 8773: my ($file) = @_;
1.609 banghart 8774: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 8775: &repcopy($file);
8776: return &readfile($file);
8777: }
8778:
8779: sub repcopy_userfile {
8780: my ($file)=@_;
1.609 banghart 8781: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 8782: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 8783: my ($cdom,$cnum,$filename) =
1.811 albertel 8784: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 8785: my $uri="/uploaded/$cdom/$cnum/$filename";
8786: if (-e "$file") {
1.828 www 8787: # we already have a local copy, check it out
1.538 albertel 8788: my @fileinfo = stat($file);
1.828 www 8789: my $rtncode;
8790: my $info;
1.538 albertel 8791: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 8792: if ($lwpresp ne 'ok') {
1.828 www 8793: # there is no such file anymore, even though we had a local copy
1.482 albertel 8794: if ($rtncode eq '404') {
1.538 albertel 8795: unlink($file);
1.482 albertel 8796: }
8797: return -1;
8798: }
8799: if ($info < $fileinfo[9]) {
1.828 www 8800: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 8801: return 'ok';
1.828 www 8802: } else {
8803: # the file is outdated, get rid of it
8804: unlink($file);
1.482 albertel 8805: }
1.828 www 8806: }
8807: # one way or the other, at this point, we don't have the file
8808: # construct the correct path for the file
8809: my @parts = ($cdom,$cnum);
8810: if ($filename =~ m|^(.+)/[^/]+$|) {
8811: push @parts, split(/\//,$1);
8812: }
8813: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8814: foreach my $part (@parts) {
8815: $path .= '/'.$part;
8816: if (!-e $path) {
8817: mkdir($path,0770);
1.482 albertel 8818: }
8819: }
1.828 www 8820: # now the path exists for sure
8821: # get a user agent
8822: my $ua=new LWP::UserAgent;
8823: my $transferfile=$file.'.in.transfer';
8824: # FIXME: this should flock
8825: if (-e $transferfile) { return 'ok'; }
8826: my $request;
8827: $uri=~s/^\///;
1.980 raeburn 8828: my $homeserver = &homeserver($cnum,$cdom);
8829: my $protocol = $protocol{$homeserver};
8830: $protocol = 'http' if ($protocol ne 'https');
8831: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 8832: my $response=$ua->request($request,$transferfile);
8833: # did it work?
8834: if ($response->is_error()) {
8835: unlink($transferfile);
8836: &logthis("Userfile repcopy failed for $uri");
8837: return -1;
8838: }
8839: # worked, rename the transfer file
8840: rename($transferfile,$file);
1.607 raeburn 8841: return 'ok';
1.481 raeburn 8842: }
8843:
1.517 albertel 8844: sub tokenwrapper {
8845: my $uri=shift;
1.980 raeburn 8846: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 8847: $uri=~s|^/||;
1.620 albertel 8848: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 8849: my $token=$1;
1.552 albertel 8850: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8851: if ($udom && $uname && $file) {
8852: $file=~s|(\?\.*)*$||;
1.949 raeburn 8853: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 8854: my $homeserver = &homeserver($uname,$udom);
8855: my $protocol = $protocol{$homeserver};
8856: $protocol = 'http' if ($protocol ne 'https');
8857: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 8858: (($uri=~/\?/)?'&':'?').'token='.$token.
8859: '&tokenissued='.$perlvar{'lonHostID'};
8860: } else {
8861: return '/adm/notfound.html';
8862: }
8863: }
8864:
1.828 www 8865: # call with reqtype HEAD: get last modification time
8866: # call with reqtype GET: get the file contents
8867: # Do not call this with reqtype GET for large files! It loads everything into memory
8868: #
1.481 raeburn 8869: sub getuploaded {
8870: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8871: $uri=~s/^\///;
1.980 raeburn 8872: my $homeserver = &homeserver($cnum,$cdom);
8873: my $protocol = $protocol{$homeserver};
8874: $protocol = 'http' if ($protocol ne 'https');
8875: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 8876: my $ua=new LWP::UserAgent;
8877: my $request=new HTTP::Request($reqtype,$uri);
8878: my $response=$ua->request($request);
8879: $$rtncode = $response->code;
1.482 albertel 8880: if (! $response->is_success()) {
8881: return 'failed';
8882: }
8883: if ($reqtype eq 'HEAD') {
1.486 www 8884: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 8885: } elsif ($reqtype eq 'GET') {
8886: $$info = $response->content;
1.472 albertel 8887: }
1.482 albertel 8888: return 'ok';
1.36 albertel 8889: }
8890:
1.481 raeburn 8891: sub readfile {
8892: my $file = shift;
8893: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8894: my $fh;
8895: open($fh,"<$file");
8896: my $a='';
1.800 albertel 8897: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 8898: return $a;
8899: }
8900:
1.36 albertel 8901: sub filelocation {
1.590 banghart 8902: my ($dir,$file) = @_;
8903: my $location;
8904: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 8905:
8906: if ($file =~ m-^/adm/-) {
8907: $file=~s-^/adm/wrapper/-/-;
8908: $file=~s-^/adm/coursedocs/showdoc/-/-;
8909: }
1.882 albertel 8910:
1.590 banghart 8911: if ($file=~m:^/~:) { # is a contruction space reference
8912: $location = $file;
8913: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 8914: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 8915: # is a correct contruction space reference
8916: $location = $file;
1.956 raeburn 8917: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8918: $location = $file;
1.609 banghart 8919: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 8920: my ($udom,$uname,$filename)=
1.811 albertel 8921: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 8922: my $home=&homeserver($uname,$udom);
8923: my $is_me=0;
8924: my @ids=¤t_machine_ids();
8925: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8926: if ($is_me) {
1.955 raeburn 8927: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 8928: } else {
8929: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8930: $udom.'/'.$uname.'/'.$filename;
8931: }
1.882 albertel 8932: } elsif ($file =~ m-^/adm/-) {
8933: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 8934: } else {
8935: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8936: $file=~s:^/res/:/:;
8937: if ( !( $file =~ m:^/:) ) {
8938: $location = $dir. '/'.$file;
8939: } else {
8940: $location = '/home/httpd/html/res'.$file;
8941: }
1.59 albertel 8942: }
1.590 banghart 8943: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 8944: while ($location=~m{/\.\./}) {
8945: if ($location =~ m{/[^/]+/\.\./}) {
8946: $location=~ s{/[^/]+/\.\./}{/}g;
8947: } else {
8948: $location=~ s{/\.\./}{/}g;
8949: }
8950: } #remove dir/..
1.590 banghart 8951: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
8952: return $location;
1.46 www 8953: }
1.36 albertel 8954:
1.46 www 8955: sub hreflocation {
8956: my ($dir,$file)=@_;
1.980 raeburn 8957: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 8958: $file=filelocation($dir,$file);
1.700 albertel 8959: } elsif ($file=~m-^/adm/-) {
8960: $file=~s-^/adm/wrapper/-/-;
8961: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 8962: }
8963: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8964: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 8965: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8966: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 8967: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 8968: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 8969: -/uploaded/$1/$2/-x;
1.46 www 8970: }
1.913 albertel 8971: if ($file=~ m{^/userfiles/}) {
8972: $file =~ s{^/userfiles/}{/uploaded/};
8973: }
1.462 albertel 8974: return $file;
1.465 albertel 8975: }
8976:
8977: sub current_machine_domains {
1.853 albertel 8978: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8979: }
8980:
8981: sub machine_domains {
8982: my ($hostname) = @_;
1.465 albertel 8983: my @domains;
1.838 albertel 8984: my %hostname = &all_hostnames();
1.465 albertel 8985: while( my($id, $name) = each(%hostname)) {
1.467 matthew 8986: # &logthis("-$id-$name-$hostname-");
1.465 albertel 8987: if ($hostname eq $name) {
1.844 albertel 8988: push(@domains,&host_domain($id));
1.465 albertel 8989: }
8990: }
8991: return @domains;
8992: }
8993:
8994: sub current_machine_ids {
1.853 albertel 8995: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8996: }
8997:
8998: sub machine_ids {
8999: my ($hostname) = @_;
9000: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9001: my @ids;
1.888 albertel 9002: my %name_to_host = &all_names();
1.889 albertel 9003: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9004: return @{ $name_to_host{$hostname} };
9005: }
9006: return;
1.31 www 9007: }
9008:
1.824 raeburn 9009: sub additional_machine_domains {
9010: my @domains;
9011: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9012: while( my $line = <$fh>) {
9013: $line =~ s/\s//g;
9014: push(@domains,$line);
9015: }
9016: return @domains;
9017: }
9018:
9019: sub default_login_domain {
9020: my $domain = $perlvar{'lonDefDomain'};
9021: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9022: foreach my $posdom (¤t_machine_domains(),
9023: &additional_machine_domains()) {
9024: if (lc($posdom) eq lc($testdomain)) {
9025: $domain=$posdom;
9026: last;
9027: }
9028: }
9029: return $domain;
9030: }
9031:
1.31 www 9032: # ------------------------------------------------------------- Declutters URLs
9033:
9034: sub declutter {
9035: my $thisfn=shift;
1.569 albertel 9036: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9037: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9038: $thisfn=~s/^\///;
1.697 albertel 9039: $thisfn=~s|^adm/wrapper/||;
9040: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9041: $thisfn=~s/^res\///;
1.235 www 9042: $thisfn=~s/\?.+$//;
1.268 www 9043: return $thisfn;
9044: }
9045:
9046: # ------------------------------------------------------------- Clutter up URLs
9047:
9048: sub clutter {
9049: my $thisfn='/'.&declutter(shift);
1.887 albertel 9050: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9051: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9052: $thisfn='/res'.$thisfn;
9053: }
1.694 albertel 9054: if ($thisfn !~m|/adm|) {
1.695 albertel 9055: if ($thisfn =~ m|/ext/|) {
1.694 albertel 9056: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9057: } else {
9058: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9059: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9060: if ($embstyle eq 'ssi'
9061: || ($embstyle eq 'hdn')
9062: || ($embstyle eq 'rat')
9063: || ($embstyle eq 'prv')
9064: || ($embstyle eq 'ign')) {
9065: #do nothing with these
9066: } elsif (($embstyle eq 'img')
1.695 albertel 9067: || ($embstyle eq 'emb')
9068: || ($embstyle eq 'wrp')) {
9069: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9070: } elsif ($embstyle eq 'unk'
9071: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9072: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9073: } else {
1.718 www 9074: # &logthis("Got a blank emb style");
1.695 albertel 9075: }
1.694 albertel 9076: }
9077: }
1.31 www 9078: return $thisfn;
1.12 www 9079: }
9080:
1.787 albertel 9081: sub clutter_with_no_wrapper {
9082: my $uri = &clutter(shift);
9083: if ($uri =~ m-^/adm/-) {
9084: $uri =~ s-^/adm/wrapper/-/-;
9085: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9086: }
9087: return $uri;
9088: }
9089:
1.557 albertel 9090: sub freeze_escape {
9091: my ($value)=@_;
9092: if (ref($value)) {
9093: $value=&nfreeze($value);
9094: return '__FROZEN__'.&escape($value);
9095: }
9096: return &escape($value);
9097: }
9098:
1.11 www 9099:
1.557 albertel 9100: sub thaw_unescape {
9101: my ($value)=@_;
9102: if ($value =~ /^__FROZEN__/) {
9103: substr($value,0,10,undef);
9104: $value=&unescape($value);
9105: return &thaw($value);
9106: }
9107: return &unescape($value);
9108: }
9109:
1.436 albertel 9110: sub correct_line_ends {
9111: my ($result)=@_;
9112: $$result =~s/\r\n/\n/mg;
9113: $$result =~s/\r/\n/mg;
1.415 albertel 9114: }
1.1 albertel 9115: # ================================================================ Main Program
9116:
1.184 www 9117: sub goodbye {
1.204 albertel 9118: &logthis("Starting Shut down");
1.443 albertel 9119: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9120: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9121: #converted
1.599 albertel 9122: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9123: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9124: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9125: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9126: #1.1 only
1.870 albertel 9127: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9128: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9129: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9130: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9131: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9132: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9133: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9134: &flushcourselogs();
9135: &logthis("Shutting down");
9136: }
9137:
1.852 albertel 9138: sub get_dns {
1.869 albertel 9139: my ($url,$func,$ignore_cache) = @_;
9140: if (!$ignore_cache) {
9141: my ($content,$cached)=
9142: &Apache::lonnet::is_cached_new('dns',$url);
9143: if ($cached) {
9144: &$func($content);
9145: return;
9146: }
9147: }
9148:
9149: my %alldns;
1.852 albertel 9150: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9151: foreach my $dns (<$config>) {
9152: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9153: my $line = $1;
9154: my ($host,$protocol) = split(/:/,$line);
9155: if ($protocol ne 'https') {
9156: $protocol = 'http';
9157: }
9158: $alldns{$host} = $protocol;
1.869 albertel 9159: }
9160: while (%alldns) {
9161: my ($dns) = keys(%alldns);
1.852 albertel 9162: my $ua=new LWP::UserAgent;
1.979 raeburn 9163: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9164: my $response=$ua->request($request);
1.979 raeburn 9165: delete($alldns{$dns});
1.852 albertel 9166: next if ($response->is_error());
9167: my @content = split("\n",$response->content);
1.869 albertel 9168: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9169: &$func(\@content);
1.869 albertel 9170: return;
1.852 albertel 9171: }
9172: close($config);
1.871 albertel 9173: my $which = (split('/',$url))[3];
9174: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9175: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9176: my @content = <$config>;
9177: &$func(\@content);
9178: return;
1.852 albertel 9179: }
1.327 albertel 9180: # ------------------------------------------------------------ Read domain file
9181: {
1.852 albertel 9182: my $loaded;
1.846 albertel 9183: my %domain;
9184:
1.852 albertel 9185: sub parse_domain_tab {
9186: my ($lines) = @_;
9187: foreach my $line (@$lines) {
9188: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9189:
1.846 albertel 9190: chomp($line);
1.852 albertel 9191: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9192: my %this_domain;
9193: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9194: 'lang_def', 'city', 'longi', 'lati',
9195: 'primary') {
9196: $this_domain{$field} = shift(@elements);
9197: }
9198: $domain{$name} = \%this_domain;
1.852 albertel 9199: }
9200: }
1.864 albertel 9201:
9202: sub reset_domain_info {
9203: undef($loaded);
9204: undef(%domain);
9205: }
9206:
1.852 albertel 9207: sub load_domain_tab {
1.869 albertel 9208: my ($ignore_cache) = @_;
9209: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9210: my $fh;
9211: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9212: my @lines = <$fh>;
9213: &parse_domain_tab(\@lines);
1.448 albertel 9214: }
1.852 albertel 9215: close($fh);
9216: $loaded = 1;
1.327 albertel 9217: }
1.846 albertel 9218:
9219: sub domain {
1.852 albertel 9220: &load_domain_tab() if (!$loaded);
9221:
1.846 albertel 9222: my ($name,$what) = @_;
9223: return if ( !exists($domain{$name}) );
9224:
9225: if (!$what) {
9226: return $domain{$name}{'description'};
9227: }
9228: return $domain{$name}{$what};
9229: }
1.974 raeburn 9230:
9231: sub domain_info {
9232: &load_domain_tab() if (!$loaded);
9233: return %domain;
9234: }
9235:
1.327 albertel 9236: }
9237:
9238:
1.1 albertel 9239: # ------------------------------------------------------------- Read hosts file
9240: {
1.838 albertel 9241: my %hostname;
1.844 albertel 9242: my %hostdom;
1.845 albertel 9243: my %libserv;
1.852 albertel 9244: my $loaded;
1.888 albertel 9245: my %name_to_host;
1.852 albertel 9246:
9247: sub parse_hosts_tab {
9248: my ($file) = @_;
9249: foreach my $configline (@$file) {
9250: next if ($configline =~ /^(\#|\s*$ )/x);
9251: next if ($configline =~ /^\^/);
9252: chomp($configline);
1.968 raeburn 9253: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 9254: $name=~s/\s//g;
9255: if ($id && $domain && $role && $name) {
9256: $hostname{$id}=$name;
1.888 albertel 9257: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9258: $hostdom{$id}=$domain;
9259: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9260: if (defined($protocol)) {
9261: if ($protocol eq 'https') {
9262: $protocol{$id} = $protocol;
9263: } else {
9264: $protocol{$id} = 'http';
9265: }
1.968 raeburn 9266: } else {
1.969 raeburn 9267: $protocol{$id} = 'http';
1.968 raeburn 9268: }
1.852 albertel 9269: }
9270: }
9271: }
1.864 albertel 9272:
9273: sub reset_hosts_info {
1.897 albertel 9274: &purge_remembered();
1.864 albertel 9275: &reset_domain_info();
9276: &reset_hosts_ip_info();
1.892 albertel 9277: undef(%name_to_host);
1.864 albertel 9278: undef(%hostname);
9279: undef(%hostdom);
9280: undef(%libserv);
9281: undef($loaded);
9282: }
1.1 albertel 9283:
1.852 albertel 9284: sub load_hosts_tab {
1.869 albertel 9285: my ($ignore_cache) = @_;
9286: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9287: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9288: my @config = <$config>;
9289: &parse_hosts_tab(\@config);
9290: close($config);
9291: $loaded=1;
1.1 albertel 9292: }
1.852 albertel 9293:
1.838 albertel 9294: sub hostname {
1.852 albertel 9295: &load_hosts_tab() if (!$loaded);
9296:
1.838 albertel 9297: my ($lonid) = @_;
9298: return $hostname{$lonid};
9299: }
1.845 albertel 9300:
1.838 albertel 9301: sub all_hostnames {
1.852 albertel 9302: &load_hosts_tab() if (!$loaded);
9303:
1.838 albertel 9304: return %hostname;
9305: }
1.845 albertel 9306:
1.888 albertel 9307: sub all_names {
9308: &load_hosts_tab() if (!$loaded);
9309:
9310: return %name_to_host;
9311: }
9312:
1.974 raeburn 9313: sub all_host_domain {
9314: &load_hosts_tab() if (!$loaded);
9315: return %hostdom;
9316: }
9317:
1.845 albertel 9318: sub is_library {
1.852 albertel 9319: &load_hosts_tab() if (!$loaded);
9320:
1.845 albertel 9321: return exists($libserv{$_[0]});
9322: }
9323:
9324: sub all_library {
1.852 albertel 9325: &load_hosts_tab() if (!$loaded);
9326:
1.845 albertel 9327: return %libserv;
9328: }
9329:
1.841 albertel 9330: sub get_servers {
1.852 albertel 9331: &load_hosts_tab() if (!$loaded);
9332:
1.841 albertel 9333: my ($domain,$type) = @_;
9334: my %possible_hosts = ($type eq 'library') ? %libserv
9335: : %hostname;
9336: my %result;
1.842 albertel 9337: if (ref($domain) eq 'ARRAY') {
9338: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9339: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9340: $result{$host} = $hostname;
9341: }
9342: }
9343: } else {
9344: while ( my ($host,$hostname) = each(%possible_hosts)) {
9345: if ($hostdom{$host} eq $domain) {
9346: $result{$host} = $hostname;
9347: }
1.841 albertel 9348: }
9349: }
9350: return %result;
9351: }
1.845 albertel 9352:
1.844 albertel 9353: sub host_domain {
1.852 albertel 9354: &load_hosts_tab() if (!$loaded);
9355:
1.844 albertel 9356: my ($lonid) = @_;
9357: return $hostdom{$lonid};
9358: }
9359:
1.841 albertel 9360: sub all_domains {
1.852 albertel 9361: &load_hosts_tab() if (!$loaded);
9362:
1.841 albertel 9363: my %seen;
9364: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9365: return @uniq;
9366: }
1.1 albertel 9367: }
9368:
1.847 albertel 9369: {
9370: my %iphost;
1.856 albertel 9371: my %name_to_ip;
9372: my %lonid_to_ip;
1.869 albertel 9373:
1.847 albertel 9374: sub get_hosts_from_ip {
9375: my ($ip) = @_;
9376: my %iphosts = &get_iphost();
9377: if (ref($iphosts{$ip})) {
9378: return @{$iphosts{$ip}};
9379: }
9380: return;
1.839 albertel 9381: }
1.864 albertel 9382:
9383: sub reset_hosts_ip_info {
9384: undef(%iphost);
9385: undef(%name_to_ip);
9386: undef(%lonid_to_ip);
9387: }
1.856 albertel 9388:
9389: sub get_host_ip {
9390: my ($lonid) = @_;
9391: if (exists($lonid_to_ip{$lonid})) {
9392: return $lonid_to_ip{$lonid};
9393: }
9394: my $name=&hostname($lonid);
9395: my $ip = gethostbyname($name);
9396: return if (!$ip || length($ip) ne 4);
9397: $ip=inet_ntoa($ip);
9398: $name_to_ip{$name} = $ip;
9399: $lonid_to_ip{$lonid} = $ip;
9400: return $ip;
9401: }
1.847 albertel 9402:
9403: sub get_iphost {
1.869 albertel 9404: my ($ignore_cache) = @_;
1.894 albertel 9405:
1.869 albertel 9406: if (!$ignore_cache) {
9407: if (%iphost) {
9408: return %iphost;
9409: }
9410: my ($ip_info,$cached)=
9411: &Apache::lonnet::is_cached_new('iphost','iphost');
9412: if ($cached) {
9413: %iphost = %{$ip_info->[0]};
9414: %name_to_ip = %{$ip_info->[1]};
9415: %lonid_to_ip = %{$ip_info->[2]};
9416: return %iphost;
9417: }
9418: }
1.894 albertel 9419:
9420: # get yesterday's info for fallback
9421: my %old_name_to_ip;
9422: my ($ip_info,$cached)=
9423: &Apache::lonnet::is_cached_new('iphost','iphost');
9424: if ($cached) {
9425: %old_name_to_ip = %{$ip_info->[1]};
9426: }
9427:
1.888 albertel 9428: my %name_to_host = &all_names();
9429: foreach my $name (keys(%name_to_host)) {
1.847 albertel 9430: my $ip;
9431: if (!exists($name_to_ip{$name})) {
9432: $ip = gethostbyname($name);
9433: if (!$ip || length($ip) ne 4) {
1.894 albertel 9434: if (defined($old_name_to_ip{$name})) {
9435: $ip = $old_name_to_ip{$name};
9436: &logthis("Can't find $name defaulting to old $ip");
9437: } else {
9438: &logthis("Name $name no IP found");
9439: next;
9440: }
9441: } else {
9442: $ip=inet_ntoa($ip);
1.847 albertel 9443: }
9444: $name_to_ip{$name} = $ip;
9445: } else {
9446: $ip = $name_to_ip{$name};
1.653 albertel 9447: }
1.888 albertel 9448: foreach my $id (@{ $name_to_host{$name} }) {
9449: $lonid_to_ip{$id} = $ip;
9450: }
9451: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9452: }
1.869 albertel 9453: &Apache::lonnet::do_cache_new('iphost','iphost',
9454: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9455: 48*60*60);
1.869 albertel 9456:
1.847 albertel 9457: return %iphost;
1.598 albertel 9458: }
9459:
1.992 raeburn 9460: #
9461: # Given a DNS returns the loncapa host name for that DNS
9462: #
9463: sub host_from_dns {
9464: my ($dns) = @_;
9465: my @hosts;
9466: my $ip;
9467:
1.993 raeburn 9468: if (exists($name_to_ip{$dns})) {
1.992 raeburn 9469: $ip = $name_to_ip{$dns};
9470: }
9471: if (!$ip) {
9472: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9473: if (length($ip) == 4) {
9474: $ip = &IO::Socket::inet_ntoa($ip);
9475: }
9476: }
9477: if ($ip) {
9478: @hosts = get_hosts_from_ip($ip);
9479: return $hosts[0];
9480: }
9481: return undef;
1.986 foxr 9482: }
1.992 raeburn 9483:
1.986 foxr 9484: }
9485:
1.862 albertel 9486: BEGIN {
9487:
9488: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9489: unless ($readit) {
9490: {
9491: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9492: %perlvar = (%perlvar,%{$configvars});
9493: }
9494:
9495:
1.1 albertel 9496: # ------------------------------------------------------ Read spare server file
9497: {
1.448 albertel 9498: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9499:
9500: while (my $configline=<$config>) {
9501: chomp($configline);
1.284 matthew 9502: if ($configline) {
1.784 albertel 9503: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9504: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9505: push(@{ $spareid{$type} }, $host);
1.1 albertel 9506: }
9507: }
1.448 albertel 9508: close($config);
1.1 albertel 9509: }
1.11 www 9510: # ------------------------------------------------------------ Read permissions
9511: {
1.448 albertel 9512: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9513:
9514: while (my $configline=<$config>) {
1.448 albertel 9515: chomp($configline);
9516: if ($configline) {
9517: my ($role,$perm)=split(/ /,$configline);
9518: if ($perm ne '') { $pr{$role}=$perm; }
9519: }
1.11 www 9520: }
1.448 albertel 9521: close($config);
1.11 www 9522: }
9523:
9524: # -------------------------------------------- Read plain texts for permissions
9525: {
1.448 albertel 9526: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9527:
9528: while (my $configline=<$config>) {
1.448 albertel 9529: chomp($configline);
9530: if ($configline) {
1.742 raeburn 9531: my ($short,@plain)=split(/:/,$configline);
9532: %{$prp{$short}} = ();
9533: if (@plain > 0) {
9534: $prp{$short}{'std'} = $plain[0];
9535: for (my $i=1; $i<@plain; $i++) {
9536: $prp{$short}{'alt'.$i} = $plain[$i];
9537: }
9538: }
1.448 albertel 9539: }
1.135 www 9540: }
1.448 albertel 9541: close($config);
1.135 www 9542: }
9543:
9544: # ---------------------------------------------------------- Read package table
9545: {
1.448 albertel 9546: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9547:
9548: while (my $configline=<$config>) {
1.483 albertel 9549: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9550: chomp($configline);
9551: my ($short,$plain)=split(/:/,$configline);
9552: my ($pack,$name)=split(/\&/,$short);
9553: if ($plain ne '') {
9554: $packagetab{$pack.'&'.$name.'&name'}=$name;
9555: $packagetab{$short}=$plain;
9556: }
1.11 www 9557: }
1.448 albertel 9558: close($config);
1.329 matthew 9559: }
9560:
9561: # ------------- set up temporary directory
9562: {
9563: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9564:
1.11 www 9565: }
9566:
1.794 albertel 9567: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9568: 'compress_threshold'=> 20_000,
9569: });
1.185 www 9570:
1.281 www 9571: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 9572: $dumpcount=0;
1.958 www 9573: $locknum=0;
1.22 www 9574:
1.163 harris41 9575: &logtouch();
1.672 albertel 9576: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 9577: $readit=1;
1.564 albertel 9578: {
9579: use integer;
9580: my $test=(2**32)+1;
1.568 albertel 9581: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 9582: &logthis(" Detected 64bit platform ($_64bit)");
9583: }
1.195 www 9584: }
1.1 albertel 9585: }
1.179 www 9586:
1.1 albertel 9587: 1;
1.191 harris41 9588: __END__
9589:
1.243 albertel 9590: =pod
9591:
1.191 harris41 9592: =head1 NAME
9593:
1.243 albertel 9594: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 9595:
9596: =head1 SYNOPSIS
9597:
1.243 albertel 9598: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 9599:
9600: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9601:
1.243 albertel 9602: Common parameters:
9603:
9604: =over 4
9605:
9606: =item *
9607:
9608: $uname : an internal username (if $cname expecting a course Id specifically)
9609:
9610: =item *
9611:
9612: $udom : a domain (if $cdom expecting a course's domain specifically)
9613:
9614: =item *
9615:
9616: $symb : a resource instance identifier
9617:
9618: =item *
9619:
9620: $namespace : the name of a .db file that contains the data needed or
9621: being set.
9622:
9623: =back
9624:
1.394 bowersj2 9625: =head1 OVERVIEW
1.191 harris41 9626:
1.394 bowersj2 9627: lonnet provides subroutines which interact with the
9628: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9629: about classes, users, and resources.
1.243 albertel 9630:
9631: For many of these objects you can also use this to store data about
9632: them or modify them in various ways.
1.191 harris41 9633:
1.394 bowersj2 9634: =head2 Symbs
1.191 harris41 9635:
1.394 bowersj2 9636: To identify a specific instance of a resource, LON-CAPA uses symbols
9637: or "symbs"X<symb>. These identifiers are built from the URL of the
9638: map, the resource number of the resource in the map, and the URL of
9639: the resource itself. The latter is somewhat redundant, but might help
9640: if maps change.
9641:
9642: An example is
9643:
9644: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9645:
9646: The respective map entry is
9647:
9648: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9649: title="Problem 2">
9650: </resource>
9651:
9652: Symbs are used by the random number generator, as well as to store and
9653: restore data specific to a certain instance of for example a problem.
9654:
9655: =head2 Storing And Retrieving Data
9656:
9657: X<store()>X<cstore()>X<restore()>Three of the most important functions
9658: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9659: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9660: is is the non-critical message twin of cstore. These functions are for
9661: handlers to store a perl hash to a user's permanent data space in an
9662: easy manner, and to retrieve it again on another call. It is expected
9663: that a handler would use this once at the beginning to retrieve data,
9664: and then again once at the end to send only the new data back.
9665:
9666: The data is stored in the user's data directory on the user's
9667: homeserver under the ID of the course.
9668:
9669: The hash that is returned by restore will have all of the previous
9670: value for all of the elements of the hash.
9671:
9672: Example:
9673:
9674: #creating a hash
9675: my %hash;
9676: $hash{'foo'}='bar';
9677:
9678: #storing it
9679: &Apache::lonnet::cstore(\%hash);
9680:
9681: #changing a value
9682: $hash{'foo'}='notbar';
9683:
9684: #adding a new value
9685: $hash{'bar'}='foo';
9686: &Apache::lonnet::cstore(\%hash);
9687:
9688: #retrieving the hash
9689: my %history=&Apache::lonnet::restore();
9690:
9691: #print the hash
9692: foreach my $key (sort(keys(%history))) {
9693: print("\%history{$key} = $history{$key}");
9694: }
9695:
9696: Will print out:
1.191 harris41 9697:
1.394 bowersj2 9698: %history{1:foo} = bar
9699: %history{1:keys} = foo:timestamp
9700: %history{1:timestamp} = 990455579
9701: %history{2:bar} = foo
9702: %history{2:foo} = notbar
9703: %history{2:keys} = foo:bar:timestamp
9704: %history{2:timestamp} = 990455580
9705: %history{bar} = foo
9706: %history{foo} = notbar
9707: %history{timestamp} = 990455580
9708: %history{version} = 2
9709:
9710: Note that the special hash entries C<keys>, C<version> and
9711: C<timestamp> were added to the hash. C<version> will be equal to the
9712: total number of versions of the data that have been stored. The
9713: C<timestamp> attribute will be the UNIX time the hash was
9714: stored. C<keys> is available in every historical section to list which
9715: keys were added or changed at a specific historical revision of a
9716: hash.
9717:
9718: B<Warning>: do not store the hash that restore returns directly. This
9719: will cause a mess since it will restore the historical keys as if the
9720: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 9721:
1.394 bowersj2 9722: Calling convention:
1.191 harris41 9723:
1.394 bowersj2 9724: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9725: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 9726:
1.394 bowersj2 9727: For more detailed information, see lonnet specific documentation.
1.191 harris41 9728:
1.394 bowersj2 9729: =head1 RETURN MESSAGES
1.191 harris41 9730:
1.394 bowersj2 9731: =over 4
1.191 harris41 9732:
1.394 bowersj2 9733: =item * B<con_lost>: unable to contact remote host
1.191 harris41 9734:
1.394 bowersj2 9735: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9736: when the connection is brought back up
1.191 harris41 9737:
1.394 bowersj2 9738: =item * B<con_failed>: unable to contact remote host and unable to save message
9739: for later delivery
1.191 harris41 9740:
1.967 bisitz 9741: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 9742:
1.394 bowersj2 9743: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 9744: that was requested
1.191 harris41 9745:
1.243 albertel 9746: =back
1.191 harris41 9747:
1.243 albertel 9748: =head1 PUBLIC SUBROUTINES
1.191 harris41 9749:
1.243 albertel 9750: =head2 Session Environment Functions
1.191 harris41 9751:
1.243 albertel 9752: =over 4
1.191 harris41 9753:
1.394 bowersj2 9754: =item *
9755: X<appenv()>
1.949 raeburn 9756: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 9757: the user envirnoment file, and will be restored for each access this
1.620 albertel 9758: user makes during this session, also modifies the %env for the current
1.949 raeburn 9759: process. Optional rolesarrayref - if defined contains a reference to an array
9760: of roles which are exempt from the restriction on modifying user.role entries
9761: in the user's environment.db and in %env.
1.191 harris41 9762:
9763: =item *
1.394 bowersj2 9764: X<delenv()>
1.987 raeburn 9765: B<delenv($delthis,$regexp)>: removes all items from the session
9766: environment file that begin with $delthis. If the
9767: optional second arg - $regexp - is true, $delthis is treated as a
9768: regular expression, otherwise \Q$delthis\E is used.
9769: The values are also deleted from the current processes %env.
1.191 harris41 9770:
1.795 albertel 9771: =item * get_env_multiple($name)
9772:
9773: gets $name from the %env hash, it seemlessly handles the cases where multiple
9774: values may be defined and end up as an array ref.
9775:
9776: returns an array of values
9777:
1.243 albertel 9778: =back
9779:
9780: =head2 User Information
1.191 harris41 9781:
1.243 albertel 9782: =over 4
1.191 harris41 9783:
9784: =item *
1.394 bowersj2 9785: X<queryauthenticate()>
9786: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 9787: authentication scheme
9788:
9789: =item *
1.394 bowersj2 9790: X<authenticate()>
9791: B<authenticate($uname,$upass,$udom)>: try to
9792: authenticate user from domain's lib servers (first use the current
9793: one). C<$upass> should be the users password.
1.191 harris41 9794:
9795: =item *
1.394 bowersj2 9796: X<homeserver()>
9797: B<homeserver($uname,$udom)>: find the server which has
9798: the user's directory and files (there must be only one), this caches
9799: the answer, and also caches if there is a borken connection.
1.191 harris41 9800:
9801: =item *
1.394 bowersj2 9802: X<idget()>
9803: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9804: (IDs are a unique resource in a domain, there must be only 1 ID per
9805: username, and only 1 username per ID in a specific domain) (returns
9806: hash: id=>name,id=>name)
1.191 harris41 9807:
9808: =item *
1.394 bowersj2 9809: X<idrget()>
9810: B<idrget($udom,@unames)>: find the IDs behind a list of
9811: usernames (returns hash: name=>id,name=>id)
1.191 harris41 9812:
9813: =item *
1.394 bowersj2 9814: X<idput()>
9815: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 9816:
9817: =item *
1.394 bowersj2 9818: X<rolesinit()>
9819: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 9820:
9821: =item *
1.551 albertel 9822: X<getsection()>
9823: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 9824: course $cname, return section name/number or '' for "not in course"
9825: and '-1' for "no section"
9826:
9827: =item *
1.394 bowersj2 9828: X<userenvironment()>
9829: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 9830: passed in @what from the requested user's environment, returns a hash
9831:
1.858 raeburn 9832: =item *
9833: X<userlog_query()>
1.859 albertel 9834: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9835: activity.log file. %filters defines filters applied when parsing the
9836: log file. These can be start or end timestamps, or the type of action
9837: - log to look for Login or Logout events, check for Checkin or
9838: Checkout, role for role selection. The response is in the form
9839: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9840: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 9841:
1.243 albertel 9842: =back
9843:
9844: =head2 User Roles
9845:
9846: =over 4
9847:
9848: =item *
9849:
1.810 raeburn 9850: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 9851: F: full access
9852: U,I,K: authentication modes (cxx only)
9853: '': forbidden
9854: 1: user needs to choose course
9855: 2: browse allowed
1.766 albertel 9856: A: passphrase authentication needed
1.243 albertel 9857:
9858: =item *
9859:
9860: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9861: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9862: and course level
9863:
9864: =item *
9865:
1.988 raeburn 9866: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
9867: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 9868: $type is Course (default) or Community.
1.988 raeburn 9869: If $forcedefault evaluates to true, text returned will be default
9870: text for $type. Otherwise, if this is a course, the text returned
9871: will be a custom name for the role (if defined in the course's
9872: environment). If no custom name is defined the default is returned.
9873:
1.832 raeburn 9874: =item *
9875:
1.935 raeburn 9876: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 9877: All arguments are optional. Returns a hash of a roles, either for
9878: co-author/assistant author roles for a user's Construction Space
1.906 albertel 9879: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 9880: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9881: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9882: For each key, value is set to colon-separated start and end times for
9883: the role. If no username and domain are specified, will default to
1.934 raeburn 9884: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 9885: of role statuses (active, future or previous), roles
9886: (e.g., cc,in, st etc.) and domains of the roles which can be used
9887: to restrict the list of roles reported. If no array ref is
9888: provided for types, will default to return only active roles.
1.834 albertel 9889:
1.243 albertel 9890: =back
9891:
9892: =head2 User Modification
9893:
9894: =over 4
9895:
9896: =item *
9897:
1.957 raeburn 9898: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 9899: user for the level given by URL. Optional start and end dates (leave empty
9900: string or zero for "no date")
1.191 harris41 9901:
9902: =item *
9903:
1.243 albertel 9904: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9905: change a users, password, possible return values are: ok,
9906: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9907: refused
1.191 harris41 9908:
9909: =item *
9910:
1.243 albertel 9911: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 9912:
9913: =item *
9914:
1.963 raeburn 9915: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9916: $forceid,$desiredhome,$email,$inststatus) :
1.243 albertel 9917: modify user
1.191 harris41 9918:
9919: =item *
9920:
1.286 matthew 9921: modifystudent
9922:
1.957 raeburn 9923: modify a student's enrollment and identification information.
1.286 matthew 9924: The course id is resolved based on the current users environment.
9925: This means the envoking user must be a course coordinator or otherwise
9926: associated with a course.
9927:
1.297 matthew 9928: This call is essentially a wrapper for lonnet::modifyuser and
9929: lonnet::modify_student_enrollment
1.286 matthew 9930:
9931: Inputs:
9932:
9933: =over 4
9934:
1.957 raeburn 9935: =item B<$udom> Student's loncapa domain
1.286 matthew 9936:
1.957 raeburn 9937: =item B<$uname> Student's loncapa login name
1.286 matthew 9938:
1.964 bisitz 9939: =item B<$uid> Student/Employee ID
1.286 matthew 9940:
1.957 raeburn 9941: =item B<$umode> Student's authentication mode
1.286 matthew 9942:
1.957 raeburn 9943: =item B<$upass> Student's password
1.286 matthew 9944:
1.957 raeburn 9945: =item B<$first> Student's first name
1.286 matthew 9946:
1.957 raeburn 9947: =item B<$middle> Student's middle name
1.286 matthew 9948:
1.957 raeburn 9949: =item B<$last> Student's last name
1.286 matthew 9950:
1.957 raeburn 9951: =item B<$gene> Student's generation
1.286 matthew 9952:
1.957 raeburn 9953: =item B<$usec> Student's section in course
1.286 matthew 9954:
9955: =item B<$end> Unix time of the roles expiration
9956:
9957: =item B<$start> Unix time of the roles start date
9958:
9959: =item B<$forceid> If defined, allow $uid to be changed
9960:
9961: =item B<$desiredhome> server to use as home server for student
9962:
1.957 raeburn 9963: =item B<$email> Student's permanent e-mail address
9964:
9965: =item B<$type> Type of enrollment (auto or manual)
9966:
1.963 raeburn 9967: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
9968:
9969: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 9970:
1.963 raeburn 9971: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 9972:
1.963 raeburn 9973: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 9974:
1.963 raeburn 9975: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 9976:
1.286 matthew 9977: =back
1.297 matthew 9978:
9979: =item *
9980:
9981: modify_student_enrollment
9982:
9983: Change a students enrollment status in a class. The environment variable
9984: 'role.request.course' must be defined for this function to proceed.
9985:
9986: Inputs:
9987:
9988: =over 4
9989:
9990: =item $udom, students domain
9991:
9992: =item $uname, students name
9993:
9994: =item $uid, students user id
9995:
9996: =item $first, students first name
9997:
9998: =item $middle
9999:
10000: =item $last
10001:
10002: =item $gene
10003:
10004: =item $usec
10005:
10006: =item $end
10007:
10008: =item $start
10009:
1.957 raeburn 10010: =item $type
10011:
10012: =item $locktype
10013:
10014: =item $cid
10015:
10016: =item $selfenroll
10017:
10018: =item $context
10019:
1.297 matthew 10020: =back
10021:
1.191 harris41 10022:
10023: =item *
10024:
1.243 albertel 10025: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10026: custom role; give a custom role to a user for the level given by URL. Specify
10027: name and domain of role author, and role name
1.191 harris41 10028:
10029: =item *
10030:
1.243 albertel 10031: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10032:
10033: =item *
10034:
1.243 albertel 10035: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10036:
10037: =back
10038:
10039: =head2 Course Infomation
10040:
10041: =over 4
1.191 harris41 10042:
10043: =item *
10044:
1.631 albertel 10045: coursedescription($courseid) : returns a hash of information about the
10046: specified course id, including all environment settings for the
10047: course, the description of the course will be in the hash under the
10048: key 'description'
1.191 harris41 10049:
10050: =item *
10051:
1.624 albertel 10052: resdata($name,$domain,$type,@which) : request for current parameter
10053: setting for a specific $type, where $type is either 'course' or 'user',
10054: @what should be a list of parameters to ask about. This routine caches
10055: answers for 5 minutes.
1.243 albertel 10056:
1.877 foxr 10057: =item *
10058:
10059: get_courseresdata($courseid, $domain) : dump the entire course resource
10060: data base, returning a hash that is keyed by the resource name and has
10061: values that are the resource value. I believe that the timestamps and
10062: versions are also returned.
10063:
10064:
1.243 albertel 10065: =back
10066:
10067: =head2 Course Modification
10068:
10069: =over 4
1.191 harris41 10070:
10071: =item *
10072:
1.243 albertel 10073: writecoursepref($courseid,%prefs) : write preferences (environment
10074: database) for a course
1.191 harris41 10075:
10076: =item *
10077:
1.1011 raeburn 10078: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10079:
10080: =item *
10081:
10082: generate_coursenum($udom) : get a unique (unused) course number in domain $udom
1.243 albertel 10083:
10084: =back
10085:
10086: =head2 Resource Subroutines
10087:
10088: =over 4
1.191 harris41 10089:
10090: =item *
10091:
1.243 albertel 10092: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10093:
10094: =item *
10095:
1.243 albertel 10096: repcopy($filename) : subscribes to the requested file, and attempts to
10097: replicate from the owning library server, Might return
1.607 raeburn 10098: 'unavailable', 'not_found', 'forbidden', 'ok', or
10099: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10100: resource. Expects the local filesystem pathname
10101: (/home/httpd/html/res/....)
10102:
10103: =back
10104:
10105: =head2 Resource Information
10106:
10107: =over 4
1.191 harris41 10108:
10109: =item *
10110:
1.243 albertel 10111: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10112: a vairety of different possible values, $varname should be a request
10113: string, and the other parameters can be used to specify who and what
10114: one is asking about.
10115:
10116: Possible values for $varname are environment.lastname (or other item
10117: from the envirnment hash), user.name (or someother aspect about the
10118: user), resource.0.maxtries (or some other part and parameter of a
10119: resource)
1.204 albertel 10120:
10121: =item *
10122:
1.243 albertel 10123: directcondval($number) : get current value of a condition; reads from a state
10124: string
1.204 albertel 10125:
10126: =item *
10127:
1.243 albertel 10128: condval($condidx) : value of condition index based on state
1.204 albertel 10129:
10130: =item *
10131:
1.243 albertel 10132: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10133: resource's metadata, $what should be either a specific key, or either
10134: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10135: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10136:
10137: this function automatically caches all requests
1.191 harris41 10138:
10139: =item *
10140:
1.243 albertel 10141: metadata_query($query,$custom,$customshow) : make a metadata query against the
10142: network of library servers; returns file handle of where SQL and regex results
10143: will be stored for query
1.191 harris41 10144:
10145: =item *
10146:
1.243 albertel 10147: symbread($filename) : return symbolic list entry (filename argument optional);
10148: returns the data handle
1.191 harris41 10149:
10150: =item *
10151:
1.243 albertel 10152: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10153: a possible symb for the URL in $thisfn, and if is an encryypted
10154: resource that the user accessed using /enc/ returns a 1 on success, 0
10155: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10156: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10157:
1.191 harris41 10158:
10159: =item *
10160:
1.243 albertel 10161: symbclean($symb) : removes versions numbers from a symb, returns the
10162: cleaned symb
1.191 harris41 10163:
10164: =item *
10165:
1.243 albertel 10166: is_on_map($uri) : checks if the $uri is somewhere on the current
10167: course map, user must be in a course for it to work.
1.191 harris41 10168:
10169: =item *
10170:
1.243 albertel 10171: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10172:
10173: =item *
10174:
1.243 albertel 10175: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10176: a random seed, all arguments are optional, if they aren't sent it uses the
10177: environment to derive them. Note: if symb isn't sent and it can't get one
10178: from &symbread it will use the current time as its return value
1.191 harris41 10179:
10180: =item *
10181:
1.243 albertel 10182: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10183: unfakeable, receipt
1.191 harris41 10184:
10185: =item *
10186:
1.620 albertel 10187: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10188:
10189: =item *
10190:
1.243 albertel 10191: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10192:
10193: =item *
10194:
1.243 albertel 10195: 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 10196:
10197: =item *
10198:
1.243 albertel 10199: 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 10200:
10201: =item *
10202:
1.243 albertel 10203: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10204:
10205: =item *
10206:
1.243 albertel 10207: devalidate($symb) : devalidate temporary spreadsheet calculations,
10208: forcing spreadsheet to reevaluate the resource scores next time.
10209:
10210: =back
10211:
10212: =head2 Storing/Retreiving Data
10213:
10214: =over 4
1.191 harris41 10215:
10216: =item *
10217:
1.243 albertel 10218: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10219: for this url; hashref needs to be given and should be a \%hashname; the
10220: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10221: be derived from the env
1.191 harris41 10222:
10223: =item *
10224:
1.243 albertel 10225: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10226: uses critical subroutine
1.191 harris41 10227:
10228: =item *
10229:
1.243 albertel 10230: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10231: all args are optional
1.191 harris41 10232:
10233: =item *
10234:
1.717 albertel 10235: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10236: dumps the complete (or key matching regexp) namespace into a hash
10237: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10238: normally &store()ed into
10239:
10240: $range should be either an integer '100' (give me the first 100
10241: matching records)
10242: or be two integers sperated by a - with no spaces
10243: '30-50' (give me the 30th through the 50th matching
10244: records)
10245:
10246:
10247: =item *
10248:
10249: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10250: replaces a &store() version of data with a replacement set of data
10251: for a particular resource in a namespace passed in the $storehash hash
10252: reference
10253:
10254: =item *
10255:
1.243 albertel 10256: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10257: works very similar to store/cstore, but all data is stored in a
10258: temporary location and can be reset using tmpreset, $storehash should
10259: be a hash reference, returns nothing on success
1.191 harris41 10260:
10261: =item *
10262:
1.243 albertel 10263: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10264: similar to restore, but all data is stored in a temporary location and
10265: can be reset using tmpreset. Returns a hash of values on success,
10266: error string otherwise.
1.191 harris41 10267:
10268: =item *
10269:
1.243 albertel 10270: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10271: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 10272:
10273: =item *
10274:
1.243 albertel 10275: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10276: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 10277:
10278: =item *
10279:
1.243 albertel 10280: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10281: namesp ($udom and $uname are optional)
1.191 harris41 10282:
10283: =item *
10284:
1.702 albertel 10285: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 10286: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 10287: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 10288:
1.702 albertel 10289: $range should be either an integer '100' (give me the first 100
10290: matching records)
10291: or be two integers sperated by a - with no spaces
10292: '30-50' (give me the 30th through the 50th matching
10293: records)
1.449 matthew 10294: =item *
10295:
10296: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10297: $store can be a scalar, an array reference, or if the amount to be
10298: incremented is > 1, a hash reference.
10299:
10300: ($udom and $uname are optional)
1.191 harris41 10301:
10302: =item *
10303:
1.243 albertel 10304: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10305: ($udom and $uname are optional)
1.191 harris41 10306:
10307: =item *
10308:
1.243 albertel 10309: cput($namespace,$storehash,$udom,$uname) : critical put
10310: ($udom and $uname are optional)
1.191 harris41 10311:
10312: =item *
10313:
1.748 albertel 10314: newput($namespace,$storehash,$udom,$uname) :
10315:
10316: Attempts to store the items in the $storehash, but only if they don't
10317: currently exist, if this succeeds you can be certain that you have
10318: successfully created a new key value pair in the $namespace db.
10319:
10320:
10321: Args:
10322: $namespace: name of database to store values to
10323: $storehash: hashref to store to the db
10324: $udom: (optional) domain of user containing the db
10325: $uname: (optional) name of user caontaining the db
10326:
10327: Returns:
10328: 'ok' -> succeeded in storing all keys of $storehash
10329: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10330: least <key> already existed in the db (other
10331: requested keys may also already exist)
1.967 bisitz 10332: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 10333: 'con_lost' -> unable to contact request server
10334: 'refused' -> action was not allowed by remote machine
10335:
10336:
10337: =item *
10338:
1.243 albertel 10339: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10340: reference filled in from namesp (encrypts the return communication)
10341: ($udom and $uname are optional)
1.191 harris41 10342:
10343: =item *
10344:
1.243 albertel 10345: log($udom,$name,$home,$message) : write to permanent log for user; use
10346: critical subroutine
10347:
1.806 raeburn 10348: =item *
10349:
1.860 raeburn 10350: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10351: array reference filled in from namespace found in domain level on either
10352: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 10353:
10354: =item *
10355:
1.860 raeburn 10356: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10357: domain level either on specified domain server ($uhome) or primary domain
10358: server ($udom and $uhome are optional)
1.806 raeburn 10359:
1.943 raeburn 10360: =item *
10361:
10362: get_domain_defaults($target_domain) : returns hash with defaults for
10363: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10364: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10365: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10366: Values are retrieved from cache (if current), or from domain's configuration.db
10367: (if available), or lastly from values in lonTabs/dns_domain,tab,
10368: or lonTabs/domain.tab.
10369:
10370: %domdefaults = &get_auth_defaults($target_domain);
10371:
1.243 albertel 10372: =back
10373:
10374: =head2 Network Status Functions
10375:
10376: =over 4
1.191 harris41 10377:
10378: =item *
10379:
10380: dirlist($uri) : return directory list based on URI
10381:
10382: =item *
10383:
1.243 albertel 10384: spareserver() : find server with least workload from spare.tab
10385:
1.986 foxr 10386:
10387: =item *
10388:
10389: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10390: if there is no corresponding loncapa host.
10391:
1.243 albertel 10392: =back
10393:
1.986 foxr 10394:
1.243 albertel 10395: =head2 Apache Request
10396:
10397: =over 4
1.191 harris41 10398:
10399: =item *
10400:
1.243 albertel 10401: ssi($url,%hash) : server side include, does a complete request cycle on url to
10402: localhost, posts hash
10403:
10404: =back
10405:
10406: =head2 Data to String to Data
10407:
10408: =over 4
1.191 harris41 10409:
10410: =item *
10411:
1.243 albertel 10412: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10413: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 10414:
10415: =item *
10416:
1.243 albertel 10417: hashref2str($hashref) : convert a hashref into a string complete with
10418: escaping and '=' and '&' separators, supports elements that are
10419: arrayrefs and hashrefs
1.191 harris41 10420:
10421: =item *
10422:
1.243 albertel 10423: arrayref2str($arrayref) : convert an arrayref into a string complete
10424: with escaping and '&' separators, supports elements that are arrayrefs
10425: and hashrefs
1.191 harris41 10426:
10427: =item *
10428:
1.243 albertel 10429: str2hash($string) : convert string to hash using unescaping and
10430: splitting on '=' and '&', supports elements that are arrayrefs and
10431: hashrefs
1.191 harris41 10432:
10433: =item *
10434:
1.243 albertel 10435: str2array($string) : convert string to hash using unescaping and
10436: splitting on '&', supports elements that are arrayrefs and hashrefs
10437:
10438: =back
10439:
10440: =head2 Logging Routines
10441:
10442: =over 4
10443:
10444: These routines allow one to make log messages in the lonnet.log and
10445: lonnet.perm logfiles.
1.191 harris41 10446:
10447: =item *
10448:
1.243 albertel 10449: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 10450:
10451: =item *
10452:
1.243 albertel 10453: logthis() : append message to the normal lonnet.log file, it gets
10454: preiodically rolled over and deleted.
1.191 harris41 10455:
10456: =item *
10457:
1.243 albertel 10458: logperm() : append a permanent message to lonnet.perm.log, this log
10459: file never gets deleted by any automated portion of the system, only
10460: messages of critical importance should go in here.
10461:
10462: =back
10463:
10464: =head2 General File Helper Routines
10465:
10466: =over 4
1.191 harris41 10467:
10468: =item *
10469:
1.481 raeburn 10470: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10471: (a) files in /uploaded
10472: (i) If a local copy of the file exists -
10473: compares modification date of local copy with last-modified date for
10474: definitive version stored on home server for course. If local copy is
10475: stale, requests a new version from the home server and stores it.
10476: If the original has been removed from the home server, then local copy
10477: is unlinked.
10478: (ii) If local copy does not exist -
10479: requests the file from the home server and stores it.
10480:
10481: If $caller is 'uploadrep':
10482: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10483: for request for files originally uploaded via DOCS.
10484: - returns 'ok' if fresh local copy now available, -1 otherwise.
10485:
10486: Otherwise:
10487: This indicates a call from the content generation phase of the request.
10488: - returns the entire contents of the file or -1.
10489:
10490: (b) files in /res
10491: - returns the entire contents of a file or -1;
10492: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 10493:
1.712 albertel 10494:
10495: =item *
10496:
10497: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10498: reference
10499:
10500: returns either a stat() list of data about the file or an empty list
10501: if the file doesn't exist or couldn't find out about it (connection
10502: problems or user unknown)
10503:
1.191 harris41 10504: =item *
10505:
1.243 albertel 10506: filelocation($dir,$file) : returns file system location of a file
10507: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10508: directory that relative $file lookups are to looked in ($dir of /a/dir
10509: and a file of ../bob will become /a/bob)
1.191 harris41 10510:
10511: =item *
10512:
10513: hreflocation($dir,$file) : returns file system location or a URL; same as
10514: filelocation except for hrefs
10515:
10516: =item *
10517:
10518: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10519:
1.243 albertel 10520: =back
10521:
1.608 albertel 10522: =head2 Usererfile file routines (/uploaded*)
10523:
10524: =over 4
10525:
10526: =item *
10527:
10528: userfileupload(): main rotine for putting a file in a user or course's
10529: filespace, arguments are,
10530:
1.620 albertel 10531: formname - required - this is the name of the element in $env where the
1.608 albertel 10532: filename, and the contents of the file to create/modifed exist
1.620 albertel 10533: the filename is in $env{'form.'.$formname.'.filename'} and the
10534: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10535: coursedoc - if true, store the file in the course of the active role
10536: of the current user
10537: subdir - required - subdirectory to put the file in under ../userfiles/
10538: if undefined, it will be placed in "unknown"
10539:
10540: (This routine calls clean_filename() to remove any dangerous
10541: characters from the filename, and then calls finuserfileupload() to
10542: complete the transaction)
10543:
10544: returns either the url of the uploaded file (/uploaded/....) if successful
10545: and /adm/notfound.html if unsuccessful
10546:
10547: =item *
10548:
10549: clean_filename(): routine for cleaing a filename up for storage in
10550: userfile space, argument is:
10551:
10552: filename - proposed filename
10553:
10554: returns: the new clean filename
10555:
10556: =item *
10557:
10558: finishuserfileupload(): routine that creaes and sends the file to
10559: userspace, probably shouldn't be called directly
10560:
10561: docuname: username or courseid of destination for the file
10562: docudom: domain of user/course of destination for the file
10563: formname: same as for userfileupload()
10564: fname: filename (inculding subdirectories) for the file
10565:
10566: returns either the url of the uploaded file (/uploaded/....) if successful
10567: and /adm/notfound.html if unsuccessful
10568:
10569: =item *
10570:
10571: renameuserfile(): renames an existing userfile to a new name
10572:
10573: Args:
10574: docuname: username or courseid of destination for the file
10575: docudom: domain of user/course of destination for the file
10576: old: current file name (including any subdirs under userfiles)
10577: new: desired file name (including any subdirs under userfiles)
10578:
10579: =item *
10580:
10581: mkdiruserfile(): creates a directory is a userfiles dir
10582:
10583: Args:
10584: docuname: username or courseid of destination for the file
10585: docudom: domain of user/course of destination for the file
10586: dir: dir to create (including any subdirs under userfiles)
10587:
10588: =item *
10589:
10590: removeuserfile(): removes a file that exists in userfiles
10591:
10592: Args:
10593: docuname: username or courseid of destination for the file
10594: docudom: domain of user/course of destination for the file
10595: fname: filname to delete (including any subdirs under userfiles)
10596:
10597: =item *
10598:
10599: removeuploadedurl(): convience function for removeuserfile()
10600:
10601: Args:
10602: url: a full /uploaded/... url to delete
10603:
1.747 albertel 10604: =item *
10605:
10606: get_portfile_permissions():
10607: Args:
10608: domain: domain of user or course contain the portfolio files
10609: user: name of user or num of course contain the portfolio files
10610: Returns:
10611: hashref of a dump of the proper file_permissions.db
10612:
10613:
10614: =item *
10615:
10616: get_access_controls():
10617:
10618: Args:
10619: current_permissions: the hash ref returned from get_portfile_permissions()
10620: group: (optional) the group you want the files associated with
10621: file: (optional) the file you want access info on
10622:
10623: Returns:
1.749 raeburn 10624: a hash (keys are file names) of hashes containing
10625: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10626: values are XML containing access control settings (see below)
1.747 albertel 10627:
10628: Internal notes:
10629:
1.749 raeburn 10630: access controls are stored in file_permissions.db as key=value pairs.
10631: key -> path to file/file_name\0uniqueID:scope_end_start
10632: where scope -> public,guest,course,group,domains or users.
10633: end -> UNIX time for end of access (0 -> no end date)
10634: start -> UNIX time for start of access
10635:
10636: value -> XML description of access control
10637: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10638: <start></start>
10639: <end></end>
10640:
10641: <password></password> for scope type = guest
10642:
10643: <domain></domain> for scope type = course or group
10644: <number></number>
10645: <roles id="">
10646: <role></role>
10647: <access></access>
10648: <section></section>
10649: <group></group>
10650: </roles>
10651:
10652: <dom></dom> for scope type = domains
10653:
10654: <users> for scope type = users
10655: <user>
10656: <uname></uname>
10657: <udom></udom>
10658: </user>
10659: </users>
10660: </scope>
10661:
10662: Access data is also aggregated for each file in an additional key=value pair:
10663: key -> path to file/file_name\0accesscontrol
10664: value -> reference to hash
10665: hash contains key = value pairs
10666: where key = uniqueID:scope_end_start
10667: value = UNIX time record was last updated
10668:
10669: Used to improve speed of look-ups of access controls for each file.
10670:
10671: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10672:
10673: modify_access_controls():
10674:
10675: Modifies access controls for a portfolio file
10676: Args
10677: 1. file name
10678: 2. reference to hash of required changes,
10679: 3. domain
10680: 4. username
10681: where domain,username are the domain of the portfolio owner
10682: (either a user or a course)
10683:
10684: Returns:
10685: 1. result of additions or updates ('ok' or 'error', with error message).
10686: 2. result of deletions ('ok' or 'error', with error message).
10687: 3. reference to hash of any new or updated access controls.
10688: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10689: key = integer (inbound ID)
10690: value = uniqueID
1.747 albertel 10691:
1.608 albertel 10692: =back
10693:
1.243 albertel 10694: =head2 HTTP Helper Routines
10695:
10696: =over 4
10697:
1.191 harris41 10698: =item *
10699:
10700: escape() : unpack non-word characters into CGI-compatible hex codes
10701:
10702: =item *
10703:
10704: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10705:
1.243 albertel 10706: =back
10707:
10708: =head1 PRIVATE SUBROUTINES
10709:
10710: =head2 Underlying communication routines (Shouldn't call)
10711:
10712: =over 4
10713:
10714: =item *
10715:
10716: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10717:
10718: =item *
10719:
10720: reply() : uses subreply to send a message to remote machine, logs all failures
10721:
10722: =item *
10723:
10724: critical() : passes a critical message to another server; if cannot
10725: get through then place message in connection buffer directory and
10726: returns con_delayed, if incapable of saving message, returns
10727: con_failed
10728:
10729: =item *
10730:
10731: reconlonc() : tries to reconnect lonc client processes.
10732:
10733: =back
10734:
10735: =head2 Resource Access Logging
10736:
10737: =over 4
10738:
10739: =item *
10740:
10741: flushcourselogs() : flush (save) buffer logs and access logs
10742:
10743: =item *
10744:
10745: courselog($what) : save message for course in hash
10746:
10747: =item *
10748:
10749: courseacclog($what) : save message for course using &courselog(). Perform
10750: special processing for specific resource types (problems, exams, quizzes, etc).
10751:
1.191 harris41 10752: =item *
10753:
10754: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10755: as a PerlChildExitHandler
1.243 albertel 10756:
10757: =back
10758:
10759: =head2 Other
10760:
10761: =over 4
10762:
10763: =item *
10764:
10765: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 10766:
10767: =back
10768:
10769: =cut
1.877 foxr 10770:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>