Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1010
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1010 ! raeburn 4: # $Id: lonnet.pm,v 1.1009 2009/08/06 04:54:23 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968 raeburn 79: $_64bit %env %protocol);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.807 albertel 95: use LONCAPA qw(:DEFAULT :match);
1.740 www 96: use LONCAPA::Configuration;
1.676 albertel 97:
1.195 www 98: my $readit;
1.550 foxr 99: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 100:
1.977 amueller 101: my $upload_photo_form = 0; #Variable to check when user upload a photo 0=not 1=true
102:
1.619 albertel 103: require Exporter;
104:
105: our @ISA = qw (Exporter);
106: our @EXPORT = qw(%env);
107:
1.449 matthew 108:
1.1 albertel 109: # --------------------------------------------------------------------- Logging
1.729 www 110: {
111: my $logid;
112: sub instructor_log {
1.957 raeburn 113: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
114: if (($cnum eq '') || ($cdom eq '')) {
115: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
116: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
117: }
1.729 www 118: $logid++;
1.957 raeburn 119: my $now = time();
120: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 121: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 122: { $id => {
123: 'exe_uname' => $env{'user.name'},
124: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 125: 'exe_time' => $now,
1.730 www 126: 'exe_ip' => $ENV{'REMOTE_ADDR'},
127: 'delflag' => $delflag,
128: 'logentry' => $storehash,
129: 'uname' => $uname,
130: 'udom' => $udom,
131: }
1.957 raeburn 132: },$cdom,$cnum);
1.729 www 133: }
134: }
1.1 albertel 135:
1.163 harris41 136: sub logtouch {
137: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 138: unless (-e "$execdir/logs/lonnet.log") {
139: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 140: close $fh;
141: }
142: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
143: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
144: }
145:
1.1 albertel 146: sub logthis {
147: my $message=shift;
148: my $execdir=$perlvar{'lonDaemons'};
149: my $now=time;
150: my $local=localtime($now);
1.448 albertel 151: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 152: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
153: print $fh $logstring;
1.448 albertel 154: close($fh);
155: }
1.1 albertel 156: return 1;
157: }
158:
159: sub logperm {
160: my $message=shift;
161: my $execdir=$perlvar{'lonDaemons'};
162: my $now=time;
163: my $local=localtime($now);
1.448 albertel 164: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
165: print $fh "$now:$message:$local\n";
166: close($fh);
167: }
1.1 albertel 168: return 1;
169: }
170:
1.850 albertel 171: sub create_connection {
1.853 albertel 172: my ($hostname,$lonid) = @_;
1.851 albertel 173: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 174: Type => SOCK_STREAM,
175: Timeout => 10);
176: return 0 if (!$client);
1.890 albertel 177: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 178: my $result = <$client>;
179: chomp($result);
180: return 1 if ($result eq 'done');
181: return 0;
182: }
183:
1.983 raeburn 184: sub get_server_timezone {
185: my ($cnum,$cdom) = @_;
186: my $home=&homeserver($cnum,$cdom);
187: if ($home ne 'no_host') {
188: my $cachetime = 24*3600;
189: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
190: if (defined($cached)) {
191: return $timezone;
192: } else {
193: my $timezone = &reply('servertimezone',$home);
194: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
195: }
196: }
197: }
1.850 albertel 198:
1.993 raeburn 199: sub get_server_loncaparev {
200: my ($dom,$lonhost) = @_;
201: if (defined($lonhost)) {
202: if (!defined(&hostname($lonhost))) {
203: undef($lonhost);
204: }
205: }
206: if (!defined($lonhost)) {
207: if (defined(&domain($dom,'primary'))) {
208: $lonhost=&domain($dom,'primary');
209: if ($lonhost eq 'no_host') {
210: undef($lonhost);
211: }
212: }
213: }
214: if (defined($lonhost)) {
215: my $cachetime = 24*3600;
216: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
217: if (defined($cached)) {
218: return $loncaparev;
219: } else {
220: my $loncaparev = &reply('serverloncaparev',$lonhost);
221: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
222: }
223: }
224: }
225:
1.1 albertel 226: # -------------------------------------------------- Non-critical communication
227: sub subreply {
228: my ($cmd,$server)=@_;
1.838 albertel 229: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 230: #
231: # With loncnew process trimming, there's a timing hole between lonc server
232: # process exit and the master server picking up the listen on the AF_UNIX
233: # socket. In that time interval, a lock file will exist:
234:
235: my $lockfile=$peerfile.".lock";
236: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
237: sleep(1);
238: }
239: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 240: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 241: #
1.550 foxr 242: # We'll give the connection a few tries before abandoning it. If
243: # connection is not possible, we'll con_lost back to the client.
244: #
245: my $client;
246: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
247: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
248: Type => SOCK_STREAM,
249: Timeout => 10);
1.869 albertel 250: if ($client) {
1.550 foxr 251: last; # Connected!
1.850 albertel 252: } else {
1.853 albertel 253: &create_connection(&hostname($server),$server);
1.550 foxr 254: }
1.850 albertel 255: sleep(1); # Try again later if failed connection.
1.550 foxr 256: }
257: my $answer;
258: if ($client) {
1.704 albertel 259: print $client "sethost:$server:$cmd\n";
1.550 foxr 260: $answer=<$client>;
261: if (!$answer) { $answer="con_lost"; }
262: chomp($answer);
263: } else {
264: $answer = 'con_lost'; # Failed connection.
265: }
1.1 albertel 266: return $answer;
267: }
268:
269: sub reply {
270: my ($cmd,$server)=@_;
1.838 albertel 271: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 272: my $answer=subreply($cmd,$server);
1.65 www 273: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 274: &logthis("<font color=\"blue\">WARNING:".
1.12 www 275: " $cmd to $server returned $answer</font>");
276: }
1.1 albertel 277: return $answer;
278: }
279:
280: # ----------------------------------------------------------- Send USR1 to lonc
281:
282: sub reconlonc {
1.891 albertel 283: my ($lonid) = @_;
284: my $hostname = &hostname($lonid);
285: if ($lonid) {
286: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
287: if ($hostname && -e $peerfile) {
288: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
289: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
290: Type => SOCK_STREAM,
291: Timeout => 10);
292: if ($client) {
293: print $client ("reset_retries\n");
294: my $answer=<$client>;
295: #reset just this one.
296: }
297: }
298: return;
299: }
300:
1.836 www 301: &logthis("Trying to reconnect lonc");
1.1 albertel 302: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 303: if (open(my $fh,"<$loncfile")) {
1.1 albertel 304: my $loncpid=<$fh>;
305: chomp($loncpid);
306: if (kill 0 => $loncpid) {
307: &logthis("lonc at pid $loncpid responding, sending USR1");
308: kill USR1 => $loncpid;
309: sleep 1;
1.836 www 310: } else {
1.12 www 311: &logthis(
1.672 albertel 312: "<font color=\"blue\">WARNING:".
1.12 www 313: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 314: }
315: } else {
1.836 www 316: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 317: }
318: }
319:
320: # ------------------------------------------------------ Critical communication
1.12 www 321:
1.1 albertel 322: sub critical {
323: my ($cmd,$server)=@_;
1.838 albertel 324: unless (&hostname($server)) {
1.672 albertel 325: &logthis("<font color=\"blue\">WARNING:".
1.89 www 326: " Critical message to unknown server ($server)</font>");
327: return 'no_such_host';
328: }
1.1 albertel 329: my $answer=reply($cmd,$server);
330: if ($answer eq 'con_lost') {
331: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 332: my $answer=reply($cmd,$server);
1.1 albertel 333: if ($answer eq 'con_lost') {
334: my $now=time;
335: my $middlename=$cmd;
1.5 www 336: $middlename=substr($middlename,0,16);
1.1 albertel 337: $middlename=~s/\W//g;
338: my $dfilename=
1.305 www 339: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
340: $dumpcount++;
1.1 albertel 341: {
1.448 albertel 342: my $dfh;
343: if (open($dfh,">$dfilename")) {
344: print $dfh "$cmd\n";
345: close($dfh);
346: }
1.1 albertel 347: }
348: sleep 2;
349: my $wcmd='';
350: {
1.448 albertel 351: my $dfh;
352: if (open($dfh,"<$dfilename")) {
353: $wcmd=<$dfh>;
354: close($dfh);
355: }
1.1 albertel 356: }
357: chomp($wcmd);
1.7 www 358: if ($wcmd eq $cmd) {
1.672 albertel 359: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 360: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 361: &logperm("D:$server:$cmd");
362: return 'con_delayed';
363: } else {
1.672 albertel 364: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 365: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 366: &logperm("F:$server:$cmd");
367: return 'con_failed';
368: }
369: }
370: }
371: return $answer;
1.405 albertel 372: }
373:
1.755 albertel 374: # ------------------------------------------- check if return value is an error
375:
376: sub error {
377: my ($result) = @_;
1.756 albertel 378: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 379: if ($2 == 2) { return undef; }
380: return $1;
381: }
382: return undef;
383: }
384:
1.783 albertel 385: sub convert_and_load_session_env {
386: my ($lonidsdir,$handle)=@_;
387: my @profile;
388: {
1.917 albertel 389: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
390: if (!$opened) {
1.915 albertel 391: return 0;
392: }
1.783 albertel 393: flock($idf,LOCK_SH);
394: @profile=<$idf>;
395: close($idf);
396: }
397: my %temp_env;
398: foreach my $line (@profile) {
1.786 albertel 399: if ($line !~ m/=/) {
400: return 0;
401: }
1.783 albertel 402: chomp($line);
403: my ($envname,$envvalue)=split(/=/,$line,2);
404: $temp_env{&unescape($envname)} = &unescape($envvalue);
405: }
406: unlink("$lonidsdir/$handle.id");
407: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
408: 0640)) {
409: %disk_env = %temp_env;
410: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
411: untie(%disk_env);
412: }
1.786 albertel 413: return 1;
1.783 albertel 414: }
415:
1.374 www 416: # ------------------------------------------- Transfer profile into environment
1.780 albertel 417: my $env_loaded;
418: sub transfer_profile_to_env {
1.788 albertel 419: my ($lonidsdir,$handle,$force_transfer) = @_;
420: if (!$force_transfer && $env_loaded) { return; }
1.374 www 421:
1.720 albertel 422: if (!defined($lonidsdir)) {
423: $lonidsdir = $perlvar{'lonIDsDir'};
424: }
425: if (!defined($handle)) {
426: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
427: }
428:
1.786 albertel 429: my $convert;
430: {
1.917 albertel 431: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
432: if (!$opened) {
1.915 albertel 433: return;
434: }
1.786 albertel 435: flock($idf,LOCK_SH);
436: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
437: &GDBM_READER(),0640)) {
438: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
439: untie(%disk_env);
440: } else {
441: $convert = 1;
442: }
443: }
444: if ($convert) {
445: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
446: &logthis("Failed to load session, or convert session.");
447: }
1.374 www 448: }
1.783 albertel 449:
1.786 albertel 450: my %remove;
1.783 albertel 451: while ( my $envname = each(%env) ) {
1.433 matthew 452: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
453: if ($time < time-300) {
1.783 albertel 454: $remove{$key}++;
1.433 matthew 455: }
456: }
457: }
1.783 albertel 458:
1.619 albertel 459: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 460: $env_loaded=1;
1.783 albertel 461: foreach my $expired_key (keys(%remove)) {
1.433 matthew 462: &delenv($expired_key);
1.374 www 463: }
1.1 albertel 464: }
465:
1.916 albertel 466: # ---------------------------------------------------- Check for valid session
467: sub check_for_valid_session {
468: my ($r) = @_;
469: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
470: my $lonid=$cookies{'lonID'};
471: return undef if (!$lonid);
472:
473: my $handle=&LONCAPA::clean_handle($lonid->value);
474: my $lonidsdir=$r->dir_config('lonIDsDir');
475: return undef if (!-e "$lonidsdir/$handle.id");
476:
1.917 albertel 477: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
478: return undef if (!$opened);
1.916 albertel 479:
480: flock($idf,LOCK_SH);
481: my %disk_env;
482: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
483: &GDBM_READER(),0640)) {
484: return undef;
485: }
486:
487: if (!defined($disk_env{'user.name'})
488: || !defined($disk_env{'user.domain'})) {
489: return undef;
490: }
491: return $handle;
492: }
493:
1.830 albertel 494: sub timed_flock {
495: my ($file,$lock_type) = @_;
496: my $failed=0;
497: eval {
498: local $SIG{__DIE__}='DEFAULT';
499: local $SIG{ALRM}=sub {
500: $failed=1;
501: die("failed lock");
502: };
503: alarm(13);
504: flock($file,$lock_type);
505: alarm(0);
506: };
507: if ($failed) {
508: return undef;
509: } else {
510: return 1;
511: }
512: }
513:
1.5 www 514: # ---------------------------------------------------------- Append Environment
515:
516: sub appenv {
1.949 raeburn 517: my ($newenv,$roles) = @_;
518: if (ref($newenv) eq 'HASH') {
519: foreach my $key (keys(%{$newenv})) {
520: my $refused = 0;
521: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
522: $refused = 1;
523: if (ref($roles) eq 'ARRAY') {
524: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
525: if (grep(/^\Q$role\E$/,@{$roles})) {
526: $refused = 0;
527: }
528: }
529: }
530: if ($refused) {
531: &logthis("<font color=\"blue\">WARNING: ".
532: "Attempt to modify environment ".$key." to ".$newenv->{$key}
533: .'</font>');
534: delete($newenv->{$key});
535: } else {
536: $env{$key}=$newenv->{$key};
537: }
538: }
539: my $opened = open(my $env_file,'+<',$env{'user.environment'});
540: if ($opened
541: && &timed_flock($env_file,LOCK_EX)
542: &&
543: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
544: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
545: while (my ($key,$value) = each(%{$newenv})) {
546: $disk_env{$key} = $value;
547: }
548: untie(%disk_env);
1.35 www 549: }
1.191 harris41 550: }
1.56 www 551: return 'ok';
552: }
553: # ----------------------------------------------------- Delete from Environment
554:
555: sub delenv {
1.987 raeburn 556: my ($delthis,$regexp) = @_;
1.56 www 557: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 558: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 559: "Attempt to delete from environment ".$delthis);
560: return 'error';
561: }
1.917 albertel 562: my $opened = open(my $env_file,'+<',$env{'user.environment'});
563: if ($opened
1.915 albertel 564: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 565: &&
566: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
567: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 568: foreach my $key (keys(%disk_env)) {
1.987 raeburn 569: if ($regexp) {
570: if ($key=~/^$delthis/) {
571: delete($env{$key});
572: delete($disk_env{$key});
573: }
574: } else {
575: if ($key=~/^\Q$delthis\E/) {
576: delete($env{$key});
577: delete($disk_env{$key});
578: }
579: }
1.448 albertel 580: }
1.783 albertel 581: untie(%disk_env);
1.5 www 582: }
583: return 'ok';
1.369 albertel 584: }
585:
1.790 albertel 586: sub get_env_multiple {
587: my ($name) = @_;
588: my @values;
589: if (defined($env{$name})) {
590: # exists is it an array
591: if (ref($env{$name})) {
592: @values=@{ $env{$name} };
593: } else {
594: $values[0]=$env{$name};
595: }
596: }
597: return(@values);
598: }
599:
1.958 www 600: # ------------------------------------------------------------------- Locking
601:
602: sub set_lock {
603: my ($text)=@_;
604: $locknum++;
605: my $id=$$.'-'.$locknum;
606: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
607: 'session.lock.'.$id => $text});
608: return $id;
609: }
610:
611: sub get_locks {
612: my $num=0;
613: my %texts=();
614: foreach my $lock (split(/\,/,$env{'session.locks'})) {
615: if ($lock=~/\w/) {
616: $num++;
617: $texts{$lock}=$env{'session.lock.'.$lock};
618: }
619: }
620: return ($num,%texts);
621: }
622:
623: sub remove_lock {
624: my ($id)=@_;
625: my $newlocks='';
626: foreach my $lock (split(/\,/,$env{'session.locks'})) {
627: if (($lock=~/\w/) && ($lock ne $id)) {
628: $newlocks.=','.$lock;
629: }
630: }
631: &appenv({'session.locks' => $newlocks});
632: &delenv('session.lock.'.$id);
633: }
634:
635: sub remove_all_locks {
636: my $activelocks=$env{'session.locks'};
637: foreach my $lock (split(/\,/,$env{'session.locks'})) {
638: if ($lock=~/\w/) {
639: &remove_lock($lock);
640: }
641: }
642: }
643:
644:
1.369 albertel 645: # ------------------------------------------ Find out current server userload
646: sub userload {
647: my $numusers=0;
648: {
649: opendir(LONIDS,$perlvar{'lonIDsDir'});
650: my $filename;
651: my $curtime=time;
652: while ($filename=readdir(LONIDS)) {
1.925 albertel 653: next if ($filename eq '.' || $filename eq '..');
654: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 655: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 656: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 657: }
658: closedir(LONIDS);
659: }
660: my $userloadpercent=0;
661: my $maxuserload=$perlvar{'lonUserLoadLim'};
662: if ($maxuserload) {
1.371 albertel 663: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 664: }
1.372 albertel 665: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 666: return $userloadpercent;
1.283 www 667: }
668:
669: # ------------------------------------------ Fight off request when overloaded
670:
671: sub overloaderror {
672: my ($r,$checkserver)=@_;
673: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
674: my $loadavg;
675: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 676: open(my $loadfile,'/proc/loadavg');
1.283 www 677: $loadavg=<$loadfile>;
678: $loadavg =~ s/\s.*//g;
1.285 matthew 679: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 680: close($loadfile);
1.283 www 681: } else {
682: $loadavg=&reply('load',$checkserver);
683: }
1.285 matthew 684: my $overload=$loadavg-100;
1.283 www 685: if ($overload>0) {
1.285 matthew 686: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 687: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 688: return 413;
1.283 www 689: }
690: return '';
1.5 www 691: }
1.1 albertel 692:
693: # ------------------------------ Find server with least workload from spare.tab
1.11 www 694:
1.1 albertel 695: sub spareserver {
1.670 albertel 696: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 697: my $spare_server;
1.370 albertel 698: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 699: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
700: : $userloadpercent;
701:
702: foreach my $try_server (@{ $spareid{'primary'} }) {
703: ($spare_server, $lowest_load) =
704: &compare_server_load($try_server, $spare_server, $lowest_load);
705: }
706:
707: my $found_server = ($spare_server ne '' && $lowest_load < 100);
708:
709: if (!$found_server) {
710: foreach my $try_server (@{ $spareid{'default'} }) {
711: ($spare_server, $lowest_load) =
712: &compare_server_load($try_server, $spare_server, $lowest_load);
713: }
714: }
715:
716: if (!$want_server_name) {
1.968 raeburn 717: my $protocol = 'http';
718: if ($protocol{$spare_server} eq 'https') {
719: $protocol = $protocol{$spare_server};
720: }
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.806 raeburn 961: # ------------------------------------------- get items from domain db files
962:
963: sub get_dom {
1.860 raeburn 964: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 965: my $items='';
966: foreach my $item (@$storearr) {
967: $items.=&escape($item).'&';
968: }
969: $items=~s/\&$//;
1.860 raeburn 970: if (!$udom) {
971: $udom=$env{'user.domain'};
972: if (defined(&domain($udom,'primary'))) {
973: $uhome=&domain($udom,'primary');
974: } else {
1.874 albertel 975: undef($uhome);
1.860 raeburn 976: }
977: } else {
978: if (!$uhome) {
979: if (defined(&domain($udom,'primary'))) {
980: $uhome=&domain($udom,'primary');
981: }
982: }
983: }
984: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 985: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 986: my %returnhash;
1.875 albertel 987: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 988: return %returnhash;
989: }
1.806 raeburn 990: my @pairs=split(/\&/,$rep);
991: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
992: return @pairs;
993: }
994: my $i=0;
995: foreach my $item (@$storearr) {
996: $returnhash{$item}=&thaw_unescape($pairs[$i]);
997: $i++;
998: }
999: return %returnhash;
1000: } else {
1.880 banghart 1001: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1002: }
1003: }
1004:
1005: # -------------------------------------------- put items in domain db files
1006:
1007: sub put_dom {
1.860 raeburn 1008: my ($namespace,$storehash,$udom,$uhome)=@_;
1009: if (!$udom) {
1010: $udom=$env{'user.domain'};
1011: if (defined(&domain($udom,'primary'))) {
1012: $uhome=&domain($udom,'primary');
1013: } else {
1.874 albertel 1014: undef($uhome);
1.860 raeburn 1015: }
1016: } else {
1017: if (!$uhome) {
1018: if (defined(&domain($udom,'primary'))) {
1019: $uhome=&domain($udom,'primary');
1020: }
1021: }
1022: }
1023: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1024: my $items='';
1025: foreach my $item (keys(%$storehash)) {
1026: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1027: }
1028: $items=~s/\&$//;
1029: return &reply("putdom:$udom:$namespace:$items",$uhome);
1030: } else {
1.860 raeburn 1031: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1032: }
1033: }
1034:
1.837 raeburn 1035: sub retrieve_inst_usertypes {
1036: my ($udom) = @_;
1037: my (%returnhash,@order);
1.989 raeburn 1038: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1039: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1040: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1041: %returnhash = %{$domdefs{'inststatustypes'}};
1042: @order = @{$domdefs{'inststatusorder'}};
1043: } else {
1044: if (defined(&domain($udom,'primary'))) {
1045: my $uhome=&domain($udom,'primary');
1046: my $rep=&reply("inst_usertypes:$udom",$uhome);
1047: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1048: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1049: return (\%returnhash,\@order);
1050: }
1051: my ($hashitems,$orderitems) = split(/:/,$rep);
1052: my @pairs=split(/\&/,$hashitems);
1053: foreach my $item (@pairs) {
1054: my ($key,$value)=split(/=/,$item,2);
1055: $key = &unescape($key);
1056: next if ($key =~ /^error: 2 /);
1057: $returnhash{$key}=&thaw_unescape($value);
1058: }
1059: my @esc_order = split(/\&/,$orderitems);
1060: foreach my $item (@esc_order) {
1061: push(@order,&unescape($item));
1062: }
1063: } else {
1064: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1065: }
1066: }
1067: return (\%returnhash,\@order);
1068: }
1069:
1.868 raeburn 1070: sub is_domainimage {
1071: my ($url) = @_;
1072: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1073: if (&domain($1) ne '') {
1074: return '1';
1075: }
1076: }
1077: return;
1078: }
1079:
1.899 raeburn 1080: sub inst_directory_query {
1081: my ($srch) = @_;
1082: my $udom = $srch->{'srchdomain'};
1083: my %results;
1084: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1085: my $outcome;
1.899 raeburn 1086: if ($homeserver ne '') {
1.904 albertel 1087: my $queryid=&reply("querysend:instdirsearch:".
1088: &escape($srch->{'srchby'}).':'.
1089: &escape($srch->{'srchterm'}).':'.
1090: &escape($srch->{'srchtype'}),$homeserver);
1091: my $host=&hostname($homeserver);
1092: if ($queryid !~/^\Q$host\E\_/) {
1093: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1094: return;
1095: }
1096: my $response = &get_query_reply($queryid);
1097: my $maxtries = 5;
1098: my $tries = 1;
1099: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1100: $response = &get_query_reply($queryid);
1101: $tries ++;
1102: }
1103:
1104: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1105: if ($response eq 'unavailable') {
1106: $outcome = $response;
1107: } else {
1108: $outcome = 'ok';
1109: my @matches = split(/\n/,$response);
1110: foreach my $match (@matches) {
1111: my ($key,$value) = split(/=/,$match);
1112: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1113: }
1.899 raeburn 1114: }
1115: }
1116: }
1.909 raeburn 1117: return ($outcome,%results);
1.899 raeburn 1118: }
1119:
1120: sub usersearch {
1121: my ($srch) = @_;
1122: my $dom = $srch->{'srchdomain'};
1123: my %results;
1124: my %libserv = &all_library();
1125: my $query = 'usersearch';
1126: foreach my $tryserver (keys(%libserv)) {
1127: if (&host_domain($tryserver) eq $dom) {
1128: my $host=&hostname($tryserver);
1129: my $queryid=
1.911 raeburn 1130: &reply("querysend:".&escape($query).':'.
1131: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1132: &escape($srch->{'srchtype'}).':'.
1133: &escape($srch->{'srchterm'}),$tryserver);
1134: if ($queryid !~/^\Q$host\E\_/) {
1135: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1136: next;
1.899 raeburn 1137: }
1138: my $reply = &get_query_reply($queryid);
1139: my $maxtries = 1;
1140: my $tries = 1;
1141: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1142: $reply = &get_query_reply($queryid);
1143: $tries ++;
1144: }
1145: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1146: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1147: } else {
1.911 raeburn 1148: my @matches;
1149: if ($reply =~ /\n/) {
1150: @matches = split(/\n/,$reply);
1151: } else {
1152: @matches = split(/\&/,$reply);
1153: }
1.899 raeburn 1154: foreach my $match (@matches) {
1155: my ($uname,$udom,%userhash);
1.911 raeburn 1156: foreach my $entry (split(/:/,$match)) {
1157: my ($key,$value) =
1158: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1159: $userhash{$key} = $value;
1160: if ($key eq 'username') {
1161: $uname = $value;
1162: } elsif ($key eq 'domain') {
1163: $udom = $value;
1.911 raeburn 1164: }
1.899 raeburn 1165: }
1166: $results{$uname.':'.$udom} = \%userhash;
1167: }
1168: }
1169: }
1170: }
1171: return %results;
1172: }
1173:
1.912 raeburn 1174: sub get_instuser {
1175: my ($udom,$uname,$id) = @_;
1176: my $homeserver = &domain($udom,'primary');
1177: my ($outcome,%results);
1178: if ($homeserver ne '') {
1179: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1180: &escape($id).':'.&escape($udom),$homeserver);
1181: my $host=&hostname($homeserver);
1182: if ($queryid !~/^\Q$host\E\_/) {
1183: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1184: return;
1185: }
1186: my $response = &get_query_reply($queryid);
1187: my $maxtries = 5;
1188: my $tries = 1;
1189: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1190: $response = &get_query_reply($queryid);
1191: $tries ++;
1192: }
1193: if (!&error($response) && $response ne 'refused') {
1194: if ($response eq 'unavailable') {
1195: $outcome = $response;
1196: } else {
1197: $outcome = 'ok';
1198: my @matches = split(/\n/,$response);
1199: foreach my $match (@matches) {
1200: my ($key,$value) = split(/=/,$match);
1201: $results{&unescape($key)} = &thaw_unescape($value);
1202: }
1203: }
1204: }
1205: }
1206: my %userinfo;
1207: if (ref($results{$uname}) eq 'HASH') {
1208: %userinfo = %{$results{$uname}};
1209: }
1210: return ($outcome,%userinfo);
1211: }
1212:
1213: sub inst_rulecheck {
1.923 raeburn 1214: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1215: my %returnhash;
1216: if ($udom ne '') {
1217: if (ref($rules) eq 'ARRAY') {
1218: @{$rules} = map {&escape($_);} (@{$rules});
1219: my $rulestr = join(':',@{$rules});
1220: my $homeserver=&domain($udom,'primary');
1221: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1222: my $response;
1223: if ($item eq 'username') {
1224: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1225: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1226: $homeserver));
1.923 raeburn 1227: } elsif ($item eq 'id') {
1228: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1229: ':'.&escape($id).':'.$rulestr,
1230: $homeserver));
1.945 raeburn 1231: } elsif ($item eq 'selfcreate') {
1232: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1233: &escape($udom).':'.&escape($uname).
1234: ':'.$rulestr,$homeserver));
1.923 raeburn 1235: }
1.912 raeburn 1236: if ($response ne 'refused') {
1237: my @pairs=split(/\&/,$response);
1238: foreach my $item (@pairs) {
1239: my ($key,$value)=split(/=/,$item,2);
1240: $key = &unescape($key);
1241: next if ($key =~ /^error: 2 /);
1242: $returnhash{$key}=&thaw_unescape($value);
1243: }
1244: }
1245: }
1246: }
1247: }
1248: return %returnhash;
1249: }
1250:
1251: sub inst_userrules {
1.923 raeburn 1252: my ($udom,$check) = @_;
1.912 raeburn 1253: my (%ruleshash,@ruleorder);
1254: if ($udom ne '') {
1255: my $homeserver=&domain($udom,'primary');
1256: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1257: my $response;
1258: if ($check eq 'id') {
1259: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1260: $homeserver);
1.943 raeburn 1261: } elsif ($check eq 'email') {
1262: $response=&reply('instemailrules:'.&escape($udom),
1263: $homeserver);
1.923 raeburn 1264: } else {
1265: $response=&reply('instuserrules:'.&escape($udom),
1266: $homeserver);
1267: }
1.912 raeburn 1268: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1269: ($response ne 'unknown_cmd') &&
1.912 raeburn 1270: ($response ne 'no_such_host')) {
1271: my ($hashitems,$orderitems) = split(/:/,$response);
1272: my @pairs=split(/\&/,$hashitems);
1273: foreach my $item (@pairs) {
1274: my ($key,$value)=split(/=/,$item,2);
1275: $key = &unescape($key);
1276: next if ($key =~ /^error: 2 /);
1277: $ruleshash{$key}=&thaw_unescape($value);
1278: }
1279: my @esc_order = split(/\&/,$orderitems);
1280: foreach my $item (@esc_order) {
1281: push(@ruleorder,&unescape($item));
1282: }
1283: }
1284: }
1285: }
1286: return (\%ruleshash,\@ruleorder);
1287: }
1288:
1.976 raeburn 1289: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1290:
1291: sub get_domain_defaults {
1292: my ($domain) = @_;
1293: my $cachetime = 60*60*24;
1294: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1295: if (defined($cached)) {
1296: if (ref($result) eq 'HASH') {
1297: return %{$result};
1298: }
1299: }
1300: my %domdefaults;
1301: my %domconfig =
1.989 raeburn 1302: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1303: 'requestcourses','inststatus'],$domain);
1.943 raeburn 1304: if (ref($domconfig{'defaults'}) eq 'HASH') {
1305: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1306: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1307: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1308: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1309: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1310: } else {
1311: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1312: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1313: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1314: }
1.976 raeburn 1315: if (ref($domconfig{'quotas'}) eq 'HASH') {
1316: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1317: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1318: } else {
1319: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1320: }
1321: my @usertools = ('aboutme','blog','portfolio');
1322: foreach my $item (@usertools) {
1323: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1324: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1325: }
1326: }
1327: }
1.985 raeburn 1328: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1329: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1330: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1331: }
1332: }
1.989 raeburn 1333: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1334: foreach my $item ('inststatustypes','inststatusorder') {
1335: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1336: }
1337: }
1.943 raeburn 1338: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1339: $cachetime);
1340: return %domdefaults;
1341: }
1342:
1.344 www 1343: # --------------------------------------------------- Assign a key to a student
1344:
1345: sub assign_access_key {
1.364 www 1346: #
1347: # a valid key looks like uname:udom#comments
1348: # comments are being appended
1349: #
1.498 www 1350: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1351: $kdom=
1.620 albertel 1352: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1353: $knum=
1.620 albertel 1354: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1355: $cdom=
1.620 albertel 1356: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1357: $cnum=
1.620 albertel 1358: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1359: $udom=$env{'user.name'} unless (defined($udom));
1360: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1361: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1362: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1363: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1364: # assigned to this person
1365: # - this should not happen,
1.345 www 1366: # unless something went wrong
1367: # the first time around
1368: # ready to assign
1.364 www 1369: $logentry=$1.'; '.$logentry;
1.496 www 1370: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1371: $kdom,$knum) eq 'ok') {
1.345 www 1372: # key now belongs to user
1.346 www 1373: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1374: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1375: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1376: return 'ok';
1377: } else {
1378: return
1379: 'error: Count not permanently assign key, will need to be re-entered later.';
1380: }
1381: } else {
1382: return 'error: Could not assign key, try again later.';
1383: }
1.364 www 1384: } elsif (!$existing{$ckey}) {
1.345 www 1385: # the key does not exist
1386: return 'error: The key does not exist';
1387: } else {
1388: # the key is somebody else's
1389: return 'error: The key is already in use';
1390: }
1.344 www 1391: }
1392:
1.364 www 1393: # ------------------------------------------ put an additional comment on a key
1394:
1395: sub comment_access_key {
1396: #
1397: # a valid key looks like uname:udom#comments
1398: # comments are being appended
1399: #
1400: my ($ckey,$cdom,$cnum,$logentry)=@_;
1401: $cdom=
1.620 albertel 1402: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1403: $cnum=
1.620 albertel 1404: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1405: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1406: if ($existing{$ckey}) {
1407: $existing{$ckey}.='; '.$logentry;
1408: # ready to assign
1.367 www 1409: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1410: $cdom,$cnum) eq 'ok') {
1411: return 'ok';
1412: } else {
1413: return 'error: Count not store comment.';
1414: }
1415: } else {
1416: # the key does not exist
1417: return 'error: The key does not exist';
1418: }
1419: }
1420:
1.344 www 1421: # ------------------------------------------------------ Generate a set of keys
1422:
1423: sub generate_access_keys {
1.364 www 1424: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1425: $cdom=
1.620 albertel 1426: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1427: $cnum=
1.620 albertel 1428: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1429: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1430: unless (($cdom) && ($cnum)) { return 0; }
1431: if ($number>10000) { return 0; }
1432: sleep(2); # make sure don't get same seed twice
1433: srand(time()^($$+($$<<15))); # from "Programming Perl"
1434: my $total=0;
1435: for (my $i=1;$i<=$number;$i++) {
1436: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1437: sprintf("%lx",int(100000*rand)).'-'.
1438: sprintf("%lx",int(100000*rand));
1439: $newkey=~s/1/g/g; # folks mix up 1 and l
1440: $newkey=~s/0/h/g; # and also 0 and O
1441: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1442: if ($existing{$newkey}) {
1443: $i--;
1444: } else {
1.364 www 1445: if (&put('accesskeys',
1446: { $newkey => '# generated '.localtime().
1.620 albertel 1447: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1448: '; '.$logentry },
1449: $cdom,$cnum) eq 'ok') {
1.344 www 1450: $total++;
1451: }
1452: }
1453: }
1.620 albertel 1454: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1455: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1456: return $total;
1457: }
1458:
1459: # ------------------------------------------------------- Validate an accesskey
1460:
1461: sub validate_access_key {
1462: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1463: $cdom=
1.620 albertel 1464: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1465: $cnum=
1.620 albertel 1466: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1467: $udom=$env{'user.domain'} unless (defined($udom));
1468: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1469: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1470: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1471: }
1472:
1473: # ------------------------------------- Find the section of student in a course
1.652 albertel 1474: sub devalidate_getsection_cache {
1475: my ($udom,$unam,$courseid)=@_;
1476: my $hashid="$udom:$unam:$courseid";
1477: &devalidate_cache_new('getsection',$hashid);
1478: }
1.298 matthew 1479:
1.815 albertel 1480: sub courseid_to_courseurl {
1481: my ($courseid) = @_;
1482: #already url style courseid
1483: return $courseid if ($courseid =~ m{^/});
1484:
1485: if (exists($env{'course.'.$courseid.'.num'})) {
1486: my $cnum = $env{'course.'.$courseid.'.num'};
1487: my $cdom = $env{'course.'.$courseid.'.domain'};
1488: return "/$cdom/$cnum";
1489: }
1490:
1491: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1492: if (exists($courseinfo{'num'})) {
1493: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1494: }
1495:
1496: return undef;
1497: }
1498:
1.298 matthew 1499: sub getsection {
1500: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1501: my $cachetime=1800;
1.551 albertel 1502:
1503: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1504: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1505: if (defined($cached)) { return $result; }
1506:
1.298 matthew 1507: my %Pending;
1508: my %Expired;
1509: #
1510: # Each role can either have not started yet (pending), be active,
1511: # or have expired.
1512: #
1513: # If there is an active role, we are done.
1514: #
1515: # If there is more than one role which has not started yet,
1516: # choose the one which will start sooner
1517: # If there is one role which has not started yet, return it.
1518: #
1519: # If there is more than one expired role, choose the one which ended last.
1520: # If there is a role which has expired, return it.
1521: #
1.815 albertel 1522: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1523: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1524: foreach my $key (keys(%roleshash)) {
1.479 albertel 1525: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1526: my $section=$1;
1527: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1528: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1529: my $now=time;
1.548 albertel 1530: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1531: $Expired{$end}=$section;
1532: next;
1533: }
1.548 albertel 1534: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1535: $Pending{$start}=$section;
1536: next;
1537: }
1.599 albertel 1538: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1539: }
1540: #
1541: # Presumedly there will be few matching roles from the above
1542: # loop and the sorting time will be negligible.
1543: if (scalar(keys(%Pending))) {
1544: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1545: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1546: }
1547: if (scalar(keys(%Expired))) {
1548: my @sorted = sort {$a <=> $b} keys(%Expired);
1549: my $time = pop(@sorted);
1.599 albertel 1550: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1551: }
1.599 albertel 1552: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1553: }
1.70 www 1554:
1.599 albertel 1555: sub save_cache {
1556: &purge_remembered();
1.722 albertel 1557: #&Apache::loncommon::validate_page();
1.620 albertel 1558: undef(%env);
1.780 albertel 1559: undef($env_loaded);
1.599 albertel 1560: }
1.452 albertel 1561:
1.599 albertel 1562: my $to_remember=-1;
1563: my %remembered;
1564: my %accessed;
1565: my $kicks=0;
1566: my $hits=0;
1.849 albertel 1567: sub make_key {
1568: my ($name,$id) = @_;
1.872 albertel 1569: if (length($id) > 65
1570: && length(&escape($id)) > 200) {
1571: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1572: }
1.849 albertel 1573: return &escape($name.':'.$id);
1574: }
1575:
1.599 albertel 1576: sub devalidate_cache_new {
1577: my ($name,$id,$debug) = @_;
1578: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1579: $id=&make_key($name,$id);
1.599 albertel 1580: $memcache->delete($id);
1581: delete($remembered{$id});
1582: delete($accessed{$id});
1583: }
1584:
1585: sub is_cached_new {
1586: my ($name,$id,$debug) = @_;
1.849 albertel 1587: $id=&make_key($name,$id);
1.599 albertel 1588: if (exists($remembered{$id})) {
1589: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1590: $accessed{$id}=[&gettimeofday()];
1591: $hits++;
1592: return ($remembered{$id},1);
1593: }
1594: my $value = $memcache->get($id);
1595: if (!(defined($value))) {
1596: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1597: return (undef,undef);
1.416 albertel 1598: }
1.599 albertel 1599: if ($value eq '__undef__') {
1600: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1601: $value=undef;
1602: }
1603: &make_room($id,$value,$debug);
1604: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1605: return ($value,1);
1606: }
1607:
1608: sub do_cache_new {
1609: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1610: $id=&make_key($name,$id);
1.599 albertel 1611: my $setvalue=$value;
1612: if (!defined($setvalue)) {
1613: $setvalue='__undef__';
1614: }
1.623 albertel 1615: if (!defined($time) ) {
1616: $time=600;
1617: }
1.599 albertel 1618: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1619: my $result = $memcache->set($id,$setvalue,$time);
1620: if (! $result) {
1.872 albertel 1621: &logthis("caching of id -> $id failed");
1.910 albertel 1622: $memcache->disconnect_all();
1.872 albertel 1623: }
1.600 albertel 1624: # need to make a copy of $value
1.919 albertel 1625: &make_room($id,$value,$debug);
1.599 albertel 1626: return $value;
1627: }
1628:
1629: sub make_room {
1630: my ($id,$value,$debug)=@_;
1.919 albertel 1631:
1632: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1633: : $value;
1.599 albertel 1634: if ($to_remember<0) { return; }
1635: $accessed{$id}=[&gettimeofday()];
1636: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1637: my $to_kick;
1638: my $max_time=0;
1639: foreach my $other (keys(%accessed)) {
1640: if (&tv_interval($accessed{$other}) > $max_time) {
1641: $to_kick=$other;
1642: $max_time=&tv_interval($accessed{$other});
1643: }
1644: }
1645: delete($remembered{$to_kick});
1646: delete($accessed{$to_kick});
1647: $kicks++;
1648: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1649: return;
1650: }
1651:
1.599 albertel 1652: sub purge_remembered {
1.604 albertel 1653: #&logthis("Tossing ".scalar(keys(%remembered)));
1654: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1655: undef(%remembered);
1656: undef(%accessed);
1.428 albertel 1657: }
1.70 www 1658: # ------------------------------------- Read an entry from a user's environment
1659:
1660: sub userenvironment {
1661: my ($udom,$unam,@what)=@_;
1.976 raeburn 1662: my $items;
1663: foreach my $item (@what) {
1664: $items.=&escape($item).'&';
1665: }
1666: $items=~s/\&$//;
1.70 www 1667: my %returnhash=();
1.1009 raeburn 1668: my $uhome = &homeserver($unam,$udom);
1669: unless ($uhome eq 'no_host') {
1670: my @answer=split(/\&/,
1671: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1672: my $i;
1673: for ($i=0;$i<=$#what;$i++) {
1674: $returnhash{$what[$i]}=&unescape($answer[$i]);
1675: }
1.70 www 1676: }
1677: return %returnhash;
1.1 albertel 1678: }
1679:
1.617 albertel 1680: # ---------------------------------------------------------- Get a studentphoto
1681: sub studentphoto {
1682: my ($udom,$unam,$ext) = @_;
1683: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1684: if (defined($env{'request.course.id'})) {
1.708 raeburn 1685: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1686: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1687: return(&retrievestudentphoto($udom,$unam,$ext));
1688: } else {
1689: my ($result,$perm_reqd)=
1.707 albertel 1690: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1691: if ($result eq 'ok') {
1692: if (!($perm_reqd eq 'yes')) {
1693: return(&retrievestudentphoto($udom,$unam,$ext));
1694: }
1695: }
1696: }
1697: }
1698: } else {
1699: my ($result,$perm_reqd) =
1.707 albertel 1700: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1701: if ($result eq 'ok') {
1702: if (!($perm_reqd eq 'yes')) {
1703: return(&retrievestudentphoto($udom,$unam,$ext));
1704: }
1705: }
1706: }
1707: return '/adm/lonKaputt/lonlogo_broken.gif';
1708: }
1709:
1710: sub retrievestudentphoto {
1711: my ($udom,$unam,$ext,$type) = @_;
1712: my $home=&Apache::lonnet::homeserver($unam,$udom);
1713: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1714: if ($ret eq 'ok') {
1715: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1716: if ($type eq 'thumbnail') {
1717: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1718: }
1719: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1720: return $tokenurl;
1721: } else {
1722: if ($type eq 'thumbnail') {
1723: return '/adm/lonKaputt/genericstudent_tn.gif';
1724: } else {
1725: return '/adm/lonKaputt/lonlogo_broken.gif';
1726: }
1.617 albertel 1727: }
1728: }
1729:
1.263 www 1730: # -------------------------------------------------------------------- New chat
1731:
1732: sub chatsend {
1.724 raeburn 1733: my ($newentry,$anon,$group)=@_;
1.620 albertel 1734: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1735: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1736: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1737: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1738: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1739: &escape($newentry)).':'.$group,$chome);
1.292 www 1740: }
1741:
1742: # ------------------------------------------ Find current version of a resource
1743:
1744: sub getversion {
1745: my $fname=&clutter(shift);
1746: unless ($fname=~/^\/res\//) { return -1; }
1747: return ¤tversion(&filelocation('',$fname));
1748: }
1749:
1750: sub currentversion {
1751: my $fname=shift;
1.599 albertel 1752: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1753: if (defined($cached)) { return $result; }
1.292 www 1754: my $author=$fname;
1755: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1756: my ($udom,$uname)=split(/\//,$author);
1757: my $home=homeserver($uname,$udom);
1758: if ($home eq 'no_host') {
1759: return -1;
1760: }
1761: my $answer=reply("currentversion:$fname",$home);
1762: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1763: return -1;
1764: }
1.599 albertel 1765: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1766: }
1767:
1.1 albertel 1768: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1769:
1.1 albertel 1770: sub subscribe {
1771: my $fname=shift;
1.761 raeburn 1772: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1773: $fname=~s/[\n\r]//g;
1.1 albertel 1774: my $author=$fname;
1775: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1776: my ($udom,$uname)=split(/\//,$author);
1777: my $home=homeserver($uname,$udom);
1.335 albertel 1778: if ($home eq 'no_host') {
1779: return 'not_found';
1.1 albertel 1780: }
1781: my $answer=reply("sub:$fname",$home);
1.64 www 1782: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1783: $answer.=' by '.$home;
1784: }
1.1 albertel 1785: return $answer;
1786: }
1787:
1.8 www 1788: # -------------------------------------------------------------- Replicate file
1789:
1790: sub repcopy {
1791: my $filename=shift;
1.23 www 1792: $filename=~s/\/+/\//g;
1.607 raeburn 1793: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1794: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1795: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1796: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1797: return &repcopy_userfile($filename);
1798: }
1.532 albertel 1799: $filename=~s/[\n\r]//g;
1.8 www 1800: my $transname="$filename.in.transfer";
1.828 www 1801: # FIXME: this should flock
1.607 raeburn 1802: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1803: my $remoteurl=subscribe($filename);
1.64 www 1804: if ($remoteurl =~ /^con_lost by/) {
1805: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1806: return 'unavailable';
1.8 www 1807: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1808: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1809: return 'not_found';
1.64 www 1810: } elsif ($remoteurl =~ /^rejected by/) {
1811: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1812: return 'forbidden';
1.20 www 1813: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1814: return 'ok';
1.8 www 1815: } else {
1.290 www 1816: my $author=$filename;
1817: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1818: my ($udom,$uname)=split(/\//,$author);
1819: my $home=homeserver($uname,$udom);
1820: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1821: my @parts=split(/\//,$filename);
1822: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1823: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1824: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1825: return 'bad_request';
1.8 www 1826: }
1827: my $count;
1828: for ($count=5;$count<$#parts;$count++) {
1829: $path.="/$parts[$count]";
1830: if ((-e $path)!=1) {
1831: mkdir($path,0777);
1832: }
1833: }
1834: my $ua=new LWP::UserAgent;
1835: my $request=new HTTP::Request('GET',"$remoteurl");
1836: my $response=$ua->request($request,$transname);
1837: if ($response->is_error()) {
1838: unlink($transname);
1839: my $message=$response->status_line;
1.672 albertel 1840: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1841: ." LWP get: $message: $filename</font>");
1.607 raeburn 1842: return 'unavailable';
1.8 www 1843: } else {
1.16 www 1844: if ($remoteurl!~/\.meta$/) {
1845: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1846: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1847: if ($mresponse->is_error()) {
1848: unlink($filename.'.meta');
1849: &logthis(
1.672 albertel 1850: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1851: }
1852: }
1.8 www 1853: rename($transname,$filename);
1.607 raeburn 1854: return 'ok';
1.8 www 1855: }
1.290 www 1856: }
1.8 www 1857: }
1.330 www 1858: }
1859:
1860: # ------------------------------------------------ Get server side include body
1861: sub ssi_body {
1.381 albertel 1862: my ($filelink,%form)=@_;
1.606 matthew 1863: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1864: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1865: }
1.953 www 1866: my $output='';
1867: my $response;
1.980 raeburn 1868: if ($filelink=~/^https?\:/) {
1.954 raeburn 1869: ($output,$response)=&externalssi($filelink);
1.953 www 1870: } else {
1.1004 droeschl 1871: $filelink .= $filelink=~/\?/ ? '&' : '?';
1872: $filelink .= 'inhibitmenu=yes';
1.953 www 1873: ($output,$response)=&ssi($filelink,%form);
1874: }
1.778 albertel 1875: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1876: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1877: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1878: if (wantarray) {
1879: return ($output, $response);
1880: } else {
1881: return $output;
1882: }
1.8 www 1883: }
1884:
1.15 www 1885: # --------------------------------------------------------- Server Side Include
1886:
1.782 albertel 1887: sub absolute_url {
1888: my ($host_name) = @_;
1889: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1890: if ($host_name eq '') {
1891: $host_name = $ENV{'SERVER_NAME'};
1892: }
1893: return $protocol.$host_name;
1894: }
1895:
1.942 foxr 1896: #
1897: # Server side include.
1898: # Parameters:
1899: # fn Possibly encrypted resource name/id.
1900: # form Hash that describes how the rendering should be done
1901: # and other things.
1.944 foxr 1902: # Returns:
1.950 raeburn 1903: # Scalar context: The content of the response.
1904: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1905: #
1.15 www 1906: sub ssi {
1907:
1.944 foxr 1908: my ($fn,%form)=@_;
1.15 www 1909: my $ua=new LWP::UserAgent;
1.23 www 1910: my $request;
1.711 albertel 1911:
1912: $form{'no_update_last_known'}=1;
1.895 albertel 1913: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1914: if (%form) {
1.782 albertel 1915: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 1916: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 1917: } else {
1.782 albertel 1918: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1919: }
1920:
1.15 www 1921: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1922: my $response=$ua->request($request);
1923:
1.944 foxr 1924: if (wantarray) {
1925: return ($response->content, $response);
1926: } else {
1927: return $response->content;
1.942 foxr 1928: }
1.324 www 1929: }
1930:
1931: sub externalssi {
1932: my ($url)=@_;
1933: my $ua=new LWP::UserAgent;
1934: my $request=new HTTP::Request('GET',$url);
1935: my $response=$ua->request($request);
1.954 raeburn 1936: if (wantarray) {
1937: return ($response->content, $response);
1938: } else {
1939: return $response->content;
1940: }
1.15 www 1941: }
1.254 www 1942:
1.492 albertel 1943: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1944:
1945: sub allowuploaded {
1946: my ($srcurl,$url)=@_;
1947: $url=&clutter(&declutter($url));
1948: my $dir=$url;
1949: $dir=~s/\/[^\/]+$//;
1950: my %httpref=();
1951: my $httpurl=&hreflocation('',$url);
1952: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 1953: &Apache::lonnet::appenv(\%httpref);
1.254 www 1954: }
1.477 raeburn 1955:
1.478 albertel 1956: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1957: # input: action, courseID, current domain, intended
1.637 raeburn 1958: # path to file, source of file, instruction to parse file for objects,
1959: # ref to hash for embedded objects,
1960: # ref to hash for codebase of java objects.
1961: #
1.485 raeburn 1962: # output: url to file (if action was uploaddoc),
1963: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1964: #
1.478 albertel 1965: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1966: # course.
1.477 raeburn 1967: #
1.478 albertel 1968: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1969: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1970: # course's home server.
1.477 raeburn 1971: #
1.478 albertel 1972: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1973: # be copied from $source (current location) to
1974: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1975: # and will then be copied to
1976: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1977: # course's home server.
1.485 raeburn 1978: #
1.481 raeburn 1979: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1980: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1981: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1982: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1983: # in course's home server.
1.637 raeburn 1984: #
1.477 raeburn 1985:
1986: sub process_coursefile {
1.638 albertel 1987: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1988: my $fetchresult;
1.638 albertel 1989: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1990: if ($action eq 'propagate') {
1.638 albertel 1991: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1992: $home);
1.481 raeburn 1993: } else {
1.477 raeburn 1994: my $fpath = '';
1995: my $fname = $file;
1.478 albertel 1996: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1997: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1998: my $filepath = &build_filepath($fpath);
1.481 raeburn 1999: if ($action eq 'copy') {
2000: if ($source eq '') {
2001: $fetchresult = 'no source file';
2002: return $fetchresult;
2003: } else {
2004: my $destination = $filepath.'/'.$fname;
2005: rename($source,$destination);
2006: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2007: $home);
1.481 raeburn 2008: }
2009: } elsif ($action eq 'uploaddoc') {
2010: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2011: print $fh $env{'form.'.$source};
1.481 raeburn 2012: close($fh);
1.637 raeburn 2013: if ($parser eq 'parse') {
1.961 raeburn 2014: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637 raeburn 2015: unless ($parse_result eq 'ok') {
2016: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2017: }
2018: }
1.477 raeburn 2019: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2020: $home);
1.481 raeburn 2021: if ($fetchresult eq 'ok') {
2022: return '/uploaded/'.$fpath.'/'.$fname;
2023: } else {
2024: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2025: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2026: return '/adm/notfound.html';
2027: }
1.477 raeburn 2028: }
2029: }
1.485 raeburn 2030: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2031: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2032: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2033: }
2034: return $fetchresult;
2035: }
2036:
1.637 raeburn 2037: sub build_filepath {
2038: my ($fpath) = @_;
2039: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2040: unless ($fpath eq '') {
2041: my @parts=split('/',$fpath);
2042: foreach my $part (@parts) {
2043: $filepath.= '/'.$part;
2044: if ((-e $filepath)!=1) {
2045: mkdir($filepath,0777);
2046: }
2047: }
2048: }
2049: return $filepath;
2050: }
2051:
2052: sub store_edited_file {
1.638 albertel 2053: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2054: my $file = $primary_url;
2055: $file =~ s#^/uploaded/$docudom/$docuname/##;
2056: my $fpath = '';
2057: my $fname = $file;
2058: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2059: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2060: my $filepath = &build_filepath($fpath);
2061: open(my $fh,'>'.$filepath.'/'.$fname);
2062: print $fh $content;
2063: close($fh);
1.638 albertel 2064: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2065: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2066: $home);
1.637 raeburn 2067: if ($$fetchresult eq 'ok') {
2068: return '/uploaded/'.$fpath.'/'.$fname;
2069: } else {
1.638 albertel 2070: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2071: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2072: return '/adm/notfound.html';
2073: }
2074: }
2075:
1.531 albertel 2076: sub clean_filename {
1.831 albertel 2077: my ($fname,$args)=@_;
1.315 www 2078: # Replace Windows backslashes by forward slashes
1.257 www 2079: $fname=~s/\\/\//g;
1.831 albertel 2080: if (!$args->{'keep_path'}) {
2081: # Get rid of everything but the actual filename
2082: $fname=~s/^.*\/([^\/]+)$/$1/;
2083: }
1.315 www 2084: # Replace spaces by underscores
2085: $fname=~s/\s+/\_/g;
2086: # Replace all other weird characters by nothing
1.831 albertel 2087: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2088: # Replace all .\d. sequences with _\d. so they no longer look like version
2089: # numbers
2090: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2091: return $fname;
2092: }
1.984 neumanie 2093: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
2094: sub resizeImage {
2095: my($img_url) = @_;
2096: my $ima = Image::Magick->new;
2097: $ima->Read($img_url);
2098: if($ima->Get('width') > 400)
2099: {
2100: my $factor = $ima->Get('width')/400;
2101: $ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
2102: }
2103: if($ima->Get('height') > 500)
2104: {
2105: my $factor = $ima->Get('height')/500;
2106: $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
2107: }
2108:
2109: $ima->Write($img_url);
2110: }
1.531 albertel 2111:
1.977 amueller 2112: #Wrapper function for userphotoupload
2113: sub userphotoupload
2114: {
2115: my($formname,$subdir) = @_;
2116: $upload_photo_form = 1;
2117: return &userfileupload($formname,undef,$subdir);
2118: }
2119:
1.608 albertel 2120: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2121: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2122: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2123: # $coursedoc - if true up to the current course
2124: # if false
2125: # $subdir - directory in userfile to store the file into
1.858 raeburn 2126: # $parser - instruction to parse file for objects ($parser = parse)
2127: # $allfiles - reference to hash for embedded objects
2128: # $codebase - reference to hash for codebase of java objects
2129: # $desuname - username for permanent storage of uploaded file
2130: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2131: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2132: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 2133: #
1.686 albertel 2134: # output: url of file in userspace, or error: <message>
2135: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2136:
2137:
1.531 albertel 2138: sub userfileupload {
1.860 raeburn 2139: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2140: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 2141: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2142: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2143: $fname=&clean_filename($fname);
1.315 www 2144: # See if there is anything left
1.257 www 2145: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2146: chop($env{'form.'.$formname});
1.523 raeburn 2147: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2148: my $now = time;
2149: my $filepath = 'tmp/helprequests/'.$now;
2150: my @parts=split(/\//,$filepath);
2151: my $fullpath = $perlvar{'lonDaemons'};
2152: for (my $i=0;$i<@parts;$i++) {
2153: $fullpath .= '/'.$parts[$i];
2154: if ((-e $fullpath)!=1) {
2155: mkdir($fullpath,0777);
2156: }
2157: }
2158: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2159: print $fh $env{'form.'.$formname};
1.523 raeburn 2160: close($fh);
1.741 raeburn 2161: return $fullpath.'/'.$fname;
2162: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2163: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2164: '_'.$env{'user.domain'}.'/pending';
2165: my @parts=split(/\//,$filepath);
2166: my $fullpath = $perlvar{'lonDaemons'};
2167: for (my $i=0;$i<@parts;$i++) {
2168: $fullpath .= '/'.$parts[$i];
2169: if ((-e $fullpath)!=1) {
2170: mkdir($fullpath,0777);
2171: }
2172: }
2173: open(my $fh,'>'.$fullpath.'/'.$fname);
2174: print $fh $env{'form.'.$formname};
2175: close($fh);
2176: return $fullpath.'/'.$fname;
1.523 raeburn 2177: }
1.995 raeburn 2178: if ($subdir eq 'scantron') {
2179: $fname = 'scantron_orig_'.$fname;
2180: } else {
1.258 www 2181: # Create the directory if not present
1.995 raeburn 2182: $fname="$subdir/$fname";
2183: }
1.259 www 2184: if ($coursedoc) {
1.638 albertel 2185: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2186: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2187: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2188: return &finishuserfileupload($docuname,$docudom,
2189: $formname,$fname,$parser,$allfiles,
1.860 raeburn 2190: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 2191: } else {
1.620 albertel 2192: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2193: return &process_coursefile('uploaddoc',$docuname,$docudom,
2194: $fname,$formname,$parser,
2195: $allfiles,$codebase);
1.481 raeburn 2196: }
1.719 banghart 2197: } elsif (defined($destuname)) {
2198: my $docuname=$destuname;
2199: my $docudom=$destudom;
1.860 raeburn 2200: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2201: $parser,$allfiles,$codebase,
2202: $thumbwidth,$thumbheight);
1.719 banghart 2203:
1.259 www 2204: } else {
1.638 albertel 2205: my $docuname=$env{'user.name'};
2206: my $docudom=$env{'user.domain'};
1.714 raeburn 2207: if (exists($env{'form.group'})) {
2208: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2209: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2210: }
1.860 raeburn 2211: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2212: $parser,$allfiles,$codebase,
2213: $thumbwidth,$thumbheight);
1.259 www 2214: }
1.271 www 2215: }
2216:
2217: sub finishuserfileupload {
1.860 raeburn 2218: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2219: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 2220: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2221: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2222:
1.860 raeburn 2223: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2224: $file=$fname;
2225: if ($fname=~m|/|) {
2226: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2227: $path.=$fnamepath.'/';
2228: }
1.259 www 2229: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2230: my $count;
2231: for ($count=4;$count<=$#parts;$count++) {
2232: $filepath.="/$parts[$count]";
2233: if ((-e $filepath)!=1) {
2234: mkdir($filepath,0777);
2235: }
2236: }
1.984 neumanie 2237:
1.258 www 2238: # Save the file
2239: {
1.701 albertel 2240: if (!open(FH,'>'.$filepath.'/'.$file)) {
2241: &logthis('Failed to create '.$filepath.'/'.$file);
2242: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2243: return '/adm/notfound.html';
2244: }
2245: if (!print FH ($env{'form.'.$formname})) {
2246: &logthis('Failed to write to '.$filepath.'/'.$file);
2247: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2248: return '/adm/notfound.html';
2249: }
1.570 albertel 2250: close(FH);
1.977 amueller 2251: if($upload_photo_form==1)
2252: {
1.984 neumanie 2253: resizeImage($filepath.'/'.$file);
1.977 amueller 2254: $upload_photo_form = 0;
2255: }
1.258 www 2256: }
1.637 raeburn 2257: if ($parser eq 'parse') {
1.961 raeburn 2258: my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638 albertel 2259: $codebase);
1.637 raeburn 2260: unless ($parse_result eq 'ok') {
1.638 albertel 2261: &logthis('Failed to parse '.$filepath.$file.
2262: ' for embedded media: '.$parse_result);
1.637 raeburn 2263: }
2264: }
1.860 raeburn 2265: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2266: my $input = $filepath.'/'.$file;
2267: my $output = $filepath.'/'.'tn-'.$file;
2268: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2269: system("convert -sample $thumbsize $input $output");
2270: if (-e $filepath.'/'.'tn-'.$file) {
2271: $fetchthumb = 1;
2272: }
2273: }
1.858 raeburn 2274:
1.259 www 2275: # Notify homeserver to grep it
2276: #
1.984 neumanie 2277: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2278: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2279: if ($fetchresult eq 'ok') {
1.860 raeburn 2280: if ($fetchthumb) {
2281: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2282: if ($thumbresult ne 'ok') {
2283: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2284: $docuhome.': '.$thumbresult);
2285: }
2286: }
1.259 www 2287: #
1.258 www 2288: # Return the URL to it
1.494 albertel 2289: return '/uploaded/'.$path.$file;
1.263 www 2290: } else {
1.494 albertel 2291: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2292: ': '.$fetchresult);
1.263 www 2293: return '/adm/notfound.html';
1.858 raeburn 2294: }
1.493 albertel 2295: }
2296:
1.637 raeburn 2297: sub extract_embedded_items {
1.961 raeburn 2298: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2299: my @state = ();
2300: my %javafiles = (
2301: codebase => '',
2302: code => '',
2303: archive => ''
2304: );
2305: my %mediafiles = (
2306: src => '',
2307: movie => '',
2308: );
1.648 raeburn 2309: my $p;
2310: if ($content) {
2311: $p = HTML::LCParser->new($content);
2312: } else {
1.961 raeburn 2313: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2314: }
1.641 albertel 2315: while (my $t=$p->get_token()) {
1.640 albertel 2316: if ($t->[0] eq 'S') {
2317: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2318: push(@state, $tagname);
1.648 raeburn 2319: if (lc($tagname) eq 'allow') {
2320: &add_filetype($allfiles,$attr->{'src'},'src');
2321: }
1.640 albertel 2322: if (lc($tagname) eq 'img') {
2323: &add_filetype($allfiles,$attr->{'src'},'src');
2324: }
1.886 albertel 2325: if (lc($tagname) eq 'a') {
2326: &add_filetype($allfiles,$attr->{'href'},'href');
2327: }
1.645 raeburn 2328: if (lc($tagname) eq 'script') {
2329: if ($attr->{'archive'} =~ /\.jar$/i) {
2330: &add_filetype($allfiles,$attr->{'archive'},'archive');
2331: } else {
2332: &add_filetype($allfiles,$attr->{'src'},'src');
2333: }
2334: }
2335: if (lc($tagname) eq 'link') {
2336: if (lc($attr->{'rel'}) eq 'stylesheet') {
2337: &add_filetype($allfiles,$attr->{'href'},'href');
2338: }
2339: }
1.640 albertel 2340: if (lc($tagname) eq 'object' ||
2341: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2342: foreach my $item (keys(%javafiles)) {
2343: $javafiles{$item} = '';
2344: }
2345: }
2346: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2347: my $name = lc($attr->{'name'});
2348: foreach my $item (keys(%javafiles)) {
2349: if ($name eq $item) {
2350: $javafiles{$item} = $attr->{'value'};
2351: last;
2352: }
2353: }
2354: foreach my $item (keys(%mediafiles)) {
2355: if ($name eq $item) {
2356: &add_filetype($allfiles, $attr->{'value'}, 'value');
2357: last;
2358: }
2359: }
2360: }
2361: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2362: foreach my $item (keys(%javafiles)) {
2363: if ($attr->{$item}) {
2364: $javafiles{$item} = $attr->{$item};
2365: last;
2366: }
2367: }
2368: foreach my $item (keys(%mediafiles)) {
2369: if ($attr->{$item}) {
2370: &add_filetype($allfiles,$attr->{$item},$item);
2371: last;
2372: }
2373: }
2374: }
2375: } elsif ($t->[0] eq 'E') {
2376: my ($tagname) = ($t->[1]);
2377: if ($javafiles{'codebase'} ne '') {
2378: $javafiles{'codebase'} .= '/';
2379: }
2380: if (lc($tagname) eq 'applet' ||
2381: lc($tagname) eq 'object' ||
2382: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2383: ) {
2384: foreach my $item (keys(%javafiles)) {
2385: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2386: my $file=$javafiles{'codebase'}.$javafiles{$item};
2387: &add_filetype($allfiles,$file,$item);
2388: }
2389: }
2390: }
2391: pop @state;
2392: }
2393: }
1.637 raeburn 2394: return 'ok';
2395: }
2396:
1.639 albertel 2397: sub add_filetype {
2398: my ($allfiles,$file,$type)=@_;
2399: if (exists($allfiles->{$file})) {
2400: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2401: push(@{$allfiles->{$file}}, &escape($type));
2402: }
2403: } else {
2404: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2405: }
2406: }
2407:
1.493 albertel 2408: sub removeuploadedurl {
1.984 neumanie 2409: my ($url)=@_;
2410: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2411: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2412: }
2413:
2414: sub removeuserfile {
2415: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2416: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2417: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2418: if ($result eq 'ok') {
1.798 raeburn 2419: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2420: my $metafile = $fname.'.meta';
2421: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2422: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2423: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2424: my $sqlresult =
1.823 albertel 2425: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2426: 'portfolio_metadata',$group,
2427: 'delete');
1.798 raeburn 2428: }
2429: }
2430: return $result;
1.257 www 2431: }
1.15 www 2432:
1.530 albertel 2433: sub mkdiruserfile {
2434: my ($docuname,$docudom,$dir)=@_;
2435: my $home=&homeserver($docuname,$docudom);
2436: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2437: }
2438:
1.531 albertel 2439: sub renameuserfile {
2440: my ($docuname,$docudom,$old,$new)=@_;
2441: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2442: my $result = &reply("renameuserfile:$docudom:$docuname:".
2443: &escape("$old").':'.&escape("$new"),$home);
2444: if ($result eq 'ok') {
2445: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2446: my $oldmeta = $old.'.meta';
2447: my $newmeta = $new.'.meta';
2448: my $metaresult =
2449: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2450: my $url = "/uploaded/$docudom/$docuname/$old";
2451: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2452: my $sqlresult =
1.823 albertel 2453: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2454: 'portfolio_metadata',$group,
2455: 'delete');
1.798 raeburn 2456: }
2457: }
2458: return $result;
1.531 albertel 2459: }
2460:
1.14 www 2461: # ------------------------------------------------------------------------- Log
2462:
2463: sub log {
2464: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2465: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2466: }
2467:
2468: # ------------------------------------------------------------------ Course Log
1.352 www 2469: #
2470: # This routine flushes several buffers of non-mission-critical nature
2471: #
1.157 www 2472:
2473: sub flushcourselogs {
1.352 www 2474: &logthis('Flushing log buffers');
2475: #
2476: # course logs
2477: # This is a log of all transactions in a course, which can be used
2478: # for data mining purposes
2479: #
2480: # It also collects the courseid database, which lists last transaction
2481: # times and course titles for all courseids
2482: #
2483: my %courseidbuffer=();
1.921 raeburn 2484: foreach my $crsid (keys(%courselogs)) {
1.352 www 2485: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2486: &escape($courselogs{$crsid}),
2487: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2488: delete $courselogs{$crsid};
2489: } else {
2490: &logthis('Failed to flush log buffer for '.$crsid);
2491: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2492: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2493: " exceeded maximum size, deleting.</font>");
2494: delete $courselogs{$crsid};
2495: }
1.352 www 2496: }
1.920 raeburn 2497: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2498: 'description' => $coursedescrbuf{$crsid},
2499: 'inst_code' => $courseinstcodebuf{$crsid},
2500: 'type' => $coursetypebuf{$crsid},
2501: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2502: };
1.191 harris41 2503: }
1.352 www 2504: #
2505: # Write course id database (reverse lookup) to homeserver of courses
2506: # Is used in pickcourse
2507: #
1.840 albertel 2508: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2509: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2510: $courseidbuffer{$crs_home},
2511: $crs_home,'timeonly');
1.352 www 2512: }
2513: #
2514: # File accesses
2515: # Writes to the dynamic metadata of resources to get hit counts, etc.
2516: #
1.449 matthew 2517: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2518: if ($entry =~ /___count$/) {
2519: my ($dom,$name);
1.807 albertel 2520: ($dom,$name,undef)=
1.811 albertel 2521: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2522: if (! defined($dom) || $dom eq '' ||
2523: ! defined($name) || $name eq '') {
1.620 albertel 2524: my $cid = $env{'request.course.id'};
2525: $dom = $env{'request.'.$cid.'.domain'};
2526: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2527: }
1.450 matthew 2528: my $value = $accesshash{$entry};
2529: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2530: my %temphash=($url => $value);
1.449 matthew 2531: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2532: if ($result eq 'ok') {
2533: delete $accesshash{$entry};
2534: } elsif ($result eq 'unknown_cmd') {
2535: # Target server has old code running on it.
1.450 matthew 2536: my %temphash=($entry => $value);
1.449 matthew 2537: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2538: delete $accesshash{$entry};
2539: }
2540: }
2541: } else {
1.811 albertel 2542: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2543: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2544: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2545: delete $accesshash{$entry};
2546: }
1.185 www 2547: }
1.191 harris41 2548: }
1.352 www 2549: #
2550: # Roles
2551: # Reverse lookup of user roles for course faculty/staff and co-authorship
2552: #
1.800 albertel 2553: foreach my $entry (keys(%userrolehash)) {
1.351 www 2554: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2555: split(/\:/,$entry);
2556: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2557: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2558: $rudom,$runame) eq 'ok') {
2559: delete $userrolehash{$entry};
2560: }
2561: }
1.662 raeburn 2562: #
2563: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2564: #
2565: my %domrolebuffer = ();
1.1000 raeburn 2566: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2567: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2568: if ($domrolebuffer{$rudom}) {
2569: $domrolebuffer{$rudom}.='&'.&escape($entry).
2570: '='.&escape($domainrolehash{$entry});
2571: } else {
2572: $domrolebuffer{$rudom}.=&escape($entry).
2573: '='.&escape($domainrolehash{$entry});
2574: }
2575: delete $domainrolehash{$entry};
2576: }
2577: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2578: my %servers = &get_servers($dom,'library');
2579: foreach my $tryserver (keys(%servers)) {
2580: unless (&reply('domroleput:'.$dom.':'.
2581: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2582: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2583: }
1.662 raeburn 2584: }
2585: }
1.186 www 2586: $dumpcount++;
1.157 www 2587: }
2588:
2589: sub courselog {
2590: my $what=shift;
1.158 www 2591: $what=time.':'.$what;
1.620 albertel 2592: unless ($env{'request.course.id'}) { return ''; }
2593: $coursedombuf{$env{'request.course.id'}}=
2594: $env{'course.'.$env{'request.course.id'}.'.domain'};
2595: $coursenumbuf{$env{'request.course.id'}}=
2596: $env{'course.'.$env{'request.course.id'}.'.num'};
2597: $coursehombuf{$env{'request.course.id'}}=
2598: $env{'course.'.$env{'request.course.id'}.'.home'};
2599: $coursedescrbuf{$env{'request.course.id'}}=
2600: $env{'course.'.$env{'request.course.id'}.'.description'};
2601: $courseinstcodebuf{$env{'request.course.id'}}=
2602: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2603: $courseownerbuf{$env{'request.course.id'}}=
2604: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2605: $coursetypebuf{$env{'request.course.id'}}=
2606: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2607: if (defined $courselogs{$env{'request.course.id'}}) {
2608: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2609: } else {
1.620 albertel 2610: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2611: }
1.620 albertel 2612: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2613: &flushcourselogs();
2614: }
1.158 www 2615: }
2616:
2617: sub courseacclog {
2618: my $fnsymb=shift;
1.620 albertel 2619: unless ($env{'request.course.id'}) { return ''; }
2620: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2621: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2622: $what.=':POST';
1.583 matthew 2623: # FIXME: Probably ought to escape things....
1.800 albertel 2624: foreach my $key (keys(%env)) {
2625: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2626: my $formitem = $1;
2627: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2628: $what.=':'.$formitem.'='.$env{$key};
2629: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2630: $what.=':'.$formitem.'='.$env{$key};
2631: }
1.158 www 2632: }
1.191 harris41 2633: }
1.583 matthew 2634: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2635: # FIXME: We should not be depending on a form parameter that someone
2636: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2637: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2638: $what.= ':POST';
2639: # FIXME: Probably ought to escape things....
2640: foreach my $element ('courseexp','crsfulltext','crsrelated',
2641: 'crsdiscuss') {
1.620 albertel 2642: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2643: }
2644: }
1.158 www 2645: }
2646: &courselog($what);
1.149 www 2647: }
2648:
1.185 www 2649: sub countacc {
2650: my $url=&declutter(shift);
1.458 matthew 2651: return if (! defined($url) || $url eq '');
1.620 albertel 2652: unless ($env{'request.course.id'}) { return ''; }
2653: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2654: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2655: $accesshash{$key}++;
1.185 www 2656: }
1.349 www 2657:
1.361 www 2658: sub linklog {
2659: my ($from,$to)=@_;
2660: $from=&declutter($from);
2661: $to=&declutter($to);
2662: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2663: $accesshash{$to.'___'.$from.'___goto'}=1;
2664: }
2665:
1.349 www 2666: sub userrolelog {
2667: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2668: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2669: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2670: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2671: ($trole=~/^ta/)) {
1.350 www 2672: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2673: $userrolehash
2674: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2675: =$tend.':'.$tstart;
1.662 raeburn 2676: }
1.898 albertel 2677: if (($env{'request.role'} =~ /dc\./) &&
2678: (($trole=~/^au/) || ($trole=~/^in/) ||
2679: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2680: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2681: $userrolehash
2682: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2683: =$tend.':'.$tstart;
2684: }
1.662 raeburn 2685: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2686: ($trole=~/^li/) || ($trole=~/^li/) ||
2687: ($trole=~/^au/) || ($trole=~/^dg/) ||
2688: ($trole=~/^sc/)) {
2689: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2690: $domainrolehash
2691: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2692: = $tend.':'.$tstart;
2693: }
1.351 www 2694: }
2695:
1.957 raeburn 2696: sub courserolelog {
2697: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2698: if (($trole eq 'cc') || ($trole eq 'in') ||
2699: ($trole eq 'ep') || ($trole eq 'ad') ||
2700: ($trole eq 'ta') || ($trole eq 'st') ||
2701: ($trole=~/^cr/) || ($trole eq 'gr')) {
2702: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2703: my $cdom = $1;
2704: my $cnum = $2;
2705: my $sec = $3;
2706: my $namespace = 'rolelog';
2707: my %storehash = (
2708: role => $trole,
2709: start => $tstart,
2710: end => $tend,
2711: selfenroll => $selfenroll,
2712: context => $context,
2713: );
2714: if ($trole eq 'gr') {
2715: $namespace = 'groupslog';
2716: $storehash{'group'} = $sec;
2717: } else {
2718: $storehash{'section'} = $sec;
2719: }
2720: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2721: if (($trole ne 'st') || ($sec ne '')) {
2722: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2723: }
1.957 raeburn 2724: }
2725: }
2726: return;
2727: }
2728:
1.351 www 2729: sub get_course_adv_roles {
1.948 raeburn 2730: my ($cid,$codes) = @_;
1.620 albertel 2731: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2732: my %coursehash=&coursedescription($cid);
1.988 raeburn 2733: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2734: my %nothide=();
1.800 albertel 2735: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2736: if ($user !~ /:/) {
2737: $nothide{join(':',split(/[\@]/,$user))}=1;
2738: } else {
2739: $nothide{$user}=1;
2740: }
1.470 www 2741: }
1.351 www 2742: my %returnhash=();
2743: my %dumphash=
2744: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2745: my $now=time;
1.997 raeburn 2746: my %privileged;
1.1000 raeburn 2747: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2748: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2749: if (($tstart) && ($tstart<0)) { next; }
2750: if (($tend) && ($tend<$now)) { next; }
2751: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2752: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2753: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2754: unless (ref($privileged{$domain}) eq 'HASH') {
2755: my %dompersonnel =
1.998 raeburn 2756: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2757: $privileged{$domain} = {};
2758: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2759: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2760: foreach my $user (keys(%{$dompersonnel{$server}})) {
2761: my ($trole,$uname,$udom) = split(/:/,$user);
2762: $privileged{$udom}{$uname} = 1;
2763: }
2764: }
2765: }
2766: }
2767: if ((exists($privileged{$domain}{$username})) &&
2768: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2769: if ($role eq 'cr') { next; }
1.948 raeburn 2770: if ($codes) {
2771: if ($section) { $role .= ':'.$section; }
2772: if ($returnhash{$role}) {
2773: $returnhash{$role}.=','.$username.':'.$domain;
2774: } else {
2775: $returnhash{$role}=$username.':'.$domain;
2776: }
1.351 www 2777: } else {
1.988 raeburn 2778: my $key=&plaintext($role,$crstype);
1.973 bisitz 2779: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2780: if ($returnhash{$key}) {
2781: $returnhash{$key}.=','.$username.':'.$domain;
2782: } else {
2783: $returnhash{$key}=$username.':'.$domain;
2784: }
1.351 www 2785: }
1.948 raeburn 2786: }
1.400 www 2787: return %returnhash;
2788: }
2789:
2790: sub get_my_roles {
1.937 raeburn 2791: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2792: unless (defined($uname)) { $uname=$env{'user.name'}; }
2793: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2794: my (%dumphash,%nothide);
1.858 raeburn 2795: if ($context eq 'userroles') {
2796: %dumphash = &dump('roles',$udom,$uname);
2797: } else {
2798: %dumphash=
1.400 www 2799: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2800: if ($hidepriv) {
2801: my %coursehash=&coursedescription($udom.'_'.$uname);
2802: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2803: if ($user !~ /:/) {
2804: $nothide{join(':',split(/[\@]/,$user))} = 1;
2805: } else {
2806: $nothide{$user} = 1;
2807: }
2808: }
2809: }
1.858 raeburn 2810: }
1.400 www 2811: my %returnhash=();
2812: my $now=time;
1.999 raeburn 2813: my %privileged;
1.800 albertel 2814: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2815: my ($role,$tend,$tstart);
2816: if ($context eq 'userroles') {
2817: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2818: } else {
2819: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2820: }
1.400 www 2821: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2822: my $status = 'active';
1.939 raeburn 2823: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2824: $status = 'previous';
2825: }
2826: if (($tstart) && ($now<$tstart)) {
2827: $status = 'future';
2828: }
2829: if (ref($types) eq 'ARRAY') {
2830: if (!grep(/^\Q$status\E$/,@{$types})) {
2831: next;
2832: }
2833: } else {
2834: if ($status ne 'active') {
2835: next;
2836: }
2837: }
1.867 raeburn 2838: my ($rolecode,$username,$domain,$section,$area);
2839: if ($context eq 'userroles') {
2840: ($area,$rolecode) = split(/_/,$entry);
2841: (undef,$domain,$username,$section) = split(/\//,$area);
2842: } else {
2843: ($role,$username,$domain,$section) = split(/\:/,$entry);
2844: }
1.832 raeburn 2845: if (ref($roledoms) eq 'ARRAY') {
2846: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2847: next;
2848: }
2849: }
2850: if (ref($roles) eq 'ARRAY') {
2851: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2852: if ($role =~ /^cr\//) {
2853: if (!grep(/^cr$/,@{$roles})) {
2854: next;
2855: }
2856: } else {
2857: next;
2858: }
1.832 raeburn 2859: }
1.867 raeburn 2860: }
1.937 raeburn 2861: if ($hidepriv) {
1.999 raeburn 2862: if ($context eq 'userroles') {
2863: if ((&privileged($username,$domain)) &&
2864: (!$nothide{$username.':'.$domain})) {
2865: next;
2866: }
2867: } else {
2868: unless (ref($privileged{$domain}) eq 'HASH') {
2869: my %dompersonnel =
2870: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2871: $privileged{$domain} = {};
2872: if (keys(%dompersonnel)) {
2873: foreach my $server (keys(%dompersonnel)) {
2874: if (ref($dompersonnel{$server}) eq 'HASH') {
2875: foreach my $user (keys(%{$dompersonnel{$server}})) {
2876: my ($trole,$uname,$udom) = split(/:/,$user);
2877: $privileged{$udom}{$uname} = $trole;
2878: }
2879: }
2880: }
2881: }
2882: }
2883: if (exists($privileged{$domain}{$username})) {
2884: if (!$nothide{$username.':'.$domain}) {
2885: next;
2886: }
2887: }
1.937 raeburn 2888: }
2889: }
1.933 raeburn 2890: if ($withsec) {
2891: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2892: $tstart.':'.$tend;
2893: } else {
2894: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2895: }
1.832 raeburn 2896: }
1.373 www 2897: return %returnhash;
1.399 www 2898: }
2899:
2900: # ----------------------------------------------------- Frontpage Announcements
2901: #
2902: #
2903:
2904: sub postannounce {
2905: my ($server,$text)=@_;
1.844 albertel 2906: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2907: unless ($text=~/\w/) { $text=''; }
2908: return &reply('setannounce:'.&escape($text),$server);
2909: }
2910:
2911: sub getannounce {
1.448 albertel 2912:
2913: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2914: my $announcement='';
1.800 albertel 2915: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2916: close($fh);
1.399 www 2917: if ($announcement=~/\w/) {
2918: return
2919: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2920: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2921: } else {
2922: return '';
2923: }
2924: } else {
2925: return '';
2926: }
1.351 www 2927: }
1.353 www 2928:
2929: # ---------------------------------------------------------- Course ID routines
2930: # Deal with domain's nohist_courseid.db files
2931: #
2932:
2933: sub courseidput {
1.921 raeburn 2934: my ($domain,$storehash,$coursehome,$caller) = @_;
2935: my $outcome;
2936: if ($caller eq 'timeonly') {
2937: my $cids = '';
2938: foreach my $item (keys(%$storehash)) {
2939: $cids.=&escape($item).'&';
2940: }
2941: $cids=~s/\&$//;
2942: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2943: $coursehome);
2944: } else {
2945: my $items = '';
2946: foreach my $item (keys(%$storehash)) {
2947: $items.= &escape($item).'='.
2948: &freeze_escape($$storehash{$item}).'&';
2949: }
2950: $items=~s/\&$//;
2951: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2952: $coursehome);
1.918 raeburn 2953: }
2954: if ($outcome eq 'unknown_cmd') {
2955: my $what;
2956: foreach my $cid (keys(%$storehash)) {
2957: $what .= &escape($cid).'=';
1.921 raeburn 2958: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 2959: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 2960: }
2961: $what =~ s/\:$/&/;
2962: }
2963: $what =~ s/\&$//;
2964: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2965: } else {
2966: return $outcome;
2967: }
1.353 www 2968: }
2969:
2970: sub courseiddump {
1.921 raeburn 2971: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 2972: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1008 raeburn 2973: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,$cloneonly)=@_;
1.918 raeburn 2974: my $as_hash = 1;
2975: my %returnhash;
2976: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2977: my %libserv = &all_library();
2978: foreach my $tryserver (keys(%libserv)) {
2979: if ( ( $hostidflag == 1
2980: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2981: || (!defined($hostidflag)) ) {
2982:
1.918 raeburn 2983: if (($domfilter eq '') ||
2984: (&host_domain($tryserver) eq $domfilter)) {
2985: my $rep =
2986: &reply('courseiddump:'.&host_domain($tryserver).':'.
2987: $sincefilter.':'.&escape($descfilter).':'.
2988: &escape($instcodefilter).':'.&escape($ownerfilter).
2989: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 2990: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 2991: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 2992: $showhidden.':'.$caller.':'.&escape($cloner).':'.
2993: &escape($cc_clone).':'.$cloneonly,$tryserver);
1.918 raeburn 2994: my @pairs=split(/\&/,$rep);
2995: foreach my $item (@pairs) {
2996: my ($key,$value)=split(/\=/,$item,2);
2997: $key = &unescape($key);
2998: next if ($key =~ /^error: 2 /);
2999: my $result = &thaw_unescape($value);
3000: if (ref($result) eq 'HASH') {
3001: $returnhash{$key}=$result;
3002: } else {
1.921 raeburn 3003: my @responses = split(/:/,$value);
3004: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3005: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3006: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3007: }
1.1008 raeburn 3008: }
1.353 www 3009: }
3010: }
3011: }
3012: }
3013: return %returnhash;
3014: }
3015:
1.658 raeburn 3016: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3017:
3018: sub dcmailput {
1.685 raeburn 3019: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3020: my $status = &Apache::lonnet::critical(
1.740 www 3021: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3022: &escape($message),$server);
1.662 raeburn 3023: return $status;
3024: }
3025:
1.658 raeburn 3026: sub dcmaildump {
3027: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3028: my %returnhash=();
1.846 albertel 3029:
3030: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3031: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3032: &escape($enddate).':';
3033: my @esc_senders=map { &escape($_)} @$senders;
3034: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3035: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3036: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3037: if (($key) && ($value)) {
3038: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3039: }
3040: }
3041: }
3042: return %returnhash;
3043: }
1.662 raeburn 3044: # ---------------------------------------------------------- Domain roles
3045:
3046: sub get_domain_roles {
3047: my ($dom,$roles,$startdate,$enddate)=@_;
3048: if (undef($startdate) || $startdate eq '') {
3049: $startdate = '.';
3050: }
3051: if (undef($enddate) || $enddate eq '') {
3052: $enddate = '.';
3053: }
1.922 raeburn 3054: my $rolelist;
3055: if (ref($roles) eq 'ARRAY') {
3056: $rolelist = join(':',@{$roles});
3057: }
1.662 raeburn 3058: my %personnel = ();
1.841 albertel 3059:
3060: my %servers = &get_servers($dom,'library');
3061: foreach my $tryserver (keys(%servers)) {
3062: %{$personnel{$tryserver}}=();
3063: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3064: &escape($startdate).':'.
3065: &escape($enddate).':'.
3066: &escape($rolelist), $tryserver))) {
3067: my ($key,$value) = split(/\=/,$line,2);
3068: if (($key) && ($value)) {
3069: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3070: }
3071: }
1.662 raeburn 3072: }
3073: return %personnel;
3074: }
1.658 raeburn 3075:
1.149 www 3076: # ----------------------------------------------------------- Check out an item
3077:
1.504 albertel 3078: sub get_first_access {
3079: my ($type,$argsymb)=@_;
1.790 albertel 3080: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3081: if ($argsymb) { $symb=$argsymb; }
3082: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3083: if ($type eq 'course') {
3084: $res='course';
3085: } elsif ($type eq 'map') {
1.588 albertel 3086: $res=&symbread($map);
3087: } else {
3088: $res=$symb;
3089: }
3090: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3091: return $times{"$courseid\0$res"};
1.504 albertel 3092: }
3093:
3094: sub set_first_access {
3095: my ($type)=@_;
1.790 albertel 3096: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3097: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3098: if ($type eq 'course') {
3099: $res='course';
3100: } elsif ($type eq 'map') {
1.588 albertel 3101: $res=&symbread($map);
3102: } else {
3103: $res=$symb;
3104: }
3105: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3106: if (!$firstaccess) {
1.588 albertel 3107: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3108: }
3109: return 'already_set';
1.504 albertel 3110: }
3111:
1.149 www 3112: sub checkout {
3113: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3114: my $now=time;
3115: my $lonhost=$perlvar{'lonHostID'};
3116: my $infostr=&escape(
1.234 www 3117: 'CHECKOUTTOKEN&'.
1.149 www 3118: $tuname.'&'.
3119: $tudom.'&'.
3120: $tcrsid.'&'.
3121: $symb.'&'.
3122: $now.'&'.$ENV{'REMOTE_ADDR'});
3123: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3124: if ($token=~/^error\:/) {
1.672 albertel 3125: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3126: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3127: "</font>");
3128: return '';
3129: }
3130:
1.149 www 3131: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3132: $token=~tr/a-z/A-Z/;
3133:
1.153 www 3134: my %infohash=('resource.0.outtoken' => $token,
3135: 'resource.0.checkouttime' => $now,
3136: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3137:
3138: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3139: return '';
1.151 www 3140: } else {
1.672 albertel 3141: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3142: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3143: "</font>");
1.149 www 3144: }
3145:
3146: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3147: &escape('Checkout '.$infostr.' - '.
3148: $token)) ne 'ok') {
3149: return '';
1.151 www 3150: } else {
1.672 albertel 3151: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3152: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3153: "</font>");
1.149 www 3154: }
1.151 www 3155: return $token;
1.149 www 3156: }
3157:
3158: # ------------------------------------------------------------ Check in an item
3159:
3160: sub checkin {
3161: my $token=shift;
1.150 www 3162: my $now=time;
3163: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3164: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3165: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3166: $dtoken=~s/\W/\_/g;
1.234 www 3167: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3168: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3169:
1.154 www 3170: unless (($tuname) && ($tudom)) {
3171: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3172: return '';
3173: }
3174:
3175: unless (&allowed('mgr',$tcrsid)) {
3176: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3177: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3178: return '';
3179: }
3180:
1.153 www 3181: my %infohash=('resource.0.intoken' => $token,
3182: 'resource.0.checkintime' => $now,
3183: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3184:
3185: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3186: return '';
3187: }
3188:
3189: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3190: &escape('Checkin - '.$token)) ne 'ok') {
3191: return '';
3192: }
3193:
3194: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3195: }
3196:
3197: # --------------------------------------------- Set Expire Date for Spreadsheet
3198:
3199: sub expirespread {
3200: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3201: my $cid=$env{'request.course.id'};
1.110 www 3202: if ($cid) {
3203: my $now=time;
3204: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3205: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3206: $env{'course.'.$cid.'.num'}.
1.110 www 3207: ':nohist_expirationdates:'.
3208: &escape($key).'='.$now,
1.620 albertel 3209: $env{'course.'.$cid.'.home'})
1.110 www 3210: }
3211: return 'ok';
1.14 www 3212: }
3213:
1.109 www 3214: # ----------------------------------------------------- Devalidate Spreadsheets
3215:
3216: sub devalidate {
1.325 www 3217: my ($symb,$uname,$udom)=@_;
1.620 albertel 3218: my $cid=$env{'request.course.id'};
1.109 www 3219: if ($cid) {
1.391 matthew 3220: # delete the stored spreadsheets for
3221: # - the student level sheet of this user in course's homespace
3222: # - the assessment level sheet for this resource
3223: # for this user in user's homespace
1.553 albertel 3224: # - current conditional state info
1.325 www 3225: my $key=$uname.':'.$udom.':';
1.109 www 3226: my $status=
1.299 matthew 3227: &del('nohist_calculatedsheets',
1.391 matthew 3228: [$key.'studentcalc:'],
1.620 albertel 3229: $env{'course.'.$cid.'.domain'},
3230: $env{'course.'.$cid.'.num'})
1.133 albertel 3231: .' '.
3232: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3233: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3234: unless ($status eq 'ok ok') {
3235: &logthis('Could not devalidate spreadsheet '.
1.325 www 3236: $uname.' at '.$udom.' for '.
1.109 www 3237: $symb.': '.$status);
1.133 albertel 3238: }
1.553 albertel 3239: &delenv('user.state.'.$cid);
1.109 www 3240: }
3241: }
3242:
1.265 albertel 3243: sub get_scalar {
3244: my ($string,$end) = @_;
3245: my $value;
3246: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3247: $value = $1;
3248: } elsif ($$string =~ s/^([^&]*?)&//) {
3249: $value = $1;
3250: }
3251: return &unescape($value);
3252: }
3253:
3254: sub array2str {
3255: my (@array) = @_;
3256: my $result=&arrayref2str(\@array);
3257: $result=~s/^__ARRAY_REF__//;
3258: $result=~s/__END_ARRAY_REF__$//;
3259: return $result;
3260: }
3261:
1.204 albertel 3262: sub arrayref2str {
3263: my ($arrayref) = @_;
1.265 albertel 3264: my $result='__ARRAY_REF__';
1.204 albertel 3265: foreach my $elem (@$arrayref) {
1.265 albertel 3266: if(ref($elem) eq 'ARRAY') {
3267: $result.=&arrayref2str($elem).'&';
3268: } elsif(ref($elem) eq 'HASH') {
3269: $result.=&hashref2str($elem).'&';
3270: } elsif(ref($elem)) {
3271: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3272: } else {
3273: $result.=&escape($elem).'&';
3274: }
3275: }
3276: $result=~s/\&$//;
1.265 albertel 3277: $result .= '__END_ARRAY_REF__';
1.204 albertel 3278: return $result;
3279: }
3280:
1.168 albertel 3281: sub hash2str {
1.204 albertel 3282: my (%hash) = @_;
3283: my $result=&hashref2str(\%hash);
1.265 albertel 3284: $result=~s/^__HASH_REF__//;
3285: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3286: return $result;
3287: }
3288:
3289: sub hashref2str {
3290: my ($hashref)=@_;
1.265 albertel 3291: my $result='__HASH_REF__';
1.800 albertel 3292: foreach my $key (sort(keys(%$hashref))) {
3293: if (ref($key) eq 'ARRAY') {
3294: $result.=&arrayref2str($key).'=';
3295: } elsif (ref($key) eq 'HASH') {
3296: $result.=&hashref2str($key).'=';
3297: } elsif (ref($key)) {
1.265 albertel 3298: $result.='=';
1.800 albertel 3299: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3300: } else {
1.800 albertel 3301: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3302: }
3303:
1.800 albertel 3304: if(ref($hashref->{$key}) eq 'ARRAY') {
3305: $result.=&arrayref2str($hashref->{$key}).'&';
3306: } elsif(ref($hashref->{$key}) eq 'HASH') {
3307: $result.=&hashref2str($hashref->{$key}).'&';
3308: } elsif(ref($hashref->{$key})) {
1.265 albertel 3309: $result.='&';
1.800 albertel 3310: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3311: } else {
1.800 albertel 3312: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3313: }
3314: }
1.168 albertel 3315: $result=~s/\&$//;
1.265 albertel 3316: $result .= '__END_HASH_REF__';
1.168 albertel 3317: return $result;
3318: }
3319:
3320: sub str2hash {
1.265 albertel 3321: my ($string)=@_;
3322: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3323: return %$hash;
3324: }
3325:
3326: sub str2hashref {
1.168 albertel 3327: my ($string) = @_;
1.265 albertel 3328:
3329: my %hash;
3330:
3331: if($string !~ /^__HASH_REF__/) {
3332: if (! ($string eq '' || !defined($string))) {
3333: $hash{'error'}='Not hash reference';
3334: }
3335: return (\%hash, $string);
3336: }
3337:
3338: $string =~ s/^__HASH_REF__//;
3339:
3340: while($string !~ /^__END_HASH_REF__/) {
3341: #key
3342: my $key='';
3343: if($string =~ /^__HASH_REF__/) {
3344: ($key, $string)=&str2hashref($string);
3345: if(defined($key->{'error'})) {
3346: $hash{'error'}='Bad data';
3347: return (\%hash, $string);
3348: }
3349: } elsif($string =~ /^__ARRAY_REF__/) {
3350: ($key, $string)=&str2arrayref($string);
3351: if($key->[0] eq 'Array reference error') {
3352: $hash{'error'}='Bad data';
3353: return (\%hash, $string);
3354: }
3355: } else {
3356: $string =~ s/^(.*?)=//;
1.267 albertel 3357: $key=&unescape($1);
1.265 albertel 3358: }
3359: $string =~ s/^=//;
3360:
3361: #value
3362: my $value='';
3363: if($string =~ /^__HASH_REF__/) {
3364: ($value, $string)=&str2hashref($string);
3365: if(defined($value->{'error'})) {
3366: $hash{'error'}='Bad data';
3367: return (\%hash, $string);
3368: }
3369: } elsif($string =~ /^__ARRAY_REF__/) {
3370: ($value, $string)=&str2arrayref($string);
3371: if($value->[0] eq 'Array reference error') {
3372: $hash{'error'}='Bad data';
3373: return (\%hash, $string);
3374: }
3375: } else {
3376: $value=&get_scalar(\$string,'__END_HASH_REF__');
3377: }
3378: $string =~ s/^&//;
3379:
3380: $hash{$key}=$value;
1.204 albertel 3381: }
1.265 albertel 3382:
3383: $string =~ s/^__END_HASH_REF__//;
3384:
3385: return (\%hash, $string);
1.204 albertel 3386: }
3387:
3388: sub str2array {
1.265 albertel 3389: my ($string)=@_;
3390: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3391: return @$array;
3392: }
3393:
3394: sub str2arrayref {
1.204 albertel 3395: my ($string) = @_;
1.265 albertel 3396: my @array;
3397:
3398: if($string !~ /^__ARRAY_REF__/) {
3399: if (! ($string eq '' || !defined($string))) {
3400: $array[0]='Array reference error';
3401: }
3402: return (\@array, $string);
3403: }
3404:
3405: $string =~ s/^__ARRAY_REF__//;
3406:
3407: while($string !~ /^__END_ARRAY_REF__/) {
3408: my $value='';
3409: if($string =~ /^__HASH_REF__/) {
3410: ($value, $string)=&str2hashref($string);
3411: if(defined($value->{'error'})) {
3412: $array[0] ='Array reference error';
3413: return (\@array, $string);
3414: }
3415: } elsif($string =~ /^__ARRAY_REF__/) {
3416: ($value, $string)=&str2arrayref($string);
3417: if($value->[0] eq 'Array reference error') {
3418: $array[0] ='Array reference error';
3419: return (\@array, $string);
3420: }
3421: } else {
3422: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3423: }
3424: $string =~ s/^&//;
3425:
3426: push(@array, $value);
1.191 harris41 3427: }
1.265 albertel 3428:
3429: $string =~ s/^__END_ARRAY_REF__//;
3430:
3431: return (\@array, $string);
1.168 albertel 3432: }
3433:
1.167 albertel 3434: # -------------------------------------------------------------------Temp Store
3435:
1.168 albertel 3436: sub tmpreset {
3437: my ($symb,$namespace,$domain,$stuname) = @_;
3438: if (!$symb) {
3439: $symb=&symbread();
1.620 albertel 3440: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3441: }
3442: $symb=escape($symb);
3443:
1.620 albertel 3444: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3445: $namespace=~s/\//\_/g;
3446: $namespace=~s/\W//g;
3447:
1.620 albertel 3448: if (!$domain) { $domain=$env{'user.domain'}; }
3449: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3450: if ($domain eq 'public' && $stuname eq 'public') {
3451: $stuname=$ENV{'REMOTE_ADDR'};
3452: }
1.168 albertel 3453: my $path=$perlvar{'lonDaemons'}.'/tmp';
3454: my %hash;
3455: if (tie(%hash,'GDBM_File',
3456: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3457: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3458: foreach my $key (keys(%hash)) {
1.180 albertel 3459: if ($key=~ /:$symb/) {
1.168 albertel 3460: delete($hash{$key});
3461: }
3462: }
3463: }
3464: }
3465:
1.167 albertel 3466: sub tmpstore {
1.168 albertel 3467: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3468:
3469: if (!$symb) {
3470: $symb=&symbread();
1.620 albertel 3471: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3472: }
3473: $symb=escape($symb);
3474:
3475: if (!$namespace) {
3476: # I don't think we would ever want to store this for a course.
3477: # it seems this will only be used if we don't have a course.
1.620 albertel 3478: #$namespace=$env{'request.course.id'};
1.168 albertel 3479: #if (!$namespace) {
1.620 albertel 3480: $namespace=$env{'request.state'};
1.168 albertel 3481: #}
3482: }
3483: $namespace=~s/\//\_/g;
3484: $namespace=~s/\W//g;
1.620 albertel 3485: if (!$domain) { $domain=$env{'user.domain'}; }
3486: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3487: if ($domain eq 'public' && $stuname eq 'public') {
3488: $stuname=$ENV{'REMOTE_ADDR'};
3489: }
1.168 albertel 3490: my $now=time;
3491: my %hash;
3492: my $path=$perlvar{'lonDaemons'}.'/tmp';
3493: if (tie(%hash,'GDBM_File',
3494: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3495: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3496: $hash{"version:$symb"}++;
3497: my $version=$hash{"version:$symb"};
3498: my $allkeys='';
3499: foreach my $key (keys(%$storehash)) {
3500: $allkeys.=$key.':';
1.591 albertel 3501: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3502: }
3503: $hash{"$version:$symb:timestamp"}=$now;
3504: $allkeys.='timestamp';
3505: $hash{"$version:keys:$symb"}=$allkeys;
3506: if (untie(%hash)) {
3507: return 'ok';
3508: } else {
3509: return "error:$!";
3510: }
3511: } else {
3512: return "error:$!";
3513: }
3514: }
1.167 albertel 3515:
1.168 albertel 3516: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3517:
1.168 albertel 3518: sub tmprestore {
3519: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3520:
1.168 albertel 3521: if (!$symb) {
3522: $symb=&symbread();
1.620 albertel 3523: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3524: }
3525: $symb=escape($symb);
3526:
1.620 albertel 3527: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3528:
1.620 albertel 3529: if (!$domain) { $domain=$env{'user.domain'}; }
3530: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3531: if ($domain eq 'public' && $stuname eq 'public') {
3532: $stuname=$ENV{'REMOTE_ADDR'};
3533: }
1.168 albertel 3534: my %returnhash;
3535: $namespace=~s/\//\_/g;
3536: $namespace=~s/\W//g;
3537: my %hash;
3538: my $path=$perlvar{'lonDaemons'}.'/tmp';
3539: if (tie(%hash,'GDBM_File',
3540: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3541: &GDBM_READER(),0640)) {
1.168 albertel 3542: my $version=$hash{"version:$symb"};
3543: $returnhash{'version'}=$version;
3544: my $scope;
3545: for ($scope=1;$scope<=$version;$scope++) {
3546: my $vkeys=$hash{"$scope:keys:$symb"};
3547: my @keys=split(/:/,$vkeys);
3548: my $key;
3549: $returnhash{"$scope:keys"}=$vkeys;
3550: foreach $key (@keys) {
1.591 albertel 3551: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3552: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3553: }
3554: }
1.168 albertel 3555: if (!(untie(%hash))) {
3556: return "error:$!";
3557: }
3558: } else {
3559: return "error:$!";
3560: }
3561: return %returnhash;
1.167 albertel 3562: }
3563:
1.9 www 3564: # ----------------------------------------------------------------------- Store
3565:
3566: sub store {
1.124 www 3567: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3568: my $home='';
3569:
1.168 albertel 3570: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3571:
1.213 www 3572: $symb=&symbclean($symb);
1.122 albertel 3573: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3574:
1.620 albertel 3575: if (!$domain) { $domain=$env{'user.domain'}; }
3576: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3577:
3578: &devalidate($symb,$stuname,$domain);
1.109 www 3579:
3580: $symb=escape($symb);
1.187 www 3581: if (!$namespace) {
1.620 albertel 3582: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3583: return '';
3584: }
3585: }
1.620 albertel 3586: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3587:
3588: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3589: $$storehash{'host'}=$perlvar{'lonHostID'};
3590:
1.12 www 3591: my $namevalue='';
1.800 albertel 3592: foreach my $key (keys(%$storehash)) {
3593: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3594: }
1.12 www 3595: $namevalue=~s/\&$//;
1.187 www 3596: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3597: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3598: }
3599:
1.47 www 3600: # -------------------------------------------------------------- Critical Store
3601:
3602: sub cstore {
1.124 www 3603: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3604: my $home='';
3605:
1.168 albertel 3606: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3607:
1.213 www 3608: $symb=&symbclean($symb);
1.122 albertel 3609: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3610:
1.620 albertel 3611: if (!$domain) { $domain=$env{'user.domain'}; }
3612: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3613:
3614: &devalidate($symb,$stuname,$domain);
1.109 www 3615:
3616: $symb=escape($symb);
1.187 www 3617: if (!$namespace) {
1.620 albertel 3618: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3619: return '';
3620: }
3621: }
1.620 albertel 3622: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3623:
3624: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3625: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3626:
1.47 www 3627: my $namevalue='';
1.800 albertel 3628: foreach my $key (keys(%$storehash)) {
3629: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3630: }
1.47 www 3631: $namevalue=~s/\&$//;
1.187 www 3632: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3633: return critical
3634: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3635: }
3636:
1.9 www 3637: # --------------------------------------------------------------------- Restore
3638:
3639: sub restore {
1.124 www 3640: my ($symb,$namespace,$domain,$stuname) = @_;
3641: my $home='';
3642:
1.168 albertel 3643: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3644:
1.122 albertel 3645: if (!$symb) {
3646: unless ($symb=escape(&symbread())) { return ''; }
3647: } else {
1.213 www 3648: $symb=&escape(&symbclean($symb));
1.122 albertel 3649: }
1.188 www 3650: if (!$namespace) {
1.620 albertel 3651: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3652: return '';
3653: }
3654: }
1.620 albertel 3655: if (!$domain) { $domain=$env{'user.domain'}; }
3656: if (!$stuname) { $stuname=$env{'user.name'}; }
3657: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3658: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3659:
1.12 www 3660: my %returnhash=();
1.800 albertel 3661: foreach my $line (split(/\&/,$answer)) {
3662: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3663: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3664: }
1.75 www 3665: my $version;
3666: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3667: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3668: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3669: }
1.75 www 3670: }
1.13 www 3671: return %returnhash;
1.34 www 3672: }
3673:
3674: # ---------------------------------------------------------- Course Description
3675:
3676: sub coursedescription {
1.731 albertel 3677: my ($courseid,$args)=@_;
1.34 www 3678: $courseid=~s/^\///;
1.49 www 3679: $courseid=~s/\_/\//g;
1.34 www 3680: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3681: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3682: my $normalid=$cdomain.'_'.$cnum;
3683: # need to always cache even if we get errors otherwise we keep
3684: # trying and trying and trying to get the course description.
3685: my %envhash=();
3686: my %returnhash=();
1.731 albertel 3687:
3688: my $expiretime=600;
3689: if ($env{'request.course.id'} eq $normalid) {
3690: $expiretime=120;
3691: }
3692:
3693: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3694: if (!$args->{'freshen_cache'}
3695: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3696: foreach my $key (keys(%env)) {
3697: next if ($key !~ /^\Q$prefix\E(.*)/);
3698: my ($setting) = $1;
3699: $returnhash{$setting} = $env{$key};
3700: }
3701: return %returnhash;
3702: }
3703:
3704: # get the data agin
3705: if (!$args->{'one_time'}) {
3706: $envhash{'course.'.$normalid.'.last_cache'}=time;
3707: }
1.811 albertel 3708:
1.34 www 3709: if ($chome ne 'no_host') {
1.302 albertel 3710: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3711: if (!exists($returnhash{'con_lost'})) {
3712: $returnhash{'home'}= $chome;
3713: $returnhash{'domain'} = $cdomain;
3714: $returnhash{'num'} = $cnum;
1.741 raeburn 3715: if (!defined($returnhash{'type'})) {
3716: $returnhash{'type'} = 'Course';
3717: }
1.130 albertel 3718: while (my ($name,$value) = each %returnhash) {
1.53 www 3719: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3720: }
1.270 www 3721: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3722: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3723: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3724: $envhash{'course.'.$normalid.'.home'}=$chome;
3725: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3726: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3727: }
3728: }
1.731 albertel 3729: if (!$args->{'one_time'}) {
1.949 raeburn 3730: &appenv(\%envhash);
1.731 albertel 3731: }
1.302 albertel 3732: return %returnhash;
1.461 www 3733: }
3734:
3735: # -------------------------------------------------See if a user is privileged
3736:
3737: sub privileged {
3738: my ($username,$domain)=@_;
3739: my $rolesdump=&reply("dump:$domain:$username:roles",
3740: &homeserver($username,$domain));
3741: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3742: my $now=time;
3743: if ($rolesdump ne '') {
1.800 albertel 3744: foreach my $entry (split(/&/,$rolesdump)) {
3745: if ($entry!~/^rolesdef_/) {
3746: my ($area,$role)=split(/=/,$entry);
1.461 www 3747: $area=~s/\_\w\w$//;
3748: my ($trole,$tend,$tstart)=split(/_/,$role);
3749: if (($trole eq 'dc') || ($trole eq 'su')) {
3750: my $active=1;
3751: if ($tend) {
3752: if ($tend<$now) { $active=0; }
3753: }
3754: if ($tstart) {
3755: if ($tstart>$now) { $active=0; }
3756: }
3757: if ($active) { return 1; }
3758: }
3759: }
3760: }
3761: }
3762: return 0;
1.9 www 3763: }
1.1 albertel 3764:
1.103 harris41 3765: # -------------------------------------------------------- Get user privileges
1.11 www 3766:
3767: sub rolesinit {
3768: my ($domain,$username,$authhost)=@_;
1.966 raeburn 3769: my %userroles;
1.11 www 3770: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966 raeburn 3771: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11 www 3772: my %allroles=();
1.678 raeburn 3773: my %allgroups=();
1.11 www 3774: my $now=time;
1.966 raeburn 3775: %userroles = ('user.login.time' => $now);
1.678 raeburn 3776: my $group_privs;
1.11 www 3777:
3778: if ($rolesdump ne '') {
1.800 albertel 3779: foreach my $entry (split(/&/,$rolesdump)) {
3780: if ($entry!~/^rolesdef_/) {
3781: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3782: $area=~s/\_\w\w$//;
1.678 raeburn 3783: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3784: if ($role=~/^cr/) {
1.807 albertel 3785: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3786: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3787: ($tend,$tstart)=split('_',$trest);
3788: } else {
3789: $trole=$role;
3790: }
1.678 raeburn 3791: } elsif ($role =~ m|^gr/|) {
3792: ($trole,$tend,$tstart) = split(/_/,$role);
3793: ($trole,$group_privs) = split(/\//,$trole);
3794: $group_privs = &unescape($group_privs);
1.587 albertel 3795: } else {
3796: ($trole,$tend,$tstart)=split(/_/,$role);
3797: }
1.743 albertel 3798: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3799: $username);
3800: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3801: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3802: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3803: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3804: my $spec=$trole.'.'.$area;
3805: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3806: if ($trole =~ /^cr\//) {
1.567 raeburn 3807: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3808: } elsif ($trole eq 'gr') {
3809: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3810: } else {
1.567 raeburn 3811: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3812: }
1.12 www 3813: }
1.662 raeburn 3814: }
1.191 harris41 3815: }
1.743 albertel 3816: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3817: $userroles{'user.adv'} = $adv;
3818: $userroles{'user.author'} = $author;
1.620 albertel 3819: $env{'user.adv'}=$adv;
1.11 www 3820: }
1.743 albertel 3821: return \%userroles;
1.11 www 3822: }
3823:
1.567 raeburn 3824: sub set_arearole {
3825: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3826: # log the associated role with the area
3827: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3828: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3829: }
3830:
3831: sub custom_roleprivs {
3832: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3833: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3834: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3835: if (&hostname($homsvr) ne '') {
1.567 raeburn 3836: my ($rdummy,$roledef)=
3837: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3838: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3839: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3840: if (defined($syspriv)) {
3841: $$allroles{'cm./'}.=':'.$syspriv;
3842: $$allroles{$spec.'./'}.=':'.$syspriv;
3843: }
3844: if ($tdomain ne '') {
3845: if (defined($dompriv)) {
3846: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3847: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3848: }
3849: if (($trest ne '') && (defined($coursepriv))) {
3850: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3851: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3852: }
3853: }
3854: }
3855: }
3856: }
3857:
1.678 raeburn 3858: sub group_roleprivs {
3859: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3860: my $access = 1;
3861: my $now = time;
3862: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3863: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3864: if ($access) {
1.811 albertel 3865: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3866: $$allgroups{$course}{$group} .=':'.$group_privs;
3867: }
3868: }
1.567 raeburn 3869:
3870: sub standard_roleprivs {
3871: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3872: if (defined($pr{$trole.':s'})) {
3873: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3874: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3875: }
3876: if ($tdomain ne '') {
3877: if (defined($pr{$trole.':d'})) {
3878: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3879: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3880: }
3881: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3882: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3883: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3884: }
3885: }
3886: }
3887:
3888: sub set_userprivs {
1.678 raeburn 3889: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3890: my $author=0;
3891: my $adv=0;
1.678 raeburn 3892: my %grouproles = ();
3893: if (keys(%{$allgroups}) > 0) {
1.1000 raeburn 3894: foreach my $role (keys(%{$allroles})) {
1.681 raeburn 3895: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3896: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3897: $trole = $1;
3898: $area = $2;
1.681 raeburn 3899: $sec = $3;
3900: $extendedarea = $area.$sec;
3901: if (exists($$allgroups{$area})) {
3902: foreach my $group (keys(%{$$allgroups{$area}})) {
3903: my $spec = $trole.'.'.$extendedarea;
3904: $grouproles{$spec.'.'.$area.'/'.$group} =
3905: $$allgroups{$area}{$group};
1.678 raeburn 3906: }
3907: }
3908: }
3909: }
3910: }
1.800 albertel 3911: foreach my $group (keys(%grouproles)) {
3912: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3913: }
1.800 albertel 3914: foreach my $role (keys(%{$allroles})) {
3915: my %thesepriv;
1.941 raeburn 3916: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3917: foreach my $item (split(/:/,$$allroles{$role})) {
3918: if ($item ne '') {
3919: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3920: if ($restrictions eq '') {
3921: $thesepriv{$privilege}='F';
3922: } elsif ($thesepriv{$privilege} ne 'F') {
3923: $thesepriv{$privilege}.=$restrictions;
3924: }
3925: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3926: }
3927: }
3928: my $thesestr='';
1.800 albertel 3929: foreach my $priv (keys(%thesepriv)) {
3930: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3931: }
3932: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3933: }
3934: return ($author,$adv);
3935: }
3936:
1.994 raeburn 3937: sub role_status {
1.1002 raeburn 3938: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 3939: my @pwhere = ();
3940: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
3941: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
3942: unless (!defined($$role) || $$role eq '') {
3943: $$where=join('.',@pwhere);
3944: $$trolecode=$$role.'.'.$$where;
3945: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
3946: $$tstatus='is';
3947: if ($$tstart && $$tstart>$then) {
3948: $$tstatus='future';
1.1002 raeburn 3949: if ($$tstart && $$tstart>$refresh) {
3950: if ($$tstart<$now) {
3951: if (($$where ne '') && ($$role ne '')) {
3952: my (%allroles,%allgroups,$group_privs);
3953: my %userroles = (
3954: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
3955: );
3956: my $spec=$$role.'.'.$$where;
3957: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
3958: if ($$role eq 'gr') {
3959: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
3960: $env{'user.name'})=@_;
3961: my ($trole) = split('_',$role,1);
3962: (undef,my $group_privs) = split(/\//,$trole);
3963: $group_privs = &unescape($group_privs);
3964: }
3965: if ($$role =~ /^cr\//) {
3966: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
3967: } elsif ($$role eq 'gr') {
3968: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
3969: $env{'user.name'});
3970: my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
3971: (undef,my $group_privs) = split(/\//,$trole);
3972: $group_privs = &unescape($group_privs);
3973: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
3974: } else {
3975: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
3976: }
3977: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
3978: &appenv(\%userroles,[$$role,'cm']);
3979: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
3980: $$tstatus = 'is';
3981: }
3982: }
3983: }
1.994 raeburn 3984: }
3985: if ($$tend) {
3986: if ($$tend<$then) {
3987: $$tstatus='expired';
3988: } elsif ($$tend<$now) {
3989: $$tstatus='will_not';
3990: }
3991: }
3992: }
3993: }
3994: }
3995:
3996: sub check_adhoc_privs {
1.1002 raeburn 3997: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 3998: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
3999: if ($env{$cckey}) {
4000: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4001: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4002: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4003: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4004: }
4005: } else {
4006: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4007: }
4008: }
4009:
4010: sub set_adhoc_privileges {
4011: # role can be cc or ca
4012: my ($dcdom,$pickedcourse,$role) = @_;
4013: my $area = '/'.$dcdom.'/'.$pickedcourse;
4014: my $spec = $role.'.'.$area;
4015: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4016: $env{'user.name'});
4017: my %ccrole = ();
4018: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4019: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4020: &appenv(\%userroles,[$role,'cm']);
4021: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4022: &appenv( {'request.role' => $spec,
4023: 'request.role.domain' => $dcdom,
4024: 'request.course.sec' => ''
4025: }
4026: );
4027: my $tadv=0;
4028: if (&allowed('adv') eq 'F') { $tadv=1; }
4029: &appenv({'request.role.adv' => $tadv});
4030: }
4031:
1.12 www 4032: # --------------------------------------------------------------- get interface
4033:
4034: sub get {
1.131 albertel 4035: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4036: my $items='';
1.800 albertel 4037: foreach my $item (@$storearr) {
4038: $items.=&escape($item).'&';
1.191 harris41 4039: }
1.12 www 4040: $items=~s/\&$//;
1.620 albertel 4041: if (!$udomain) { $udomain=$env{'user.domain'}; }
4042: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4043: my $uhome=&homeserver($uname,$udomain);
4044:
1.133 albertel 4045: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4046: my @pairs=split(/\&/,$rep);
1.273 albertel 4047: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4048: return @pairs;
4049: }
1.15 www 4050: my %returnhash=();
1.42 www 4051: my $i=0;
1.800 albertel 4052: foreach my $item (@$storearr) {
4053: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4054: $i++;
1.191 harris41 4055: }
1.15 www 4056: return %returnhash;
1.27 www 4057: }
4058:
4059: # --------------------------------------------------------------- del interface
4060:
4061: sub del {
1.133 albertel 4062: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4063: my $items='';
1.800 albertel 4064: foreach my $item (@$storearr) {
4065: $items.=&escape($item).'&';
1.191 harris41 4066: }
1.984 neumanie 4067:
1.27 www 4068: $items=~s/\&$//;
1.620 albertel 4069: if (!$udomain) { $udomain=$env{'user.domain'}; }
4070: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4071: my $uhome=&homeserver($uname,$udomain);
4072: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4073: }
4074:
4075: # -------------------------------------------------------------- dump interface
4076:
4077: sub dump {
1.755 albertel 4078: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4079: if (!$udomain) { $udomain=$env{'user.domain'}; }
4080: if (!$uname) { $uname=$env{'user.name'}; }
4081: my $uhome=&homeserver($uname,$udomain);
4082: if ($regexp) {
4083: $regexp=&escape($regexp);
4084: } else {
4085: $regexp='.';
4086: }
4087: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4088: my @pairs=split(/\&/,$rep);
4089: my %returnhash=();
4090: foreach my $item (@pairs) {
4091: my ($key,$value)=split(/=/,$item,2);
4092: $key = &unescape($key);
4093: next if ($key =~ /^error: 2 /);
4094: $returnhash{$key}=&thaw_unescape($value);
4095: }
4096: return %returnhash;
1.407 www 4097: }
4098:
1.717 albertel 4099: # --------------------------------------------------------- dumpstore interface
4100:
4101: sub dumpstore {
4102: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4103: if (!$udomain) { $udomain=$env{'user.domain'}; }
4104: if (!$uname) { $uname=$env{'user.name'}; }
4105: my $uhome=&homeserver($uname,$udomain);
4106: if ($regexp) {
4107: $regexp=&escape($regexp);
4108: } else {
4109: $regexp='.';
4110: }
4111: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4112: my @pairs=split(/\&/,$rep);
4113: my %returnhash=();
4114: foreach my $item (@pairs) {
4115: my ($key,$value)=split(/=/,$item,2);
4116: next if ($key =~ /^error: 2 /);
4117: $returnhash{$key}=&thaw_unescape($value);
4118: }
4119: return %returnhash;
1.717 albertel 4120: }
4121:
1.407 www 4122: # -------------------------------------------------------------- keys interface
4123:
4124: sub getkeys {
4125: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4126: if (!$udomain) { $udomain=$env{'user.domain'}; }
4127: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4128: my $uhome=&homeserver($uname,$udomain);
4129: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4130: my @keyarray=();
1.800 albertel 4131: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4132: next if ($key =~ /^error: 2 /);
1.800 albertel 4133: push(@keyarray,&unescape($key));
1.407 www 4134: }
4135: return @keyarray;
1.318 matthew 4136: }
4137:
1.319 matthew 4138: # --------------------------------------------------------------- currentdump
4139: sub currentdump {
1.328 matthew 4140: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4141: $courseid = $env{'request.course.id'} if (! defined($courseid));
4142: $sdom = $env{'user.domain'} if (! defined($sdom));
4143: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4144: my $uhome = &homeserver($sname,$sdom);
4145: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4146: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4147: #
1.318 matthew 4148: my %returnhash=();
1.319 matthew 4149: #
4150: if ($rep eq "unknown_cmd") {
4151: # an old lond will not know currentdump
4152: # Do a dump and make it look like a currentdump
1.822 albertel 4153: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4154: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4155: my %hash = @tmp;
4156: @tmp=();
1.424 matthew 4157: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4158: } else {
4159: my @pairs=split(/\&/,$rep);
1.800 albertel 4160: foreach my $pair (@pairs) {
4161: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4162: my ($symb,$param) = split(/:/,$key);
4163: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4164: &thaw_unescape($value);
1.319 matthew 4165: }
1.191 harris41 4166: }
1.12 www 4167: return %returnhash;
1.424 matthew 4168: }
4169:
4170: sub convert_dump_to_currentdump{
4171: my %hash = %{shift()};
4172: my %returnhash;
4173: # Code ripped from lond, essentially. The only difference
4174: # here is the unescaping done by lonnet::dump(). Conceivably
4175: # we might run in to problems with parameter names =~ /^v\./
4176: while (my ($key,$value) = each(%hash)) {
4177: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4178: $symb = &unescape($symb);
4179: $param = &unescape($param);
1.424 matthew 4180: next if ($v eq 'version' || $symb eq 'keys');
4181: next if (exists($returnhash{$symb}) &&
4182: exists($returnhash{$symb}->{$param}) &&
4183: $returnhash{$symb}->{'v.'.$param} > $v);
4184: $returnhash{$symb}->{$param}=$value;
4185: $returnhash{$symb}->{'v.'.$param}=$v;
4186: }
4187: #
4188: # Remove all of the keys in the hashes which keep track of
4189: # the version of the parameter.
4190: while (my ($symb,$param_hash) = each(%returnhash)) {
4191: # use a foreach because we are going to delete from the hash.
4192: foreach my $key (keys(%$param_hash)) {
4193: delete($param_hash->{$key}) if ($key =~ /^v\./);
4194: }
4195: }
4196: return \%returnhash;
1.12 www 4197: }
4198:
1.627 albertel 4199: # ------------------------------------------------------ critical inc interface
4200:
4201: sub cinc {
4202: return &inc(@_,'critical');
4203: }
4204:
1.449 matthew 4205: # --------------------------------------------------------------- inc interface
4206:
4207: sub inc {
1.627 albertel 4208: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4209: if (!$udomain) { $udomain=$env{'user.domain'}; }
4210: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4211: my $uhome=&homeserver($uname,$udomain);
4212: my $items='';
4213: if (! ref($store)) {
4214: # got a single value, so use that instead
4215: $items = &escape($store).'=&';
4216: } elsif (ref($store) eq 'SCALAR') {
4217: $items = &escape($$store).'=&';
4218: } elsif (ref($store) eq 'ARRAY') {
4219: $items = join('=&',map {&escape($_);} @{$store});
4220: } elsif (ref($store) eq 'HASH') {
4221: while (my($key,$value) = each(%{$store})) {
4222: $items.= &escape($key).'='.&escape($value).'&';
4223: }
4224: }
4225: $items=~s/\&$//;
1.627 albertel 4226: if ($critical) {
4227: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4228: } else {
4229: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4230: }
1.449 matthew 4231: }
4232:
1.12 www 4233: # --------------------------------------------------------------- put interface
4234:
4235: sub put {
1.134 albertel 4236: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4237: if (!$udomain) { $udomain=$env{'user.domain'}; }
4238: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4239: my $uhome=&homeserver($uname,$udomain);
1.12 www 4240: my $items='';
1.800 albertel 4241: foreach my $item (keys(%$storehash)) {
4242: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4243: }
1.12 www 4244: $items=~s/\&$//;
1.134 albertel 4245: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4246: }
4247:
1.631 albertel 4248: # ------------------------------------------------------------ newput interface
4249:
4250: sub newput {
4251: my ($namespace,$storehash,$udomain,$uname)=@_;
4252: if (!$udomain) { $udomain=$env{'user.domain'}; }
4253: if (!$uname) { $uname=$env{'user.name'}; }
4254: my $uhome=&homeserver($uname,$udomain);
4255: my $items='';
4256: foreach my $key (keys(%$storehash)) {
4257: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4258: }
4259: $items=~s/\&$//;
4260: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4261: }
4262:
4263: # --------------------------------------------------------- putstore interface
4264:
1.524 raeburn 4265: sub putstore {
1.715 albertel 4266: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4267: if (!$udomain) { $udomain=$env{'user.domain'}; }
4268: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4269: my $uhome=&homeserver($uname,$udomain);
4270: my $items='';
1.715 albertel 4271: foreach my $key (keys(%$storehash)) {
4272: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4273: }
1.715 albertel 4274: $items=~s/\&$//;
1.716 albertel 4275: my $esc_symb=&escape($symb);
4276: my $esc_v=&escape($version);
1.715 albertel 4277: my $reply =
1.716 albertel 4278: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4279: $uhome);
4280: if ($reply eq 'unknown_cmd') {
1.716 albertel 4281: # gfall back to way things use to be done
1.715 albertel 4282: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4283: $uname);
1.524 raeburn 4284: }
1.715 albertel 4285: return $reply;
4286: }
4287:
4288: sub old_putstore {
1.716 albertel 4289: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4290: if (!$udomain) { $udomain=$env{'user.domain'}; }
4291: if (!$uname) { $uname=$env{'user.name'}; }
4292: my $uhome=&homeserver($uname,$udomain);
4293: my %newstorehash;
1.800 albertel 4294: foreach my $item (keys(%$storehash)) {
4295: my $key = $version.':'.&escape($symb).':'.$item;
4296: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4297: }
4298: my $items='';
4299: my %allitems = ();
1.800 albertel 4300: foreach my $item (keys(%newstorehash)) {
4301: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4302: my $key = $1.':keys:'.$2;
4303: $allitems{$key} .= $3.':';
4304: }
1.800 albertel 4305: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4306: }
1.800 albertel 4307: foreach my $item (keys(%allitems)) {
4308: $allitems{$item} =~ s/\:$//;
4309: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4310: }
4311: $items=~s/\&$//;
4312: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4313: }
4314:
1.47 www 4315: # ------------------------------------------------------ critical put interface
4316:
4317: sub cput {
1.134 albertel 4318: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4319: if (!$udomain) { $udomain=$env{'user.domain'}; }
4320: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4321: my $uhome=&homeserver($uname,$udomain);
1.47 www 4322: my $items='';
1.800 albertel 4323: foreach my $item (keys(%$storehash)) {
4324: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4325: }
1.47 www 4326: $items=~s/\&$//;
1.134 albertel 4327: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4328: }
4329:
4330: # -------------------------------------------------------------- eget interface
4331:
4332: sub eget {
1.133 albertel 4333: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4334: my $items='';
1.800 albertel 4335: foreach my $item (@$storearr) {
4336: $items.=&escape($item).'&';
1.191 harris41 4337: }
1.12 www 4338: $items=~s/\&$//;
1.620 albertel 4339: if (!$udomain) { $udomain=$env{'user.domain'}; }
4340: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4341: my $uhome=&homeserver($uname,$udomain);
4342: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4343: my @pairs=split(/\&/,$rep);
4344: my %returnhash=();
1.42 www 4345: my $i=0;
1.800 albertel 4346: foreach my $item (@$storearr) {
4347: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4348: $i++;
1.191 harris41 4349: }
1.12 www 4350: return %returnhash;
4351: }
4352:
1.667 albertel 4353: # ------------------------------------------------------------ tmpput interface
4354: sub tmpput {
1.802 raeburn 4355: my ($storehash,$server,$context)=@_;
1.667 albertel 4356: my $items='';
1.800 albertel 4357: foreach my $item (keys(%$storehash)) {
4358: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4359: }
4360: $items=~s/\&$//;
1.802 raeburn 4361: if (defined($context)) {
4362: $items .= ':'.&escape($context);
4363: }
1.667 albertel 4364: return &reply("tmpput:$items",$server);
4365: }
4366:
4367: # ------------------------------------------------------------ tmpget interface
4368: sub tmpget {
1.688 albertel 4369: my ($token,$server)=@_;
4370: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4371: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4372: my %returnhash;
4373: foreach my $item (split(/\&/,$rep)) {
4374: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4375: next if ($key =~ /^error: 2 /);
1.667 albertel 4376: $returnhash{&unescape($key)}=&thaw_unescape($value);
4377: }
4378: return %returnhash;
4379: }
4380:
1.688 albertel 4381: # ------------------------------------------------------------ tmpget interface
4382: sub tmpdel {
4383: my ($token,$server)=@_;
4384: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4385: return &reply("tmpdel:$token",$server);
4386: }
4387:
1.765 albertel 4388: # -------------------------------------------------- portfolio access checking
4389:
4390: sub portfolio_access {
1.766 albertel 4391: my ($requrl) = @_;
1.765 albertel 4392: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4393: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4394: if ($result) {
4395: my %setters;
4396: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4397: my ($startblock,$endblock) =
4398: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4399: if ($startblock && $endblock) {
4400: return 'B';
4401: }
4402: } else {
4403: my ($startblock,$endblock) =
4404: &Apache::loncommon::blockcheck(\%setters,'port');
4405: if ($startblock && $endblock) {
4406: return 'B';
4407: }
4408: }
4409: }
1.765 albertel 4410: if ($result eq 'ok') {
1.766 albertel 4411: return 'F';
1.765 albertel 4412: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4413: return 'A';
1.765 albertel 4414: }
1.766 albertel 4415: return '';
1.765 albertel 4416: }
4417:
4418: sub get_portfolio_access {
1.767 albertel 4419: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4420:
4421: if (!ref($access_hash)) {
4422: my $current_perms = &get_portfile_permissions($udom,$unum);
4423: my %access_controls = &get_access_controls($current_perms,$group,
4424: $file_name);
4425: $access_hash = $access_controls{$file_name};
4426: }
4427:
1.765 albertel 4428: my ($public,$guest,@domains,@users,@courses,@groups);
4429: my $now = time;
4430: if (ref($access_hash) eq 'HASH') {
4431: foreach my $key (keys(%{$access_hash})) {
4432: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4433: if ($start > $now) {
4434: next;
4435: }
4436: if ($end && $end<$now) {
4437: next;
4438: }
4439: if ($scope eq 'public') {
4440: $public = $key;
4441: last;
4442: } elsif ($scope eq 'guest') {
4443: $guest = $key;
4444: } elsif ($scope eq 'domains') {
4445: push(@domains,$key);
4446: } elsif ($scope eq 'users') {
4447: push(@users,$key);
4448: } elsif ($scope eq 'course') {
4449: push(@courses,$key);
4450: } elsif ($scope eq 'group') {
4451: push(@groups,$key);
4452: }
4453: }
4454: if ($public) {
4455: return 'ok';
4456: }
4457: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4458: if ($guest) {
4459: return $guest;
4460: }
4461: } else {
4462: if (@domains > 0) {
4463: foreach my $domkey (@domains) {
4464: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4465: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4466: return 'ok';
4467: }
4468: }
4469: }
4470: }
4471: if (@users > 0) {
4472: foreach my $userkey (@users) {
1.865 raeburn 4473: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4474: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4475: if (ref($item) eq 'HASH') {
4476: if (($item->{'uname'} eq $env{'user.name'}) &&
4477: ($item->{'udom'} eq $env{'user.domain'})) {
4478: return 'ok';
4479: }
4480: }
4481: }
4482: }
1.765 albertel 4483: }
4484: }
4485: my %roleshash;
4486: my @courses_and_groups = @courses;
4487: push(@courses_and_groups,@groups);
4488: if (@courses_and_groups > 0) {
4489: my (%allgroups,%allroles);
4490: my ($start,$end,$role,$sec,$group);
4491: foreach my $envkey (%env) {
1.811 albertel 4492: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4493: my $cid = $2.'_'.$3;
4494: if ($1 eq 'gr') {
4495: $group = $4;
4496: $allgroups{$cid}{$group} = $env{$envkey};
4497: } else {
4498: if ($4 eq '') {
4499: $sec = 'none';
4500: } else {
4501: $sec = $4;
4502: }
4503: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4504: }
1.811 albertel 4505: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4506: my $cid = $2.'_'.$3;
4507: if ($4 eq '') {
4508: $sec = 'none';
4509: } else {
4510: $sec = $4;
4511: }
4512: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4513: }
4514: }
4515: if (keys(%allroles) == 0) {
4516: return;
4517: }
4518: foreach my $key (@courses_and_groups) {
4519: my %content = %{$$access_hash{$key}};
4520: my $cnum = $content{'number'};
4521: my $cdom = $content{'domain'};
4522: my $cid = $cdom.'_'.$cnum;
4523: if (!exists($allroles{$cid})) {
4524: next;
4525: }
4526: foreach my $role_id (keys(%{$content{'roles'}})) {
4527: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4528: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4529: my @status = @{$content{'roles'}{$role_id}{'access'}};
4530: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4531: foreach my $role (keys(%{$allroles{$cid}})) {
4532: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4533: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4534: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4535: if (grep/^all$/,@sections) {
4536: return 'ok';
4537: } else {
4538: if (grep/^$sec$/,@sections) {
4539: return 'ok';
4540: }
4541: }
4542: }
4543: }
4544: if (keys(%{$allgroups{$cid}}) == 0) {
4545: if (grep/^none$/,@groups) {
4546: return 'ok';
4547: }
4548: } else {
4549: if (grep/^all$/,@groups) {
4550: return 'ok';
4551: }
4552: foreach my $group (keys(%{$allgroups{$cid}})) {
4553: if (grep/^$group$/,@groups) {
4554: return 'ok';
4555: }
4556: }
4557: }
4558: }
4559: }
4560: }
4561: }
4562: }
4563: if ($guest) {
4564: return $guest;
4565: }
4566: }
4567: }
4568: return;
4569: }
4570:
4571: sub course_group_datechecker {
4572: my ($dates,$now,$status) = @_;
4573: my ($start,$end) = split(/\./,$dates);
4574: if (!$start && !$end) {
4575: return 'ok';
4576: }
4577: if (grep/^active$/,@{$status}) {
4578: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4579: return 'ok';
4580: }
4581: }
4582: if (grep/^previous$/,@{$status}) {
4583: if ($end > $now ) {
4584: return 'ok';
4585: }
4586: }
4587: if (grep/^future$/,@{$status}) {
4588: if ($start > $now) {
4589: return 'ok';
4590: }
4591: }
4592: return;
4593: }
4594:
4595: sub parse_portfolio_url {
4596: my ($url) = @_;
4597:
4598: my ($type,$udom,$unum,$group,$file_name);
4599:
1.823 albertel 4600: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4601: $type = 1;
4602: $udom = $1;
4603: $unum = $2;
4604: $file_name = $3;
1.823 albertel 4605: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4606: $type = 2;
4607: $udom = $1;
4608: $unum = $2;
4609: $group = $3;
4610: $file_name = $3.'/'.$4;
4611: }
4612: if (wantarray) {
4613: return ($type,$udom,$unum,$file_name,$group);
4614: }
4615: return $type;
4616: }
4617:
4618: sub is_portfolio_url {
4619: my ($url) = @_;
4620: return scalar(&parse_portfolio_url($url));
4621: }
4622:
1.798 raeburn 4623: sub is_portfolio_file {
4624: my ($file) = @_;
1.820 raeburn 4625: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4626: return 1;
4627: }
4628: return;
4629: }
4630:
1.976 raeburn 4631: sub usertools_access {
1.985 raeburn 4632: my ($uname,$udom,$tool,$action,$context) = @_;
4633: my ($access,%tools);
4634: if ($context eq '') {
4635: $context = 'tools';
4636: }
4637: if ($context eq 'requestcourses') {
4638: %tools = (
4639: official => 1,
4640: unofficial => 1,
1.1006 raeburn 4641: community => 1,
1.985 raeburn 4642: );
4643: } else {
4644: %tools = (
4645: aboutme => 1,
4646: blog => 1,
4647: portfolio => 1,
4648: );
4649: }
1.976 raeburn 4650: return if (!defined($tools{$tool}));
4651:
4652: if ((!defined($udom)) || (!defined($uname))) {
4653: $udom = $env{'user.domain'};
4654: $uname = $env{'user.name'};
4655: }
4656:
1.978 raeburn 4657: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4658: if ($action ne 'reload') {
1.985 raeburn 4659: if ($context eq 'requestcourses') {
4660: return $env{'environment.canrequest.'.$tool};
4661: } else {
4662: return $env{'environment.availabletools.'.$tool};
4663: }
4664: }
1.976 raeburn 4665: }
4666:
4667: my ($toolstatus,$inststatus);
4668:
1.985 raeburn 4669: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4670: ($action ne 'reload')) {
4671: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4672: $inststatus = $env{'environment.inststatus'};
4673: } else {
1.985 raeburn 4674: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
4675: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4676: $inststatus = $userenv{'inststatus'};
4677: }
4678:
4679: if ($toolstatus ne '') {
4680: if ($toolstatus) {
4681: $access = 1;
4682: } else {
4683: $access = 0;
4684: }
4685: return $access;
4686: }
4687:
4688: my $is_adv = &is_advanced_user($udom,$uname);
4689: my %domdef = &get_domain_defaults($udom);
4690: if (ref($domdef{$tool}) eq 'HASH') {
4691: if ($is_adv) {
4692: if ($domdef{$tool}{'_LC_adv'} ne '') {
4693: if ($domdef{$tool}{'_LC_adv'}) {
4694: $access = 1;
4695: } else {
4696: $access = 0;
4697: }
4698: return $access;
4699: }
4700: }
4701: if ($inststatus ne '') {
4702: my ($hasaccess,$hasnoaccess);
4703: foreach my $affiliation (split(/:/,$inststatus)) {
4704: if ($domdef{$tool}{$affiliation} ne '') {
4705: if ($domdef{$tool}{$affiliation}) {
4706: $hasaccess = 1;
4707: } else {
4708: $hasnoaccess = 1;
4709: }
4710: }
4711: }
4712: if ($hasaccess || $hasnoaccess) {
4713: if ($hasaccess) {
4714: $access = 1;
4715: } elsif ($hasnoaccess) {
4716: $access = 0;
4717: }
4718: return $access;
4719: }
4720: } else {
4721: if ($domdef{$tool}{'default'} ne '') {
4722: if ($domdef{$tool}{'default'}) {
4723: $access = 1;
4724: } elsif ($domdef{$tool}{'default'} == 0) {
4725: $access = 0;
4726: }
4727: return $access;
4728: }
4729: }
4730: } else {
1.985 raeburn 4731: if ($context eq 'tools') {
4732: $access = 1;
4733: } else {
4734: $access = 0;
4735: }
1.976 raeburn 4736: return $access;
4737: }
4738: }
4739:
4740: sub is_advanced_user {
4741: my ($udom,$uname) = @_;
4742: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4743: my %allroles;
4744: my $is_adv;
4745: foreach my $role (keys(%roleshash)) {
4746: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4747: my $area = '/'.$tdomain.'/'.$trest;
4748: if ($sec ne '') {
4749: $area .= '/'.$sec;
4750: }
4751: if (($area ne '') && ($trole ne '')) {
4752: my $spec=$trole.'.'.$area;
4753: if ($trole =~ /^cr\//) {
4754: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4755: } elsif ($trole ne 'gr') {
4756: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4757: }
4758: }
4759: }
4760: foreach my $role (keys(%allroles)) {
4761: last if ($is_adv);
4762: foreach my $item (split(/:/,$allroles{$role})) {
4763: if ($item ne '') {
4764: my ($privilege,$restrictions)=split(/&/,$item);
4765: if ($privilege eq 'adv') {
4766: $is_adv = 1;
4767: last;
4768: }
4769: }
4770: }
4771: }
4772: return $is_adv;
4773: }
1.798 raeburn 4774:
1.341 www 4775: # ---------------------------------------------- Custom access rule evaluation
4776:
4777: sub customaccess {
4778: my ($priv,$uri)=@_;
1.807 albertel 4779: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4780: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4781: $udom = &LONCAPA::clean_domain($udom);
4782: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4783: my $access=0;
1.800 albertel 4784: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4785: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4786: if ($type eq 'user') {
4787: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4788: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4789: if ($tdom) {
4790: if ($tdom ne $env{'user.domain'}) { next; }
4791: }
1.896 albertel 4792: if ($tuname) {
4793: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4794: }
4795: $access=($effect eq 'allow');
4796: last;
4797: }
4798: } else {
4799: if ($role) {
4800: if ($role ne $urole) { next; }
4801: }
4802: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4803: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4804: if ($tdom) {
4805: if ($tdom ne $udom) { next; }
4806: }
4807: if ($tcrs) {
4808: if ($tcrs ne $ucrs) { next; }
4809: }
4810: if ($tsec) {
4811: if ($tsec ne $usec) { next; }
4812: }
4813: $access=($effect eq 'allow');
4814: last;
4815: }
4816: if ($realm eq '' && $role eq '') {
4817: $access=($effect eq 'allow');
4818: }
1.402 bowersj2 4819: }
1.341 www 4820: }
4821: return $access;
4822: }
4823:
1.103 harris41 4824: # ------------------------------------------------- Check for a user privilege
1.12 www 4825:
4826: sub allowed {
1.810 raeburn 4827: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4828: my $ver_orguri=$uri;
1.439 www 4829: $uri=&deversion($uri);
1.152 www 4830: my $orguri=$uri;
1.52 www 4831: $uri=&declutter($uri);
1.809 raeburn 4832:
1.810 raeburn 4833: if ($priv eq 'evb') {
4834: # Evade communication block restrictions for specified role in a course
4835: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4836: return $1;
4837: } else {
4838: return;
4839: }
4840: }
4841:
1.620 albertel 4842: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4843: # Free bre access to adm and meta resources
1.775 albertel 4844: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4845: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4846: && ($priv eq 'bre')) {
1.14 www 4847: return 'F';
1.159 www 4848: }
4849:
1.545 banghart 4850: # Free bre access to user's own portfolio contents
1.714 raeburn 4851: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4852: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4853: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4854: my %setters;
4855: my ($startblock,$endblock) =
4856: &Apache::loncommon::blockcheck(\%setters,'port');
4857: if ($startblock && $endblock) {
4858: return 'B';
4859: } else {
4860: return 'F';
4861: }
1.545 banghart 4862: }
4863:
1.762 raeburn 4864: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4865: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4866: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4867: if (exists($env{'request.course.id'})) {
4868: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4869: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4870: if (($domain eq $cdom) && ($name eq $cnum)) {
4871: my $courseprivid=$env{'request.course.id'};
4872: $courseprivid=~s/\_/\//;
4873: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4874: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4875: return $1;
1.762 raeburn 4876: } else {
4877: if ($env{'request.course.sec'}) {
4878: $courseprivid.='/'.$env{'request.course.sec'};
4879: }
4880: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4881: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4882: return $2;
4883: }
1.714 raeburn 4884: }
4885: }
4886: }
4887: }
4888:
1.159 www 4889: # Free bre to public access
4890:
4891: if ($priv eq 'bre') {
1.238 www 4892: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4893: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4894: return 'F';
4895: }
1.238 www 4896: if ($copyright eq 'priv') {
4897: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4898: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4899: return '';
4900: }
4901: }
4902: if ($copyright eq 'domain') {
4903: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4904: unless (($env{'user.domain'} eq $1) ||
4905: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4906: return '';
4907: }
1.262 matthew 4908: }
1.620 albertel 4909: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4910: # Library role, so allow browsing of resources in this domain.
4911: return 'F';
1.238 www 4912: }
1.341 www 4913: if ($copyright eq 'custom') {
4914: unless (&customaccess($priv,$uri)) { return ''; }
4915: }
1.14 www 4916: }
1.264 matthew 4917: # Domain coordinator is trying to create a course
1.620 albertel 4918: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4919: # uri is the requested domain in this case.
4920: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4921: # a role of dc for the domain in question.
1.620 albertel 4922: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4923: }
1.29 www 4924:
1.52 www 4925: my $thisallowed='';
4926: my $statecond=0;
4927: my $courseprivid='';
4928:
4929: # Course
4930:
1.620 albertel 4931: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4932: $thisallowed.=$1;
4933: }
1.29 www 4934:
1.52 www 4935: # Domain
4936:
1.620 albertel 4937: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4938: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4939: $thisallowed.=$1;
4940: }
1.52 www 4941:
4942: # Course: uri itself is a course
1.66 www 4943: my $courseuri=$uri;
4944: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4945: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4946:
1.620 albertel 4947: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4948: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4949: $thisallowed.=$1;
4950: }
1.29 www 4951:
1.665 albertel 4952: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4953: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4954: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4955: $thisallowed='';
1.671 raeburn 4956: my ($match)=&is_on_map($uri);
4957: if ($match) {
4958: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4959: =~/\Q$priv\E\&([^\:]*)/) {
4960: $thisallowed.=$1;
4961: }
4962: } else {
1.705 albertel 4963: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4964: if ($refuri) {
4965: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4966: $thisallowed='F';
1.671 raeburn 4967: } else {
4968: $refuri=&declutter($refuri);
4969: my ($match) = &is_on_map($refuri);
4970: if ($match) {
4971: $thisallowed='F';
4972: }
1.669 raeburn 4973: }
1.671 raeburn 4974: }
4975: }
1.314 www 4976: }
1.492 albertel 4977:
1.766 albertel 4978: if ($priv eq 'bre'
4979: && $thisallowed ne 'F'
4980: && $thisallowed ne '2'
4981: && &is_portfolio_url($uri)) {
4982: $thisallowed = &portfolio_access($uri);
4983: }
4984:
1.52 www 4985: # Full access at system, domain or course-wide level? Exit.
1.29 www 4986: if ($thisallowed=~/F/) {
4987: return 'F';
4988: }
4989:
1.52 www 4990: # If this is generating or modifying users, exit with special codes
1.29 www 4991:
1.643 www 4992: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4993: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4994: my ($audom,$auname)=split('/',$uri);
1.643 www 4995: # no author name given, so this just checks on the general right to make a co-author in this domain
4996: unless ($auname) { return $thisallowed; }
4997: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4998: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4999: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5000: ($audom ne $env{'request.role.domain'}))) { return ''; }
5001: }
1.52 www 5002: return $thisallowed;
5003: }
5004: #
1.103 harris41 5005: # Gathered so far: system, domain and course wide privileges
1.52 www 5006: #
5007: # Course: See if uri or referer is an individual resource that is part of
5008: # the course
5009:
1.620 albertel 5010: if ($env{'request.course.id'}) {
1.232 www 5011:
1.620 albertel 5012: $courseprivid=$env{'request.course.id'};
5013: if ($env{'request.course.sec'}) {
5014: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5015: }
5016: $courseprivid=~s/\_/\//;
5017: my $checkreferer=1;
1.232 www 5018: my ($match,$cond)=&is_on_map($uri);
5019: if ($match) {
5020: $statecond=$cond;
1.620 albertel 5021: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5022: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5023: $thisallowed.=$1;
5024: $checkreferer=0;
5025: }
1.29 www 5026: }
1.83 www 5027:
1.148 www 5028: if ($checkreferer) {
1.620 albertel 5029: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5030: unless ($refuri) {
1.800 albertel 5031: foreach my $key (keys(%env)) {
5032: if ($key=~/^httpref\..*\*/) {
5033: my $pattern=$key;
1.156 www 5034: $pattern=~s/^httpref\.\/res\///;
1.148 www 5035: $pattern=~s/\*/\[\^\/\]\+/g;
5036: $pattern=~s/\//\\\//g;
1.152 www 5037: if ($orguri=~/$pattern/) {
1.800 albertel 5038: $refuri=$env{$key};
1.148 www 5039: }
5040: }
1.191 harris41 5041: }
1.148 www 5042: }
1.232 www 5043:
1.148 www 5044: if ($refuri) {
1.152 www 5045: $refuri=&declutter($refuri);
1.232 www 5046: my ($match,$cond)=&is_on_map($refuri);
5047: if ($match) {
5048: my $refstatecond=$cond;
1.620 albertel 5049: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5050: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5051: $thisallowed.=$1;
1.53 www 5052: $uri=$refuri;
5053: $statecond=$refstatecond;
1.52 www 5054: }
5055: }
1.148 www 5056: }
1.29 www 5057: }
1.52 www 5058: }
1.29 www 5059:
1.52 www 5060: #
1.103 harris41 5061: # Gathered now: all privileges that could apply, and condition number
1.52 www 5062: #
5063: #
5064: # Full or no access?
5065: #
1.29 www 5066:
1.52 www 5067: if ($thisallowed=~/F/) {
5068: return 'F';
5069: }
1.29 www 5070:
1.52 www 5071: unless ($thisallowed) {
5072: return '';
5073: }
1.29 www 5074:
1.52 www 5075: # Restrictions exist, deal with them
5076: #
5077: # C:according to course preferences
5078: # R:according to resource settings
5079: # L:unless locked
5080: # X:according to user session state
5081: #
5082:
5083: # Possibly locked functionality, check all courses
1.54 www 5084: # Locks might take effect only after 10 minutes cache expiration for other
5085: # courses, and 2 minutes for current course
1.52 www 5086:
5087: my $envkey;
5088: if ($thisallowed=~/L/) {
1.1000 raeburn 5089: foreach $envkey (keys(%env)) {
1.54 www 5090: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5091: my $courseid=$2;
5092: my $roleid=$1.'.'.$2;
1.92 www 5093: $courseid=~s/^\///;
1.54 www 5094: my $expiretime=600;
1.620 albertel 5095: if ($env{'request.role'} eq $roleid) {
1.54 www 5096: $expiretime=120;
5097: }
5098: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5099: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5100: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5101: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5102: }
1.620 albertel 5103: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5104: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5105: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5106: &log($env{'user.domain'},$env{'user.name'},
5107: $env{'user.home'},
1.57 www 5108: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5109: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5110: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5111: return '';
5112: }
5113: }
1.620 albertel 5114: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5115: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5116: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5117: &log($env{'user.domain'},$env{'user.name'},
5118: $env{'user.home'},
1.57 www 5119: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5120: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5121: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5122: return '';
5123: }
5124: }
5125: }
1.29 www 5126: }
1.52 www 5127: }
5128:
5129: #
5130: # Rest of the restrictions depend on selected course
5131: #
5132:
1.620 albertel 5133: unless ($env{'request.course.id'}) {
1.766 albertel 5134: if ($thisallowed eq 'A') {
5135: return 'A';
1.814 raeburn 5136: } elsif ($thisallowed eq 'B') {
5137: return 'B';
1.766 albertel 5138: } else {
5139: return '1';
5140: }
1.52 www 5141: }
1.29 www 5142:
1.52 www 5143: #
5144: # Now user is definitely in a course
5145: #
1.53 www 5146:
5147:
5148: # Course preferences
5149:
5150: if ($thisallowed=~/C/) {
1.620 albertel 5151: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5152: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5153: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5154: =~/\Q$rolecode\E/) {
1.689 albertel 5155: if ($priv ne 'pch') {
5156: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5157: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5158: $env{'request.course.id'});
5159: }
1.237 www 5160: return '';
5161: }
5162:
1.620 albertel 5163: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5164: =~/\Q$unamedom\E/) {
1.689 albertel 5165: if ($priv ne 'pch') {
5166: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5167: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5168: $env{'request.course.id'});
5169: }
1.54 www 5170: return '';
5171: }
1.53 www 5172: }
5173:
5174: # Resource preferences
5175:
5176: if ($thisallowed=~/R/) {
1.620 albertel 5177: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5178: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5179: if ($priv ne 'pch') {
5180: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5181: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5182: }
5183: return '';
1.54 www 5184: }
1.53 www 5185: }
1.30 www 5186:
1.246 www 5187: # Restricted by state or randomout?
1.30 www 5188:
1.52 www 5189: if ($thisallowed=~/X/) {
1.620 albertel 5190: if ($env{'acc.randomout'}) {
1.579 albertel 5191: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5192: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5193: return '';
5194: }
1.247 www 5195: }
5196: if (&condval($statecond)) {
1.52 www 5197: return '2';
5198: } else {
5199: return '';
5200: }
5201: }
1.30 www 5202:
1.766 albertel 5203: if ($thisallowed eq 'A') {
5204: return 'A';
1.814 raeburn 5205: } elsif ($thisallowed eq 'B') {
5206: return 'B';
1.766 albertel 5207: }
1.52 www 5208: return 'F';
1.232 www 5209: }
5210:
1.710 albertel 5211: sub split_uri_for_cond {
5212: my $uri=&deversion(&declutter(shift));
5213: my @uriparts=split(/\//,$uri);
5214: my $filename=pop(@uriparts);
5215: my $pathname=join('/',@uriparts);
5216: return ($pathname,$filename);
5217: }
1.232 www 5218: # --------------------------------------------------- Is a resource on the map?
5219:
5220: sub is_on_map {
1.710 albertel 5221: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5222: #Trying to find the conditional for the file
1.620 albertel 5223: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5224: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5225: if ($match) {
1.289 bowersj2 5226: return (1,$1);
5227: } else {
1.434 www 5228: return (0,0);
1.289 bowersj2 5229: }
1.12 www 5230: }
5231:
1.427 www 5232: # --------------------------------------------------------- Get symb from alias
5233:
5234: sub get_symb_from_alias {
5235: my $symb=shift;
5236: my ($map,$resid,$url)=&decode_symb($symb);
5237: # Already is a symb
5238: if ($url) { return $symb; }
5239: # Must be an alias
5240: my $aliassymb='';
5241: my %bighash;
1.620 albertel 5242: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5243: &GDBM_READER(),0640)) {
5244: my $rid=$bighash{'mapalias_'.$symb};
5245: if ($rid) {
5246: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5247: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5248: $resid,$bighash{'src_'.$rid});
1.427 www 5249: }
5250: untie %bighash;
5251: }
5252: return $aliassymb;
5253: }
5254:
1.12 www 5255: # ----------------------------------------------------------------- Define Role
5256:
5257: sub definerole {
5258: if (allowed('mcr','/')) {
5259: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5260: foreach my $role (split(':',$sysrole)) {
5261: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5262: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5263: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5264: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5265: return "refused:s:$crole&$cqual";
5266: }
5267: }
1.191 harris41 5268: }
1.800 albertel 5269: foreach my $role (split(':',$domrole)) {
5270: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5271: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5272: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5273: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5274: return "refused:d:$crole&$cqual";
5275: }
5276: }
1.191 harris41 5277: }
1.800 albertel 5278: foreach my $role (split(':',$courole)) {
5279: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5280: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5281: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5282: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5283: return "refused:c:$crole&$cqual";
5284: }
5285: }
1.191 harris41 5286: }
1.620 albertel 5287: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5288: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5289: "rolesdef_$rolename=".
5290: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5291: return reply($command,$env{'user.home'});
1.12 www 5292: } else {
5293: return 'refused';
5294: }
1.105 harris41 5295: }
5296:
5297: # ---------------- Make a metadata query against the network of library servers
5298:
5299: sub metadata_query {
1.244 matthew 5300: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5301: my %rhash;
1.845 albertel 5302: my %libserv = &all_library();
1.244 matthew 5303: my @server_list = (defined($server_array) ? @$server_array
5304: : keys(%libserv) );
5305: for my $server (@server_list) {
1.118 harris41 5306: unless ($custom or $customshow) {
5307: my $reply=&reply("querysend:".&escape($query),$server);
5308: $rhash{$server}=$reply;
5309: }
5310: else {
5311: my $reply=&reply("querysend:".&escape($query).':'.
5312: &escape($custom).':'.&escape($customshow),
5313: $server);
5314: $rhash{$server}=$reply;
5315: }
1.112 harris41 5316: }
1.118 harris41 5317: return \%rhash;
1.240 www 5318: }
5319:
5320: # ----------------------------------------- Send log queries and wait for reply
5321:
5322: sub log_query {
5323: my ($uname,$udom,$query,%filters)=@_;
5324: my $uhome=&homeserver($uname,$udom);
5325: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5326: my $uhost=&hostname($uhome);
1.800 albertel 5327: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5328: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5329: $uhome);
1.479 albertel 5330: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5331: return get_query_reply($queryid);
5332: }
5333:
1.818 raeburn 5334: # -------------------------- Update MySQL table for portfolio file
5335:
5336: sub update_portfolio_table {
1.821 raeburn 5337: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5338: if ($group ne '') {
5339: $file_name =~s /^\Q$group\E//;
5340: }
1.818 raeburn 5341: my $homeserver = &homeserver($uname,$udom);
5342: my $queryid=
1.821 raeburn 5343: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5344: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5345: my $reply = &get_query_reply($queryid);
5346: return $reply;
5347: }
5348:
1.899 raeburn 5349: # -------------------------- Update MySQL allusers table
5350:
5351: sub update_allusers_table {
5352: my ($uname,$udom,$names) = @_;
5353: my $homeserver = &homeserver($uname,$udom);
5354: my $queryid=
5355: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5356: 'lastname='.&escape($names->{'lastname'}).'%%'.
5357: 'firstname='.&escape($names->{'firstname'}).'%%'.
5358: 'middlename='.&escape($names->{'middlename'}).'%%'.
5359: 'generation='.&escape($names->{'generation'}).'%%'.
5360: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5361: 'id='.&escape($names->{'id'}),$homeserver);
5362: my $reply = &get_query_reply($queryid);
5363: return $reply;
5364: }
5365:
1.508 raeburn 5366: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5367:
5368: sub fetch_enrollment_query {
1.511 raeburn 5369: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5370: my $homeserver;
1.547 raeburn 5371: my $maxtries = 1;
1.508 raeburn 5372: if ($context eq 'automated') {
5373: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5374: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5375: } else {
5376: $homeserver = &homeserver($cnum,$dom);
5377: }
1.838 albertel 5378: my $host=&hostname($homeserver);
1.506 raeburn 5379: my $cmd = '';
1.1000 raeburn 5380: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5381: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5382: }
5383: $cmd =~ s/%%$//;
5384: $cmd = &escape($cmd);
5385: my $query = 'fetchenrollment';
1.620 albertel 5386: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5387: unless ($queryid=~/^\Q$host\E\_/) {
5388: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5389: return 'error: '.$queryid;
5390: }
1.506 raeburn 5391: my $reply = &get_query_reply($queryid);
1.547 raeburn 5392: my $tries = 1;
5393: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5394: $reply = &get_query_reply($queryid);
5395: $tries ++;
5396: }
1.526 raeburn 5397: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5398: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5399: } else {
1.901 albertel 5400: my @responses = split(/:/,$reply);
1.515 raeburn 5401: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5402: foreach my $line (@responses) {
5403: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5404: $$replyref{$key} = $value;
5405: }
5406: } else {
1.506 raeburn 5407: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5408: foreach my $line (@responses) {
5409: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5410: $$replyref{$key} = $value;
5411: if ($value > 0) {
1.800 albertel 5412: foreach my $item (@{$$affiliatesref{$key}}) {
5413: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5414: my $destname = $pathname.'/'.$filename;
5415: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5416: if ($xml_classlist =~ /^error/) {
5417: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5418: } else {
1.506 raeburn 5419: if ( open(FILE,">$destname") ) {
5420: print FILE &unescape($xml_classlist);
5421: close(FILE);
1.526 raeburn 5422: } else {
5423: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5424: }
5425: }
5426: }
5427: }
5428: }
5429: }
5430: return 'ok';
5431: }
5432: return 'error';
5433: }
5434:
1.242 www 5435: sub get_query_reply {
5436: my $queryid=shift;
1.240 www 5437: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5438: my $reply='';
5439: for (1..100) {
5440: sleep 2;
5441: if (-e $replyfile.'.end') {
1.448 albertel 5442: if (open(my $fh,$replyfile)) {
1.904 albertel 5443: $reply = join('',<$fh>);
5444: close($fh);
1.240 www 5445: } else { return 'error: reply_file_error'; }
1.242 www 5446: return &unescape($reply);
5447: }
1.240 www 5448: }
1.242 www 5449: return 'timeout:'.$queryid;
1.240 www 5450: }
5451:
5452: sub courselog_query {
1.241 www 5453: #
5454: # possible filters:
5455: # url: url or symb
5456: # username
5457: # domain
5458: # action: view, submit, grade
5459: # start: timestamp
5460: # end: timestamp
5461: #
1.240 www 5462: my (%filters)=@_;
1.620 albertel 5463: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5464: if ($filters{'url'}) {
5465: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5466: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5467: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5468: }
1.620 albertel 5469: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5470: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5471: return &log_query($cname,$cdom,'courselog',%filters);
5472: }
5473:
5474: sub userlog_query {
1.858 raeburn 5475: #
5476: # possible filters:
5477: # action: log check role
5478: # start: timestamp
5479: # end: timestamp
5480: #
1.240 www 5481: my ($uname,$udom,%filters)=@_;
5482: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5483: }
5484:
1.506 raeburn 5485: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5486:
5487: sub auto_run {
1.508 raeburn 5488: my ($cnum,$cdom) = @_;
1.876 raeburn 5489: my $response = 0;
5490: my $settings;
5491: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5492: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5493: $settings = $domconfig{'autoenroll'};
5494: if ($settings->{'run'} eq '1') {
5495: $response = 1;
5496: }
5497: } else {
1.934 raeburn 5498: my $homeserver;
5499: if (&is_course($cdom,$cnum)) {
5500: $homeserver = &homeserver($cnum,$cdom);
5501: } else {
5502: $homeserver = &domain($cdom,'primary');
5503: }
5504: if ($homeserver ne 'no_host') {
5505: $response = &reply('autorun:'.$cdom,$homeserver);
5506: }
1.876 raeburn 5507: }
1.506 raeburn 5508: return $response;
5509: }
1.776 albertel 5510:
1.506 raeburn 5511: sub auto_get_sections {
1.508 raeburn 5512: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5513: my $homeserver;
5514: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5515: $homeserver = &homeserver($cnum,$cdom);
5516: }
5517: if (!defined($homeserver)) {
5518: if ($cdom =~ /^$match_domain$/) {
5519: $homeserver = &domain($cdom,'primary');
5520: }
5521: }
5522: my @secs;
5523: if (defined($homeserver)) {
5524: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5525: unless ($response eq 'refused') {
5526: @secs = split(/:/,$response);
5527: }
1.506 raeburn 5528: }
5529: return @secs;
5530: }
1.776 albertel 5531:
1.506 raeburn 5532: sub auto_new_course {
1.508 raeburn 5533: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5534: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5535: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5536: return $response;
5537: }
1.776 albertel 5538:
1.506 raeburn 5539: sub auto_validate_courseID {
1.508 raeburn 5540: my ($cnum,$cdom,$inst_course_id) = @_;
5541: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5542: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5543: return $response;
5544: }
1.776 albertel 5545:
1.1007 raeburn 5546: sub auto_validate_instcode {
5547: my ($cnum,$cdom,$instcode,$owner) = @_;
5548: my ($homeserver,$response);
5549: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5550: $homeserver = &homeserver($cnum,$cdom);
5551: }
5552: if (!defined($homeserver)) {
5553: if ($cdom =~ /^$match_domain$/) {
5554: $homeserver = &domain($cdom,'primary');
5555: }
5556: }
5557: my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5558: &escape($instcode).':'.&escape($owner),$homeserver));
5559: return $response;
5560: }
5561:
1.506 raeburn 5562: sub auto_create_password {
1.873 raeburn 5563: my ($cnum,$cdom,$authparam,$udom) = @_;
5564: my ($homeserver,$response);
1.506 raeburn 5565: my $create_passwd = 0;
5566: my $authchk = '';
1.873 raeburn 5567: if ($udom =~ /^$match_domain$/) {
5568: $homeserver = &domain($udom,'primary');
5569: }
5570: if ($homeserver eq '') {
5571: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5572: $homeserver = &homeserver($cnum,$cdom);
5573: }
5574: }
5575: if ($homeserver eq '') {
5576: $authchk = 'nodomain';
1.506 raeburn 5577: } else {
1.873 raeburn 5578: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5579: if ($response eq 'refused') {
5580: $authchk = 'refused';
5581: } else {
1.901 albertel 5582: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5583: }
1.506 raeburn 5584: }
5585: return ($authparam,$create_passwd,$authchk);
5586: }
5587:
1.706 raeburn 5588: sub auto_photo_permission {
5589: my ($cnum,$cdom,$students) = @_;
5590: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5591: my ($outcome,$perm_reqd,$conditions) =
5592: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5593: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5594: return (undef,undef);
5595: }
1.706 raeburn 5596: return ($outcome,$perm_reqd,$conditions);
5597: }
5598:
5599: sub auto_checkphotos {
5600: my ($uname,$udom,$pid) = @_;
5601: my $homeserver = &homeserver($uname,$udom);
5602: my ($result,$resulttype);
5603: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5604: &escape($uname).':'.&escape($pid),
5605: $homeserver));
1.709 albertel 5606: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5607: return (undef,undef);
5608: }
1.706 raeburn 5609: if ($outcome) {
5610: ($result,$resulttype) = split(/:/,$outcome);
5611: }
5612: return ($result,$resulttype);
5613: }
5614:
5615: sub auto_photochoice {
5616: my ($cnum,$cdom) = @_;
5617: my $homeserver = &homeserver($cnum,$cdom);
5618: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5619: &escape($cdom),
5620: $homeserver)));
1.709 albertel 5621: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5622: return (undef,undef);
5623: }
1.706 raeburn 5624: return ($update,$comment);
5625: }
5626:
5627: sub auto_photoupdate {
5628: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5629: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5630: my $host=&hostname($homeserver);
1.706 raeburn 5631: my $cmd = '';
5632: my $maxtries = 1;
1.800 albertel 5633: foreach my $affiliate (keys(%{$affiliatesref})) {
5634: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5635: }
5636: $cmd =~ s/%%$//;
5637: $cmd = &escape($cmd);
5638: my $query = 'institutionalphotos';
5639: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5640: unless ($queryid=~/^\Q$host\E\_/) {
5641: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5642: return 'error: '.$queryid;
5643: }
5644: my $reply = &get_query_reply($queryid);
5645: my $tries = 1;
5646: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5647: $reply = &get_query_reply($queryid);
5648: $tries ++;
5649: }
5650: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5651: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5652: } else {
5653: my @responses = split(/:/,$reply);
5654: my $outcome = shift(@responses);
5655: foreach my $item (@responses) {
5656: my ($key,$value) = split(/=/,$item);
5657: $$photo{$key} = $value;
5658: }
5659: return $outcome;
5660: }
5661: return 'error';
5662: }
5663:
1.521 raeburn 5664: sub auto_instcode_format {
1.793 albertel 5665: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5666: $cat_order) = @_;
1.521 raeburn 5667: my $courses = '';
1.772 raeburn 5668: my @homeservers;
1.521 raeburn 5669: if ($caller eq 'global') {
1.841 albertel 5670: my %servers = &get_servers($codedom,'library');
5671: foreach my $tryserver (keys(%servers)) {
5672: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5673: push(@homeservers,$tryserver);
5674: }
1.584 raeburn 5675: }
1.521 raeburn 5676: } else {
1.772 raeburn 5677: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5678: }
1.793 albertel 5679: foreach my $code (keys(%{$instcodes})) {
5680: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5681: }
5682: chop($courses);
1.772 raeburn 5683: my $ok_response = 0;
5684: my $response;
5685: while (@homeservers > 0 && $ok_response == 0) {
5686: my $server = shift(@homeservers);
5687: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5688: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5689: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5690: split(/:/,$response);
1.772 raeburn 5691: %{$codes} = (%{$codes},&str2hash($codes_str));
5692: push(@{$codetitles},&str2array($codetitles_str));
5693: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5694: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5695: $ok_response = 1;
5696: }
5697: }
5698: if ($ok_response) {
1.521 raeburn 5699: return 'ok';
1.772 raeburn 5700: } else {
5701: return $response;
1.521 raeburn 5702: }
5703: }
5704:
1.792 raeburn 5705: sub auto_instcode_defaults {
5706: my ($domain,$returnhash,$code_order) = @_;
5707: my @homeservers;
1.841 albertel 5708:
5709: my %servers = &get_servers($domain,'library');
5710: foreach my $tryserver (keys(%servers)) {
5711: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5712: push(@homeservers,$tryserver);
5713: }
1.792 raeburn 5714: }
1.841 albertel 5715:
1.792 raeburn 5716: my $response;
1.841 albertel 5717: foreach my $server (@homeservers) {
1.792 raeburn 5718: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5719: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5720:
5721: foreach my $pair (split(/\&/,$response)) {
5722: my ($name,$value)=split(/\=/,$pair);
5723: if ($name eq 'code_order') {
5724: @{$code_order} = split(/\&/,&unescape($value));
5725: } else {
5726: $returnhash->{&unescape($name)}=&unescape($value);
5727: }
5728: }
5729: return 'ok';
1.792 raeburn 5730: }
1.841 albertel 5731:
5732: return $response;
1.1003 raeburn 5733: }
5734:
5735: sub auto_possible_instcodes {
1.1007 raeburn 5736: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
5737: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
5738: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
5739: return;
5740: }
1.1003 raeburn 5741: my (@homeservers,$uhome);
5742: if (defined(&domain($domain,'primary'))) {
5743: $uhome=&domain($domain,'primary');
5744: push(@homeservers,&domain($domain,'primary'));
5745: } else {
5746: my %servers = &get_servers($domain,'library');
5747: foreach my $tryserver (keys(%servers)) {
5748: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5749: push(@homeservers,$tryserver);
5750: }
5751: }
5752: }
5753: my $response;
5754: foreach my $server (@homeservers) {
5755: $response=&reply('autopossibleinstcodes:'.$domain,$server);
5756: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 5757: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
5758: split(':',$response);
5759: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
5760: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 5761: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 5762: my ($name,$value)=split('=',$item);
5763: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5764: }
5765: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 5766: my ($name,$value)=split('=',$item);
5767: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5768: }
5769: return 'ok';
5770: }
5771: return $response;
5772: }
1.792 raeburn 5773:
1.1010 ! raeburn 5774: sub auto_courserequest_checks {
! 5775: my ($dom) = @_;
! 5776: my %validations;
! 5777: return %validations;
! 5778: }
! 5779:
1.777 albertel 5780: sub auto_validate_class_sec {
1.918 raeburn 5781: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5782: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5783: my $ownerlist;
5784: if (ref($owners) eq 'ARRAY') {
5785: $ownerlist = join(',',@{$owners});
5786: } else {
5787: $ownerlist = $owners;
5788: }
1.773 raeburn 5789: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5790: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5791: return $response;
5792: }
5793:
1.679 raeburn 5794: # ------------------------------------------------------- Course Group routines
5795:
5796: sub get_coursegroups {
1.809 raeburn 5797: my ($cdom,$cnum,$group,$namespace) = @_;
5798: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5799: }
5800:
1.679 raeburn 5801: sub modify_coursegroup {
5802: my ($cdom,$cnum,$groupsettings) = @_;
5803: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5804: }
5805:
1.809 raeburn 5806: sub toggle_coursegroup_status {
5807: my ($cdom,$cnum,$group,$action) = @_;
5808: my ($from_namespace,$to_namespace);
5809: if ($action eq 'delete') {
5810: $from_namespace = 'coursegroups';
5811: $to_namespace = 'deleted_groups';
5812: } else {
5813: $from_namespace = 'deleted_groups';
5814: $to_namespace = 'coursegroups';
5815: }
5816: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5817: if (my $tmp = &error(%curr_group)) {
5818: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5819: return ('read error',$tmp);
5820: } else {
5821: my %savedsettings = %curr_group;
1.809 raeburn 5822: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5823: my $deloutcome;
5824: if ($result eq 'ok') {
1.809 raeburn 5825: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5826: } else {
5827: return ('write error',$result);
5828: }
5829: if ($deloutcome eq 'ok') {
5830: return 'ok';
5831: } else {
5832: return ('delete error',$deloutcome);
5833: }
5834: }
5835: }
5836:
1.679 raeburn 5837: sub modify_group_roles {
1.957 raeburn 5838: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 5839: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5840: my $role = 'gr/'.&escape($userprivs);
5841: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 5842: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 5843: if ($result eq 'ok') {
5844: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5845: }
1.679 raeburn 5846: return $result;
5847: }
5848:
5849: sub modify_coursegroup_membership {
5850: my ($cdom,$cnum,$membership) = @_;
5851: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5852: return $result;
5853: }
5854:
1.682 raeburn 5855: sub get_active_groups {
5856: my ($udom,$uname,$cdom,$cnum) = @_;
5857: my $now = time;
5858: my %groups = ();
5859: foreach my $key (keys(%env)) {
1.811 albertel 5860: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5861: my ($start,$end) = split(/\./,$env{$key});
5862: if (($end!=0) && ($end<$now)) { next; }
5863: if (($start!=0) && ($start>$now)) { next; }
5864: if ($1 eq $cdom && $2 eq $cnum) {
5865: $groups{$3} = $env{$key} ;
5866: }
5867: }
5868: }
5869: return %groups;
5870: }
5871:
1.683 raeburn 5872: sub get_group_membership {
5873: my ($cdom,$cnum,$group) = @_;
5874: return(&dump('groupmembership',$cdom,$cnum,$group));
5875: }
5876:
5877: sub get_users_groups {
5878: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5879: my @usersgroups;
1.683 raeburn 5880: my $cachetime=1800;
5881:
5882: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5883: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5884: if (defined($cached)) {
1.734 albertel 5885: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5886: } else {
5887: $grouplist = '';
1.816 raeburn 5888: my $courseurl = &courseid_to_courseurl($courseid);
5889: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5890: my $access_end = $env{'course.'.$courseid.
5891: '.default_enrollment_end_date'};
5892: my $now = time;
5893: foreach my $key (keys(%roleshash)) {
5894: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5895: my $group = $1;
5896: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5897: my $start = $2;
5898: my $end = $1;
5899: if ($start == -1) { next; } # deleted from group
5900: if (($start!=0) && ($start>$now)) { next; }
5901: if (($end!=0) && ($end<$now)) {
5902: if ($access_end && $access_end < $now) {
5903: if ($access_end - $end < 86400) {
5904: push(@usersgroups,$group);
1.733 raeburn 5905: }
5906: }
1.817 raeburn 5907: next;
1.733 raeburn 5908: }
1.817 raeburn 5909: push(@usersgroups,$group);
1.683 raeburn 5910: }
5911: }
5912: }
1.817 raeburn 5913: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5914: $grouplist = join(':',@usersgroups);
5915: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5916: }
1.733 raeburn 5917: return @usersgroups;
1.683 raeburn 5918: }
5919:
5920: sub devalidate_getgroups_cache {
5921: my ($udom,$uname,$cdom,$cnum)=@_;
5922: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5923:
1.683 raeburn 5924: my $hashid="$udom:$uname:$courseid";
5925: &devalidate_cache_new('getgroups',$hashid);
5926: }
5927:
1.12 www 5928: # ------------------------------------------------------------------ Plain Text
5929:
5930: sub plaintext {
1.988 raeburn 5931: my ($short,$type,$cid,$forcedefault) = @_;
1.758 albertel 5932: if ($short =~ /^cr/) {
5933: return (split('/',$short))[-1];
5934: }
1.742 raeburn 5935: if (!defined($cid)) {
5936: $cid = $env{'request.course.id'};
5937: }
1.988 raeburn 5938: if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
5939: unless ($forcedefault) {
5940: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
5941: &Apache::lonlocal::mt_escape(\$roletext);
5942: return &Apache::lonlocal::mt($roletext);
5943: }
1.742 raeburn 5944: }
5945: my %rolenames = (
1.1008 raeburn 5946: Course => 'std',
5947: Community => 'alt1',
1.742 raeburn 5948: );
5949: if (defined($type) &&
5950: defined($rolenames{$type}) &&
5951: defined($prp{$short}{$rolenames{$type}})) {
5952: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5953: } else {
5954: return &Apache::lonlocal::mt($prp{$short}{'std'});
5955: }
1.12 www 5956: }
5957:
5958: # ----------------------------------------------------------------- Assign Role
5959:
5960: sub assignrole {
1.957 raeburn 5961: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
5962: $context)=@_;
1.21 www 5963: my $mrole;
5964: if ($role =~ /^cr\//) {
1.393 www 5965: my $cwosec=$url;
1.811 albertel 5966: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5967: unless (&allowed('ccr',$cwosec)) {
1.104 www 5968: &logthis('Refused custom assignrole: '.
5969: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5970: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5971: return 'refused';
5972: }
1.21 www 5973: $mrole='cr';
1.678 raeburn 5974: } elsif ($role =~ /^gr\//) {
5975: my $cwogrp=$url;
1.811 albertel 5976: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5977: unless (&allowed('mdg',$cwogrp)) {
5978: &logthis('Refused group assignrole: '.
5979: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5980: $env{'user.name'}.' at '.$env{'user.domain'});
5981: return 'refused';
5982: }
5983: $mrole='gr';
1.21 www 5984: } else {
1.82 www 5985: my $cwosec=$url;
1.811 albertel 5986: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 5987: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
5988: my $refused;
5989: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
5990: if (!(&allowed('c'.$role,$url))) {
5991: $refused = 1;
5992: }
5993: } else {
5994: $refused = 1;
5995: }
1.947 raeburn 5996: if ($refused) {
5997: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5998: $refused = '';
5999: } else {
6000: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6001: ' '.$role.' '.$end.' '.$start.' by '.
6002: $env{'user.name'}.' at '.$env{'user.domain'});
6003: return 'refused';
6004: }
1.932 raeburn 6005: }
1.104 www 6006: }
1.21 www 6007: $mrole=$role;
6008: }
1.620 albertel 6009: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6010: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6011: if ($end) { $command.='_'.$end; }
1.21 www 6012: if ($start) {
6013: if ($end) {
1.81 www 6014: $command.='_'.$start;
1.21 www 6015: } else {
1.81 www 6016: $command.='_0_'.$start;
1.21 www 6017: }
6018: }
1.739 raeburn 6019: my $origstart = $start;
6020: my $origend = $end;
1.957 raeburn 6021: my $delflag;
1.357 www 6022: # actually delete
6023: if ($deleteflag) {
1.373 www 6024: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6025: # modify command to delete the role
1.620 albertel 6026: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6027: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6028: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6029: # set start and finish to negative values for userrolelog
6030: $start=-1;
6031: $end=-1;
1.957 raeburn 6032: $delflag = 1;
1.357 www 6033: }
6034: }
6035: # send command
1.349 www 6036: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6037: # log new user role if status is ok
1.349 www 6038: if ($answer eq 'ok') {
1.663 raeburn 6039: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6040: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6041: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6042: unless ($role =~ /^gr/) {
6043: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6044: $origstart,$selfenroll,$context);
1.739 raeburn 6045: }
1.349 www 6046: }
6047: return $answer;
1.169 harris41 6048: }
6049:
6050: # -------------------------------------------------- Modify user authentication
1.197 www 6051: # Overrides without validation
6052:
1.169 harris41 6053: sub modifyuserauth {
6054: my ($udom,$uname,$umode,$upass)=@_;
6055: my $uhome=&homeserver($uname,$udom);
1.197 www 6056: unless (&allowed('mau',$udom)) { return 'refused'; }
6057: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6058: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6059: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6060: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6061: &escape($upass),$uhome);
1.620 albertel 6062: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6063: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6064: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6065: &log($udom,,$uname,$uhome,
1.620 albertel 6066: 'Authentication changed by '.$env{'user.domain'}.', '.
6067: $env{'user.name'}.', '.$umode.
1.197 www 6068: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6069: unless ($reply eq 'ok') {
1.197 www 6070: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6071: return 'error: '.$reply;
6072: }
1.170 harris41 6073: return 'ok';
1.80 www 6074: }
6075:
1.81 www 6076: # --------------------------------------------------------------- Modify a user
1.80 www 6077:
1.81 www 6078: sub modifyuser {
1.206 matthew 6079: my ($udom, $uname, $uid,
6080: $umode, $upass, $first,
6081: $middle, $last, $gene,
1.963 raeburn 6082: $forceid, $desiredhome, $email, $inststatus)=@_;
1.807 albertel 6083: $udom= &LONCAPA::clean_domain($udom);
6084: $uname=&LONCAPA::clean_username($uname);
1.81 www 6085: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6086: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 6087: $last.', '.$gene.'(forceid: '.$forceid.')'.
6088: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6089: ' desiredhome not specified').
1.620 albertel 6090: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6091: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6092: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 6093: # ----------------------------------------------------------------- Create User
1.406 albertel 6094: if (($uhome eq 'no_host') &&
6095: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6096: my $unhome='';
1.844 albertel 6097: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6098: $unhome = $desiredhome;
1.620 albertel 6099: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6100: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6101: } else { # load balancing routine for determining $unhome
1.81 www 6102: my $loadm=10000000;
1.841 albertel 6103: my %servers = &get_servers($udom,'library');
6104: foreach my $tryserver (keys(%servers)) {
6105: my $answer=reply('load',$tryserver);
6106: if (($answer=~/\d+/) && ($answer<$loadm)) {
6107: $loadm=$answer;
6108: $unhome=$tryserver;
6109: }
1.80 www 6110: }
6111: }
6112: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6113: return 'error: unable to find a home server for '.$uname.
6114: ' in domain '.$udom;
1.80 www 6115: }
6116: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6117: &escape($upass),$unhome);
6118: unless ($reply eq 'ok') {
6119: return 'error: '.$reply;
6120: }
1.230 stredwic 6121: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6122: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6123: return 'error: unable verify users home machine.';
1.80 www 6124: }
1.209 matthew 6125: } # End of creation of new user
1.80 www 6126: # ---------------------------------------------------------------------- Add ID
6127: if ($uid) {
6128: $uid=~tr/A-Z/a-z/;
6129: my %uidhash=&idrget($udom,$uname);
1.196 www 6130: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6131: && (!$forceid)) {
1.80 www 6132: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6133: return 'error: user id "'.$uid.'" does not match '.
6134: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6135: }
6136: } else {
6137: &idput($udom,($uname => $uid));
6138: }
6139: }
6140: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6141: my @tmp=&get('environment',
1.899 raeburn 6142: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6143: 'permanentemail','inststatus'],
1.134 albertel 6144: $udom,$uname);
1.313 matthew 6145: my %names;
6146: if ($tmp[0] =~ m/^error:.*/) {
6147: %names=();
6148: } else {
6149: %names = @tmp;
6150: }
1.388 www 6151: #
6152: # Make sure to not trash student environment if instructor does not bother
6153: # to supply name and email information
6154: #
6155: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6156: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6157: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6158: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6159: if ($email) {
6160: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6161: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6162: }
1.899 raeburn 6163: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6164: if (defined($inststatus)) {
6165: $names{'inststatus'} = '';
6166: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6167: if (ref($usertypes) eq 'HASH') {
6168: my @okstatuses;
6169: foreach my $item (split(/:/,$inststatus)) {
6170: if (defined($usertypes->{$item})) {
6171: push(@okstatuses,$item);
6172: }
6173: }
6174: if (@okstatuses) {
6175: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6176: }
6177: }
6178: }
1.134 albertel 6179: my $reply = &put('environment', \%names, $udom,$uname);
6180: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 6181: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 6182: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 6183: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6184: $umode.', '.$first.', '.$middle.', '.
6185: $last.', '.$gene.', '.$email.', '.$inststatus;
6186: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6187: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6188: } else {
6189: $logmsg .= ' during self creation';
6190: }
6191: &logthis($logmsg);
1.134 albertel 6192: return 'ok';
1.80 www 6193: }
6194:
1.81 www 6195: # -------------------------------------------------------------- Modify student
1.80 www 6196:
1.81 www 6197: sub modifystudent {
6198: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6199: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6200: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6201: if (!$cid) {
1.620 albertel 6202: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6203: return 'not_in_class';
6204: }
1.80 www 6205: }
6206: # --------------------------------------------------------------- Make the user
1.81 www 6207: my $reply=&modifyuser
1.209 matthew 6208: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6209: $desiredhome,$email,$inststatus);
1.80 www 6210: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6211: # This will cause &modify_student_enrollment to get the uid from the
6212: # students environment
6213: $uid = undef if (!$forceid);
1.455 albertel 6214: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6215: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6216: return $reply;
6217: }
6218:
6219: sub modify_student_enrollment {
1.957 raeburn 6220: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6221: my ($cdom,$cnum,$chome);
6222: if (!$cid) {
1.620 albertel 6223: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6224: return 'not_in_class';
6225: }
1.620 albertel 6226: $cdom=$env{'course.'.$cid.'.domain'};
6227: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6228: } else {
6229: ($cdom,$cnum)=split(/_/,$cid);
6230: }
1.620 albertel 6231: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6232: if (!$chome) {
1.457 raeburn 6233: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6234: }
1.455 albertel 6235: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6236: # Make sure the user exists
1.81 www 6237: my $uhome=&homeserver($uname,$udom);
6238: if (($uhome eq '') || ($uhome eq 'no_host')) {
6239: return 'error: no such user';
6240: }
1.297 matthew 6241: # Get student data if we were not given enough information
6242: if (!defined($first) || $first eq '' ||
6243: !defined($last) || $last eq '' ||
6244: !defined($uid) || $uid eq '' ||
6245: !defined($middle) || $middle eq '' ||
6246: !defined($gene) || $gene eq '') {
1.294 matthew 6247: # They did not supply us with enough data to enroll the student, so
6248: # we need to pick up more information.
1.297 matthew 6249: my %tmp = &get('environment',
1.294 matthew 6250: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6251: ,$udom,$uname);
6252:
1.800 albertel 6253: #foreach my $key (keys(%tmp)) {
6254: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6255: #}
1.294 matthew 6256: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6257: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6258: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6259: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6260: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6261: }
1.556 albertel 6262: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6263: my $reply=cput('classlist',
6264: {"$uname:$udom" =>
1.515 raeburn 6265: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6266: $cdom,$cnum);
1.81 www 6267: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6268: return 'error: '.$reply;
1.652 albertel 6269: } else {
6270: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6271: }
1.297 matthew 6272: # Add student role to user
1.83 www 6273: my $uurl='/'.$cid;
1.81 www 6274: $uurl=~s/\_/\//g;
6275: if ($usec) {
6276: $uurl.='/'.$usec;
6277: }
1.957 raeburn 6278: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6279: }
6280:
1.556 albertel 6281: sub format_name {
6282: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6283: my $name;
6284: if ($first ne 'lastname') {
6285: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6286: } else {
6287: if ($lastname=~/\S/) {
6288: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6289: $name=~s/\s+,/,/;
6290: } else {
6291: $name.= $firstname.' '.$middlename.' '.$generation;
6292: }
6293: }
6294: $name=~s/^\s+//;
6295: $name=~s/\s+$//;
6296: $name=~s/\s+/ /g;
6297: return $name;
6298: }
6299:
1.84 www 6300: # ------------------------------------------------- Write to course preferences
6301:
6302: sub writecoursepref {
6303: my ($courseid,%prefs)=@_;
6304: $courseid=~s/^\///;
6305: $courseid=~s/\_/\//g;
6306: my ($cdomain,$cnum)=split(/\//,$courseid);
6307: my $chome=homeserver($cnum,$cdomain);
6308: if (($chome eq '') || ($chome eq 'no_host')) {
6309: return 'error: no such course';
6310: }
6311: my $cstring='';
1.800 albertel 6312: foreach my $pref (keys(%prefs)) {
6313: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6314: }
1.84 www 6315: $cstring=~s/\&$//;
6316: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6317: }
6318:
6319: # ---------------------------------------------------------- Make/modify course
6320:
6321: sub createcourse {
1.741 raeburn 6322: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
6323: $course_owner,$crstype)=@_;
1.84 www 6324: $url=&declutter($url);
6325: my $cid='';
1.264 matthew 6326: unless (&allowed('ccc',$udom)) {
1.84 www 6327: return 'refused';
6328: }
6329: # ------------------------------------------------------------------- Create ID
1.674 www 6330: my $uname=int(1+rand(9)).
6331: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6332: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 6333: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6334: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 6335: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6336: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6337: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
6338: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 6339: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6340: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6341: return 'error: unable to generate unique course-ID';
6342: }
6343: }
1.264 matthew 6344: # ------------------------------------------------ Check supplied server name
1.620 albertel 6345: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 6346: if (! &is_library($course_server)) {
1.264 matthew 6347: return 'error:bad server name '.$course_server;
6348: }
1.84 www 6349: # ------------------------------------------------------------- Make the course
6350: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6351: $course_server);
1.84 www 6352: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 6353: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6354: if (($uhome eq '') || ($uhome eq 'no_host')) {
6355: return 'error: no such course';
6356: }
1.271 www 6357: # ----------------------------------------------------------------- Course made
1.516 raeburn 6358: # log existence
1.918 raeburn 6359: my $newcourse = {
6360: $udom.'_'.$uname => {
1.921 raeburn 6361: description => $description,
6362: inst_code => $inst_code,
6363: owner => $course_owner,
6364: type => $crstype,
1.918 raeburn 6365: },
6366: };
1.921 raeburn 6367: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6368: # set toplevel url
1.271 www 6369: my $topurl=$url;
6370: unless ($nonstandard) {
6371: # ------------------------------------------ For standard courses, make top url
6372: my $mapurl=&clutter($url);
1.278 www 6373: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6374: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6375: <map>
6376: <resource id="1" type="start"></resource>
6377: <resource id="2" src="$mapurl"></resource>
6378: <resource id="3" type="finish"></resource>
6379: <link index="1" from="1" to="2"></link>
6380: <link index="2" from="2" to="3"></link>
6381: </map>
6382: ENDINITMAP
6383: $topurl=&declutter(
1.638 albertel 6384: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6385: );
6386: }
6387: # ----------------------------------------------------------- Write preferences
1.84 www 6388: &writecoursepref($udom.'_'.$uname,
6389: ('description' => $description,
1.271 www 6390: 'url' => $topurl));
1.84 www 6391: return '/'.$udom.'/'.$uname;
6392: }
6393:
1.813 albertel 6394: sub is_course {
6395: my ($cdom,$cnum) = @_;
6396: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6397: undef,'.');
1.813 albertel 6398: if (exists($courses{$cdom.'_'.$cnum})) {
6399: return 1;
6400: }
6401: return 0;
6402: }
6403:
1.21 www 6404: # ---------------------------------------------------------- Assign Custom Role
6405:
6406: sub assigncustomrole {
1.957 raeburn 6407: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6408: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6409: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6410: }
6411:
6412: # ----------------------------------------------------------------- Revoke Role
6413:
6414: sub revokerole {
1.957 raeburn 6415: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6416: my $now=time;
1.965 raeburn 6417: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6418: }
6419:
6420: # ---------------------------------------------------------- Revoke Custom Role
6421:
6422: sub revokecustomrole {
1.957 raeburn 6423: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6424: my $now=time;
1.357 www 6425: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6426: $deleteflag,$selfenroll,$context);
1.17 www 6427: }
6428:
1.533 banghart 6429: # ------------------------------------------------------------ Disk usage
1.535 albertel 6430: sub diskusage {
1.955 raeburn 6431: my ($udom,$uname,$directorypath,$getpropath)=@_;
6432: $directorypath =~ s/\/$//;
6433: my $listing=&reply('du2:'.&escape($directorypath).':'
6434: .&escape($getpropath).':'.&escape($uname).':'
6435: .&escape($udom),homeserver($uname,$udom));
6436: if ($listing eq 'unknown_cmd') {
6437: if ($getpropath) {
6438: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6439: }
6440: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6441: }
1.514 albertel 6442: return $listing;
1.512 banghart 6443: }
6444:
1.566 banghart 6445: sub is_locked {
6446: my ($file_name, $domain, $user) = @_;
6447: my @check;
6448: my $is_locked;
6449: push @check, $file_name;
1.613 albertel 6450: my %locked = &get('file_permissions',\@check,
1.620 albertel 6451: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6452: my ($tmp)=keys(%locked);
6453: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6454:
1.566 banghart 6455: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6456: $is_locked = 'false';
6457: foreach my $entry (@{$locked{$file_name}}) {
6458: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6459: $is_locked = 'true';
6460: last;
1.745 raeburn 6461: }
6462: }
1.566 banghart 6463: } else {
6464: $is_locked = 'false';
6465: }
6466: }
6467:
1.759 albertel 6468: sub declutter_portfile {
6469: my ($file) = @_;
1.833 albertel 6470: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6471: return $file;
6472: }
6473:
1.559 banghart 6474: # ------------------------------------------------------------- Mark as Read Only
6475:
6476: sub mark_as_readonly {
6477: my ($domain,$user,$files,$what) = @_;
1.613 albertel 6478: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6479: my ($tmp)=keys(%current_permissions);
6480: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 6481: foreach my $file (@{$files}) {
1.759 albertel 6482: $file = &declutter_portfile($file);
1.561 banghart 6483: push(@{$current_permissions{$file}},$what);
1.559 banghart 6484: }
1.613 albertel 6485: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6486: return;
6487: }
6488:
1.572 banghart 6489: # ------------------------------------------------------------Save Selected Files
6490:
6491: sub save_selected_files {
6492: my ($user, $path, @files) = @_;
6493: my $filename = $user."savedfiles";
1.573 banghart 6494: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 6495: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 6496: foreach my $file (@files) {
1.620 albertel 6497: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 6498: }
6499: foreach my $file (@other_files) {
1.574 banghart 6500: print (OUT $file."\n");
1.572 banghart 6501: }
1.574 banghart 6502: close (OUT);
1.572 banghart 6503: return 'ok';
6504: }
6505:
1.574 banghart 6506: sub clear_selected_files {
6507: my ($user) = @_;
6508: my $filename = $user."savedfiles";
6509: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6510: print (OUT undef);
6511: close (OUT);
6512: return ("ok");
6513: }
6514:
1.572 banghart 6515: sub files_in_path {
6516: my ($user, $path) = @_;
6517: my $filename = $user."savedfiles";
6518: my %return_files;
1.574 banghart 6519: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 6520: while (my $line_in = <IN>) {
1.574 banghart 6521: chomp ($line_in);
6522: my @paths_and_file = split (m!/!, $line_in);
6523: my $file_part = pop (@paths_and_file);
6524: my $path_part = join ('/', @paths_and_file);
1.573 banghart 6525: $path_part.='/';
6526: my $path_and_file = $path_part.$file_part;
6527: if ($path_part eq $path) {
6528: $return_files{$file_part}= 'selected';
6529: }
6530: }
1.574 banghart 6531: close (IN);
6532: return (\%return_files);
1.572 banghart 6533: }
6534:
6535: # called in portfolio select mode, to show files selected NOT in current directory
6536: sub files_not_in_path {
6537: my ($user, $path) = @_;
6538: my $filename = $user."savedfiles";
6539: my @return_files;
6540: my $path_part;
1.800 albertel 6541: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6542: while (my $line = <IN>) {
1.572 banghart 6543: #ok, I know it's clunky, but I want it to work
1.800 albertel 6544: my @paths_and_file = split(m|/|, $line);
6545: my $file_part = pop(@paths_and_file);
6546: chomp($file_part);
6547: my $path_part = join('/', @paths_and_file);
1.572 banghart 6548: $path_part .= '/';
6549: my $path_and_file = $path_part.$file_part;
6550: if ($path_part ne $path) {
1.800 albertel 6551: push(@return_files, ($path_and_file));
1.572 banghart 6552: }
6553: }
1.800 albertel 6554: close(OUT);
1.574 banghart 6555: return (@return_files);
1.572 banghart 6556: }
6557:
1.745 raeburn 6558: #----------------------------------------------Get portfolio file permissions
1.629 banghart 6559:
1.745 raeburn 6560: sub get_portfile_permissions {
6561: my ($domain,$user) = @_;
1.613 albertel 6562: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6563: my ($tmp)=keys(%current_permissions);
6564: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6565: return \%current_permissions;
6566: }
6567:
6568: #---------------------------------------------Get portfolio file access controls
6569:
1.749 raeburn 6570: sub get_access_controls {
1.745 raeburn 6571: my ($current_permissions,$group,$file) = @_;
1.769 albertel 6572: my %access;
6573: my $real_file = $file;
6574: $file =~ s/\.meta$//;
1.745 raeburn 6575: if (defined($file)) {
1.749 raeburn 6576: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6577: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 6578: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 6579: }
6580: }
1.745 raeburn 6581: } else {
1.749 raeburn 6582: foreach my $key (keys(%{$current_permissions})) {
6583: if ($key =~ /\0accesscontrol$/) {
6584: if (defined($group)) {
6585: if ($key !~ m-^\Q$group\E/-) {
6586: next;
6587: }
6588: }
6589: my ($fullpath) = split(/\0/,$key);
6590: if (ref($$current_permissions{$key}) eq 'HASH') {
6591: foreach my $control (keys(%{$$current_permissions{$key}})) {
6592: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6593: }
6594: }
6595: }
6596: }
6597: }
6598: return %access;
6599: }
6600:
6601: sub modify_access_controls {
6602: my ($file_name,$changes,$domain,$user)=@_;
6603: my ($outcome,$deloutcome);
6604: my %store_permissions;
6605: my %new_values;
6606: my %new_control;
6607: my %translation;
6608: my @deletions = ();
6609: my $now = time;
6610: if (exists($$changes{'activate'})) {
6611: if (ref($$changes{'activate'}) eq 'HASH') {
6612: my @newitems = sort(keys(%{$$changes{'activate'}}));
6613: my $numnew = scalar(@newitems);
6614: for (my $i=0; $i<$numnew; $i++) {
6615: my $newkey = $newitems[$i];
6616: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 6617: if ($newkey =~ /^\d+:/) {
6618: $newkey =~ s/^(\d+)/$newid/;
6619: $translation{$1} = $newid;
6620: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6621: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6622: $translation{$1} = $newid;
6623: }
1.749 raeburn 6624: $new_values{$file_name."\0".$newkey} =
6625: $$changes{'activate'}{$newitems[$i]};
6626: $new_control{$newkey} = $now;
6627: }
6628: }
6629: }
6630: my %todelete;
6631: my %changed_items;
6632: foreach my $action ('delete','update') {
6633: if (exists($$changes{$action})) {
6634: if (ref($$changes{$action}) eq 'HASH') {
6635: foreach my $key (keys(%{$$changes{$action}})) {
6636: my ($itemnum) = ($key =~ /^([^:]+):/);
6637: if ($action eq 'delete') {
6638: $todelete{$itemnum} = 1;
6639: } else {
6640: $changed_items{$itemnum} = $key;
6641: }
6642: }
1.745 raeburn 6643: }
6644: }
1.749 raeburn 6645: }
6646: # get lock on access controls for file.
6647: my $lockhash = {
6648: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6649: ':'.$env{'user.domain'},
6650: };
6651: my $tries = 0;
6652: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6653:
6654: while (($gotlock ne 'ok') && $tries <3) {
6655: $tries ++;
6656: sleep 1;
6657: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6658: }
6659: if ($gotlock eq 'ok') {
6660: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6661: my ($tmp)=keys(%curr_permissions);
6662: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6663: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6664: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6665: if (ref($curr_controls) eq 'HASH') {
6666: foreach my $control_item (keys(%{$curr_controls})) {
6667: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6668: if (defined($todelete{$itemnum})) {
6669: push(@deletions,$file_name."\0".$control_item);
6670: } else {
6671: if (defined($changed_items{$itemnum})) {
6672: $new_control{$changed_items{$itemnum}} = $now;
6673: push(@deletions,$file_name."\0".$control_item);
6674: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6675: } else {
6676: $new_control{$control_item} = $$curr_controls{$control_item};
6677: }
6678: }
1.745 raeburn 6679: }
6680: }
6681: }
1.970 raeburn 6682: my ($group);
6683: if (&is_course($domain,$user)) {
6684: ($group,my $file) = split(/\//,$file_name,2);
6685: }
1.749 raeburn 6686: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6687: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6688: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6689: # remove lock
6690: my @del_lock = ($file_name."\0".'locked_access_records');
6691: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 6692: my $sqlresult =
1.970 raeburn 6693: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 6694: $group);
1.749 raeburn 6695: } else {
6696: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 6697: }
1.749 raeburn 6698: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 6699: }
6700:
1.827 raeburn 6701: sub make_public_indefinitely {
6702: my ($requrl) = @_;
6703: my $now = time;
6704: my $action = 'activate';
6705: my $aclnum = 0;
6706: if (&is_portfolio_url($requrl)) {
6707: my (undef,$udom,$unum,$file_name,$group) =
6708: &parse_portfolio_url($requrl);
6709: my $current_perms = &get_portfile_permissions($udom,$unum);
6710: my %access_controls = &get_access_controls($current_perms,
6711: $group,$file_name);
6712: foreach my $key (keys(%{$access_controls{$file_name}})) {
6713: my ($num,$scope,$end,$start) =
6714: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6715: if ($scope eq 'public') {
6716: if ($start <= $now && $end == 0) {
6717: $action = 'none';
6718: } else {
6719: $action = 'update';
6720: $aclnum = $num;
6721: }
6722: last;
6723: }
6724: }
6725: if ($action eq 'none') {
6726: return 'ok';
6727: } else {
6728: my %changes;
6729: my $newend = 0;
6730: my $newstart = $now;
6731: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6732: $changes{$action}{$newkey} = {
6733: type => 'public',
6734: time => {
6735: start => $newstart,
6736: end => $newend,
6737: },
6738: };
6739: my ($outcome,$deloutcome,$new_values,$translation) =
6740: &modify_access_controls($file_name,\%changes,$udom,$unum);
6741: return $outcome;
6742: }
6743: } else {
6744: return 'invalid';
6745: }
6746: }
6747:
1.745 raeburn 6748: #------------------------------------------------------Get Marked as Read Only
6749:
6750: sub get_marked_as_readonly {
6751: my ($domain,$user,$what,$group) = @_;
6752: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 6753: my @readonly_files;
1.629 banghart 6754: my $cmp1=$what;
6755: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 6756: while (my ($file_name,$value) = each(%{$current_permissions})) {
6757: if (defined($group)) {
6758: if ($file_name !~ m-^\Q$group\E/-) {
6759: next;
6760: }
6761: }
1.561 banghart 6762: if (ref($value) eq "ARRAY"){
6763: foreach my $stored_what (@{$value}) {
1.629 banghart 6764: my $cmp2=$stored_what;
1.759 albertel 6765: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 6766: $cmp2=join('',@{$stored_what});
1.745 raeburn 6767: }
1.629 banghart 6768: if ($cmp1 eq $cmp2) {
1.561 banghart 6769: push(@readonly_files, $file_name);
1.745 raeburn 6770: last;
1.563 banghart 6771: } elsif (!defined($what)) {
6772: push(@readonly_files, $file_name);
1.745 raeburn 6773: last;
1.561 banghart 6774: }
6775: }
1.745 raeburn 6776: }
1.561 banghart 6777: }
6778: return @readonly_files;
6779: }
1.577 banghart 6780: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 6781:
1.577 banghart 6782: sub get_marked_as_readonly_hash {
1.745 raeburn 6783: my ($current_permissions,$group,$what) = @_;
1.577 banghart 6784: my %readonly_files;
1.745 raeburn 6785: while (my ($file_name,$value) = each(%{$current_permissions})) {
6786: if (defined($group)) {
6787: if ($file_name !~ m-^\Q$group\E/-) {
6788: next;
6789: }
6790: }
1.577 banghart 6791: if (ref($value) eq "ARRAY"){
6792: foreach my $stored_what (@{$value}) {
1.745 raeburn 6793: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6794: foreach my $lock_descriptor(@{$stored_what}) {
6795: if ($lock_descriptor eq 'graded') {
6796: $readonly_files{$file_name} = 'graded';
6797: } elsif ($lock_descriptor eq 'handback') {
6798: $readonly_files{$file_name} = 'handback';
6799: } else {
6800: if (!exists($readonly_files{$file_name})) {
6801: $readonly_files{$file_name} = 'locked';
6802: }
6803: }
1.745 raeburn 6804: }
1.750 banghart 6805: }
1.577 banghart 6806: }
6807: }
6808: }
6809: return %readonly_files;
6810: }
1.559 banghart 6811: # ------------------------------------------------------------ Unmark as Read Only
6812:
6813: sub unmark_as_readonly {
1.629 banghart 6814: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6815: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6816: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6817: $file_name = &declutter_portfile($file_name);
1.634 albertel 6818: my $symb_crs = $what;
6819: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6820: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6821: my ($tmp)=keys(%current_permissions);
6822: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6823: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6824: foreach my $file (@readonly_files) {
1.759 albertel 6825: my $clean_file = &declutter_portfile($file);
6826: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6827: my $current_locks = $current_permissions{$file};
1.563 banghart 6828: my @new_locks;
6829: my @del_keys;
6830: if (ref($current_locks) eq "ARRAY"){
6831: foreach my $locker (@{$current_locks}) {
1.632 albertel 6832: my $compare=$locker;
1.749 raeburn 6833: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6834: $compare=join('',@{$locker});
1.746 raeburn 6835: if ($compare ne $symb_crs) {
6836: push(@new_locks, $locker);
6837: }
1.563 banghart 6838: }
6839: }
1.650 albertel 6840: if (scalar(@new_locks) > 0) {
1.563 banghart 6841: $current_permissions{$file} = \@new_locks;
6842: } else {
6843: push(@del_keys, $file);
1.613 albertel 6844: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6845: delete($current_permissions{$file});
1.563 banghart 6846: }
6847: }
1.561 banghart 6848: }
1.613 albertel 6849: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6850: return;
6851: }
1.512 banghart 6852:
1.17 www 6853: # ------------------------------------------------------------ Directory lister
6854:
6855: sub dirlist {
1.955 raeburn 6856: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 6857: $uri=~s/^\///;
6858: $uri=~s/\/$//;
1.253 stredwic 6859: my ($udom, $uname);
1.955 raeburn 6860: if ($getuserdir) {
1.253 stredwic 6861: $udom = $userdomain;
6862: $uname = $username;
1.955 raeburn 6863: } else {
6864: (undef,$udom,$uname)=split(/\//,$uri);
6865: if(defined($userdomain)) {
6866: $udom = $userdomain;
6867: }
6868: if(defined($username)) {
6869: $uname = $username;
6870: }
1.253 stredwic 6871: }
1.955 raeburn 6872: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 6873:
1.955 raeburn 6874: $dirRoot = $perlvar{'lonDocRoot'};
6875: if (defined($getpropath)) {
6876: $dirRoot = &propath($udom,$uname);
1.253 stredwic 6877: $dirRoot =~ s/\/$//;
1.955 raeburn 6878: } elsif (defined($getuserdir)) {
6879: my $subdir=$uname.'__';
6880: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6881: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
6882: ."/$udom/$subdir/$uname";
6883: } elsif (defined($alternateRoot)) {
6884: $dirRoot = $alternateRoot;
1.751 banghart 6885: }
1.253 stredwic 6886:
6887: if($udom) {
6888: if($uname) {
1.955 raeburn 6889: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 6890: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 6891: .':'.&escape($uname).':'.&escape($udom),
6892: &homeserver($uname,$udom));
6893: if ($listing eq 'unknown_cmd') {
6894: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6895: &homeserver($uname,$udom));
6896: } else {
6897: @listing_results = map { &unescape($_); } split(/:/,$listing);
6898: }
1.605 matthew 6899: if ($listing eq 'unknown_cmd') {
1.800 albertel 6900: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6901: &homeserver($uname,$udom));
1.605 matthew 6902: @listing_results = split(/:/,$listing);
6903: } else {
6904: @listing_results = map { &unescape($_); } split(/:/,$listing);
6905: }
6906: return @listing_results;
1.955 raeburn 6907: } elsif(!$alternateRoot) {
1.800 albertel 6908: my %allusers;
1.841 albertel 6909: my %servers = &get_servers($udom,'library');
1.955 raeburn 6910: foreach my $tryserver (keys(%servers)) {
6911: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
6912: &escape($udom),$tryserver);
6913: if ($listing eq 'unknown_cmd') {
6914: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6915: $udom, $tryserver);
6916: } else {
6917: @listing_results = map { &unescape($_); } split(/:/,$listing);
6918: }
1.841 albertel 6919: if ($listing eq 'unknown_cmd') {
6920: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6921: $udom, $tryserver);
6922: @listing_results = split(/:/,$listing);
6923: } else {
6924: @listing_results =
6925: map { &unescape($_); } split(/:/,$listing);
6926: }
6927: if ($listing_results[0] ne 'no_such_dir' &&
6928: $listing_results[0] ne 'empty' &&
6929: $listing_results[0] ne 'con_lost') {
6930: foreach my $line (@listing_results) {
6931: my ($entry) = split(/&/,$line,2);
6932: $allusers{$entry} = 1;
6933: }
6934: }
1.253 stredwic 6935: }
6936: my $alluserstr='';
1.800 albertel 6937: foreach my $user (sort(keys(%allusers))) {
6938: $alluserstr.=$user.'&user:';
1.253 stredwic 6939: }
6940: $alluserstr=~s/:$//;
6941: return split(/:/,$alluserstr);
6942: } else {
1.800 albertel 6943: return ('missing user name');
1.253 stredwic 6944: }
1.955 raeburn 6945: } elsif(!defined($getpropath)) {
1.841 albertel 6946: my @all_domains = sort(&all_domains());
1.955 raeburn 6947: foreach my $domain (@all_domains) {
6948: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6949: }
6950: return @all_domains;
6951: } else {
1.800 albertel 6952: return ('missing domain');
1.275 stredwic 6953: }
6954: }
6955:
6956: # --------------------------------------------- GetFileTimestamp
6957: # This function utilizes dirlist and returns the date stamp for
6958: # when it was last modified. It will also return an error of -1
6959: # if an error occurs
6960:
6961: sub GetFileTimestamp {
1.955 raeburn 6962: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 6963: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6964: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 6965: my ($fileStat) =
6966: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
6967: undef,$getuserdir);
1.275 stredwic 6968: my @stats = split('&', $fileStat);
6969: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6970: # @stats contains first the filename, then the stat output
6971: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6972: } else {
6973: return -1;
1.253 stredwic 6974: }
1.26 www 6975: }
6976:
1.712 albertel 6977: sub stat_file {
6978: my ($uri) = @_;
1.787 albertel 6979: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6980:
1.955 raeburn 6981: my ($udom,$uname,$file);
1.712 albertel 6982: if ($uri =~ m-^/(uploaded|editupload)/-) {
6983: ($udom,$uname,$file) =
1.811 albertel 6984: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6985: $file = 'userfiles/'.$file;
6986: }
6987: if ($uri =~ m-^/res/-) {
6988: ($udom,$uname) =
1.807 albertel 6989: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6990: $file = $uri;
6991: }
6992:
6993: if (!$udom || !$uname || !$file) {
6994: # unable to handle the uri
6995: return ();
6996: }
1.956 raeburn 6997: my $getpropath;
6998: if ($file =~ /^userfiles\//) {
6999: $getpropath = 1;
7000: }
1.955 raeburn 7001: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7002: my @stats = split('&', $result);
1.721 banghart 7003:
1.712 albertel 7004: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7005: shift(@stats); #filename is first
7006: return @stats;
7007: }
7008: return ();
7009: }
7010:
1.26 www 7011: # -------------------------------------------------------- Value of a Condition
7012:
1.713 albertel 7013: # gets the value of a specific preevaluated condition
7014: # stored in the string $env{user.state.<cid>}
7015: # or looks up a condition reference in the bighash and if if hasn't
7016: # already been evaluated recurses into docondval to get the value of
7017: # the condition, then memoizing it to
7018: # $env{user.state.<cid>.<condition>}
1.40 www 7019: sub directcondval {
7020: my $number=shift;
1.620 albertel 7021: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7022: &Apache::lonuserstate::evalstate();
7023: }
1.713 albertel 7024: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7025: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7026: } elsif ($number =~ /^_/) {
7027: my $sub_condition;
7028: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7029: &GDBM_READER(),0640)) {
7030: $sub_condition=$bighash{'conditions'.$number};
7031: untie(%bighash);
7032: }
7033: my $value = &docondval($sub_condition);
1.949 raeburn 7034: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7035: return $value;
7036: }
1.620 albertel 7037: if ($env{'user.state.'.$env{'request.course.id'}}) {
7038: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7039: } else {
7040: return 2;
7041: }
7042: }
7043:
1.713 albertel 7044: # get the collection of conditions for this resource
1.26 www 7045: sub condval {
7046: my $condidx=shift;
1.54 www 7047: my $allpathcond='';
1.713 albertel 7048: foreach my $cond (split(/\|/,$condidx)) {
7049: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7050: $allpathcond.=
7051: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7052: }
1.191 harris41 7053: }
1.54 www 7054: $allpathcond=~s/\|$//;
1.713 albertel 7055: return &docondval($allpathcond);
7056: }
7057:
7058: #evaluates an expression of conditions
7059: sub docondval {
7060: my ($allpathcond) = @_;
7061: my $result=0;
7062: if ($env{'request.course.id'}
7063: && defined($allpathcond)) {
7064: my $operand='|';
7065: my @stack;
7066: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7067: if ($chunk eq '(') {
7068: push @stack,($operand,$result);
7069: } elsif ($chunk eq ')') {
7070: my $before=pop @stack;
7071: if (pop @stack eq '&') {
7072: $result=$result>$before?$before:$result;
7073: } else {
7074: $result=$result>$before?$result:$before;
7075: }
7076: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7077: $operand=$chunk;
7078: } else {
7079: my $new=directcondval($chunk);
7080: if ($operand eq '&') {
7081: $result=$result>$new?$new:$result;
7082: } else {
7083: $result=$result>$new?$result:$new;
7084: }
7085: }
7086: }
1.26 www 7087: }
7088: return $result;
1.421 albertel 7089: }
7090:
7091: # ---------------------------------------------------- Devalidate courseresdata
7092:
7093: sub devalidatecourseresdata {
7094: my ($coursenum,$coursedomain)=@_;
7095: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7096: &devalidate_cache_new('courseres',$hashid);
1.28 www 7097: }
7098:
1.763 www 7099:
1.200 www 7100: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7101: #
7102: # Parameters:
7103: # $coursenum - Number of the course.
7104: # $coursedomain - Domain at which the course was created.
7105: # Returns:
7106: # A hash of the course parameters along (I think) with timestamps
7107: # and version info.
1.877 foxr 7108:
1.624 albertel 7109: sub get_courseresdata {
7110: my ($coursenum,$coursedomain)=@_;
1.200 www 7111: my $coursehom=&homeserver($coursenum,$coursedomain);
7112: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7113: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7114: my %dumpreply;
1.417 albertel 7115: unless (defined($cached)) {
1.624 albertel 7116: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7117: $result=\%dumpreply;
1.251 albertel 7118: my ($tmp) = keys(%dumpreply);
7119: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7120: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7121: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7122: return $tmp;
1.416 albertel 7123: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7124: $result=undef;
1.599 albertel 7125: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7126: }
7127: }
1.624 albertel 7128: return $result;
7129: }
7130:
1.633 albertel 7131: sub devalidateuserresdata {
7132: my ($uname,$udom)=@_;
7133: my $hashid="$udom:$uname";
7134: &devalidate_cache_new('userres',$hashid);
7135: }
7136:
1.624 albertel 7137: sub get_userresdata {
7138: my ($uname,$udom)=@_;
7139: #most student don\'t have any data set, check if there is some data
7140: if (&EXT_cache_status($udom,$uname)) { return undef; }
7141:
7142: my $hashid="$udom:$uname";
7143: my ($result,$cached)=&is_cached_new('userres',$hashid);
7144: if (!defined($cached)) {
7145: my %resourcedata=&dump('resourcedata',$udom,$uname);
7146: $result=\%resourcedata;
7147: &do_cache_new('userres',$hashid,$result,600);
7148: }
7149: my ($tmp)=keys(%$result);
7150: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7151: return $result;
7152: }
7153: #error 2 occurs when the .db doesn't exist
7154: if ($tmp!~/error: 2 /) {
1.672 albertel 7155: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7156: " Trying to get resource data for ".
7157: $uname." at ".$udom.": ".
7158: $tmp."</font>");
7159: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7160: #&EXT_cache_set($udom,$uname);
7161: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7162: undef($tmp); # not really an error so don't send it back
1.624 albertel 7163: }
7164: return $tmp;
7165: }
1.879 foxr 7166: #----------------------------------------------- resdata - return resource data
7167: # Purpose:
7168: # Return resource data for either users or for a course.
7169: # Parameters:
7170: # $name - Course/user name.
7171: # $domain - Name of the domain the user/course is registered on.
7172: # $type - Type of thing $name is (must be 'course' or 'user'
7173: # @which - Array of names of resources desired.
7174: # Returns:
7175: # The value of the first reasource in @which that is found in the
7176: # resource hash.
7177: # Exceptional Conditions:
7178: # If the $type passed in is not valid (not the string 'course' or
7179: # 'user', an undefined reference is returned.
7180: # If none of the resources are found, an undef is returned
1.624 albertel 7181: sub resdata {
7182: my ($name,$domain,$type,@which)=@_;
7183: my $result;
7184: if ($type eq 'course') {
7185: $result=&get_courseresdata($name,$domain);
7186: } elsif ($type eq 'user') {
7187: $result=&get_userresdata($name,$domain);
7188: }
7189: if (!ref($result)) { return $result; }
1.251 albertel 7190: foreach my $item (@which) {
1.927 albertel 7191: if (defined($result->{$item->[0]})) {
7192: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7193: }
1.250 albertel 7194: }
1.291 albertel 7195: return undef;
1.200 www 7196: }
7197:
1.379 matthew 7198: #
7199: # EXT resource caching routines
7200: #
7201:
7202: sub clear_EXT_cache_status {
1.383 albertel 7203: &delenv('cache.EXT.');
1.379 matthew 7204: }
7205:
7206: sub EXT_cache_status {
7207: my ($target_domain,$target_user) = @_;
1.383 albertel 7208: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7209: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7210: # We know already the user has no data
7211: return 1;
7212: } else {
7213: return 0;
7214: }
7215: }
7216:
7217: sub EXT_cache_set {
7218: my ($target_domain,$target_user) = @_;
1.383 albertel 7219: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7220: #&appenv({$cachename => time});
1.379 matthew 7221: }
7222:
1.28 www 7223: # --------------------------------------------------------- Value of a Variable
1.58 www 7224: sub EXT {
1.715 albertel 7225:
1.395 albertel 7226: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7227: unless ($varname) { return ''; }
1.218 albertel 7228: #get real user name/domain, courseid and symb
7229: my $courseid;
1.359 albertel 7230: my $publicuser;
1.427 www 7231: if ($symbparm) {
7232: $symbparm=&get_symb_from_alias($symbparm);
7233: }
1.218 albertel 7234: if (!($uname && $udom)) {
1.790 albertel 7235: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7236: if (!$symbparm) { $symbparm=$cursymb; }
7237: } else {
1.620 albertel 7238: $courseid=$env{'request.course.id'};
1.218 albertel 7239: }
1.48 www 7240: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7241: my $rest;
1.320 albertel 7242: if (defined($therest[0])) {
1.48 www 7243: $rest=join('.',@therest);
7244: } else {
7245: $rest='';
7246: }
1.320 albertel 7247:
1.57 www 7248: my $qualifierrest=$qualifier;
7249: if ($rest) { $qualifierrest.='.'.$rest; }
7250: my $spacequalifierrest=$space;
7251: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7252: if ($realm eq 'user') {
1.48 www 7253: # --------------------------------------------------------------- user.resource
7254: if ($space eq 'resource') {
1.651 albertel 7255: if ( (defined($Apache::lonhomework::parsing_a_problem)
7256: || defined($Apache::lonhomework::parsing_a_task))
7257: &&
1.744 albertel 7258: ($symbparm eq &symbread()) ) {
7259: # if we are in the middle of processing the resource the
7260: # get the value we are planning on committing
7261: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7262: return $Apache::lonhomework::results{$qualifierrest};
7263: } else {
7264: return $Apache::lonhomework::history{$qualifierrest};
7265: }
1.335 albertel 7266: } else {
1.359 albertel 7267: my %restored;
1.620 albertel 7268: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 7269: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7270: } else {
7271: %restored=&restore($symbparm,$courseid,$udom,$uname);
7272: }
1.335 albertel 7273: return $restored{$qualifierrest};
7274: }
1.48 www 7275: # ----------------------------------------------------------------- user.access
7276: } elsif ($space eq 'access') {
1.218 albertel 7277: # FIXME - not supporting calls for a specific user
1.48 www 7278: return &allowed($qualifier,$rest);
7279: # ------------------------------------------ user.preferences, user.environment
7280: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7281: if (($uname eq $env{'user.name'}) &&
7282: ($udom eq $env{'user.domain'})) {
7283: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7284: } else {
1.359 albertel 7285: my %returnhash;
7286: if (!$publicuser) {
7287: %returnhash=&userenvironment($udom,$uname,
7288: $qualifierrest);
7289: }
1.218 albertel 7290: return $returnhash{$qualifierrest};
7291: }
1.48 www 7292: # ----------------------------------------------------------------- user.course
7293: } elsif ($space eq 'course') {
1.218 albertel 7294: # FIXME - not supporting calls for a specific user
1.620 albertel 7295: return $env{join('.',('request.course',$qualifier))};
1.48 www 7296: # ------------------------------------------------------------------- user.role
7297: } elsif ($space eq 'role') {
1.218 albertel 7298: # FIXME - not supporting calls for a specific user
1.620 albertel 7299: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7300: if ($qualifier eq 'value') {
7301: return $role;
7302: } elsif ($qualifier eq 'extent') {
7303: return $where;
7304: }
7305: # ----------------------------------------------------------------- user.domain
7306: } elsif ($space eq 'domain') {
1.218 albertel 7307: return $udom;
1.48 www 7308: # ------------------------------------------------------------------- user.name
7309: } elsif ($space eq 'name') {
1.218 albertel 7310: return $uname;
1.48 www 7311: # ---------------------------------------------------- Any other user namespace
1.29 www 7312: } else {
1.359 albertel 7313: my %reply;
7314: if (!$publicuser) {
7315: %reply=&get($space,[$qualifierrest],$udom,$uname);
7316: }
7317: return $reply{$qualifierrest};
1.48 www 7318: }
1.236 www 7319: } elsif ($realm eq 'query') {
7320: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7321: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7322: [$spacequalifierrest]);
1.620 albertel 7323: return $env{'form.'.$spacequalifierrest};
1.236 www 7324: } elsif ($realm eq 'request') {
1.48 www 7325: # ------------------------------------------------------------- request.browser
7326: if ($space eq 'browser') {
1.430 www 7327: if ($qualifier eq 'textremote') {
1.676 albertel 7328: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7329: return 1;
7330: } else {
7331: return 0;
7332: }
7333: } else {
1.620 albertel 7334: return $env{'browser.'.$qualifier};
1.430 www 7335: }
1.57 www 7336: # ------------------------------------------------------------ request.filename
7337: } else {
1.620 albertel 7338: return $env{'request.'.$spacequalifierrest};
1.29 www 7339: }
1.28 www 7340: } elsif ($realm eq 'course') {
1.48 www 7341: # ---------------------------------------------------------- course.description
1.620 albertel 7342: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7343: } elsif ($realm eq 'resource') {
1.165 www 7344:
1.620 albertel 7345: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7346: if (!$symbparm) { $symbparm=&symbread(); }
7347: }
1.693 albertel 7348:
7349: if ($space eq 'title') {
7350: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7351: return &gettitle($symbparm);
7352: }
7353:
7354: if ($space eq 'map') {
7355: my ($map) = &decode_symb($symbparm);
7356: return &symbread($map);
7357: }
1.905 albertel 7358: if ($space eq 'filename') {
7359: if ($symbparm) {
7360: return &clutter((&decode_symb($symbparm))[2]);
7361: }
7362: return &hreflocation('',$env{'request.filename'});
7363: }
1.693 albertel 7364:
7365: my ($section, $group, @groups);
1.593 albertel 7366: my ($courselevelm,$courselevel);
1.539 albertel 7367: if ($symbparm && defined($courseid) &&
1.620 albertel 7368: $courseid eq $env{'request.course.id'}) {
1.165 www 7369:
1.218 albertel 7370: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7371:
1.60 www 7372: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7373: my $symbp=$symbparm;
1.735 albertel 7374: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7375:
7376: my $symbparm=$symbp.'.'.$spacequalifierrest;
7377: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7378:
1.620 albertel 7379: if (($env{'user.name'} eq $uname) &&
7380: ($env{'user.domain'} eq $udom)) {
7381: $section=$env{'request.course.sec'};
1.733 raeburn 7382: @groups = split(/:/,$env{'request.course.groups'});
7383: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7384: } else {
1.539 albertel 7385: if (! defined($usection)) {
1.551 albertel 7386: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7387: } else {
7388: $section = $usection;
7389: }
1.733 raeburn 7390: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7391: }
7392:
7393: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7394: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7395: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7396:
1.593 albertel 7397: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7398: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7399: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7400:
1.60 www 7401: # ----------------------------------------------------------- first, check user
1.624 albertel 7402:
7403: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7404: ([$courselevelr,'resource'],
7405: [$courselevelm,'map' ],
7406: [$courselevel, 'course' ]));
1.931 albertel 7407: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7408:
1.594 albertel 7409: # ------------------------------------------------ second, check some of course
1.684 raeburn 7410: my $coursereply;
1.691 raeburn 7411: if (@groups > 0) {
7412: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7413: $mapparm,$spacequalifierrest);
1.927 albertel 7414: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7415: }
1.96 www 7416:
1.684 raeburn 7417: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7418: $env{'course.'.$courseid.'.domain'},
7419: 'course',
7420: ([$seclevelr, 'resource'],
7421: [$seclevelm, 'map' ],
7422: [$seclevel, 'course' ],
7423: [$courselevelr,'resource']));
7424: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7425:
1.60 www 7426: # ------------------------------------------------------ third, check map parms
1.218 albertel 7427: my %parmhash=();
7428: my $thisparm='';
7429: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7430: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7431: &GDBM_READER(),0640)) {
1.218 albertel 7432: $thisparm=$parmhash{$symbparm};
7433: untie(%parmhash);
7434: }
1.927 albertel 7435: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7436: }
1.594 albertel 7437: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7438:
1.218 albertel 7439: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7440: my $filename;
7441: if (!$symbparm) { $symbparm=&symbread(); }
7442: if ($symbparm) {
1.409 www 7443: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7444: } else {
1.620 albertel 7445: $filename=$env{'request.filename'};
1.282 albertel 7446: }
7447: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7448: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7449: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7450: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7451:
1.927 albertel 7452: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7453: if ($symbparm && defined($courseid) &&
1.620 albertel 7454: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7455: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7456: $env{'course.'.$courseid.'.domain'},
7457: 'course',
1.927 albertel 7458: ([$courselevelm,'map' ],
7459: [$courselevel, 'course']));
7460: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7461: }
1.145 www 7462: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7463: unless ($space eq '0') {
1.336 albertel 7464: my @parts=split(/_/,$space);
7465: my $id=pop(@parts);
7466: my $part=join('_',@parts);
7467: if ($part eq '') { $part='0'; }
1.927 albertel 7468: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7469: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7470: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7471: }
1.395 albertel 7472: if ($recurse) { return undef; }
7473: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 7474: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 7475: # ---------------------------------------------------- Any other user namespace
7476: } elsif ($realm eq 'environment') {
7477: # ----------------------------------------------------------------- environment
1.620 albertel 7478: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7479: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 7480: } else {
1.770 albertel 7481: if ($uname eq 'anonymous' && $udom eq '') {
7482: return '';
7483: }
1.219 albertel 7484: my %returnhash=&userenvironment($udom,$uname,
7485: $spacequalifierrest);
7486: return $returnhash{$spacequalifierrest};
7487: }
1.28 www 7488: } elsif ($realm eq 'system') {
1.48 www 7489: # ----------------------------------------------------------------- system.time
7490: if ($space eq 'time') {
7491: return time;
7492: }
1.696 albertel 7493: } elsif ($realm eq 'server') {
7494: # ----------------------------------------------------------------- system.time
7495: if ($space eq 'name') {
7496: return $ENV{'SERVER_NAME'};
7497: }
1.28 www 7498: }
1.48 www 7499: return '';
1.61 www 7500: }
7501:
1.927 albertel 7502: sub get_reply {
7503: my ($reply_value) = @_;
1.940 raeburn 7504: if (ref($reply_value) eq 'ARRAY') {
7505: if (wantarray) {
7506: return @$reply_value;
7507: }
7508: return $reply_value->[0];
7509: } else {
7510: return $reply_value;
1.927 albertel 7511: }
7512: }
7513:
1.691 raeburn 7514: sub check_group_parms {
7515: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7516: my @groupitems = ();
7517: my $resultitem;
1.927 albertel 7518: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 7519: foreach my $group (@{$groups}) {
7520: foreach my $level (@levels) {
1.927 albertel 7521: my $item = $courseid.'.['.$group.'].'.$level->[0];
7522: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 7523: }
7524: }
7525: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7526: $env{'course.'.$courseid.'.domain'},
7527: 'course',@groupitems);
7528: return $coursereply;
7529: }
7530:
7531: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 7532: my ($courseid,@groups) = @_;
7533: @groups = sort(@groups);
1.691 raeburn 7534: return @groups;
7535: }
7536:
1.395 albertel 7537: sub packages_tab_default {
7538: my ($uri,$varname)=@_;
7539: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 7540:
7541: my (@extension,@specifics,$do_default);
7542: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 7543: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 7544: if ($pack_type eq 'default') {
7545: $do_default=1;
7546: } elsif ($pack_type eq 'extension') {
7547: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 7548: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 7549: # only look at packages defaults for packages that this id is
1.738 albertel 7550: push(@specifics,[$package,$pack_type,$pack_part]);
7551: }
7552: }
7553: # first look for a package that matches the requested part id
7554: foreach my $package (@specifics) {
7555: my (undef,$pack_type,$pack_part)=@{$package};
7556: next if ($pack_part ne $part);
7557: if (defined($packagetab{"$pack_type&$name&default"})) {
7558: return $packagetab{"$pack_type&$name&default"};
7559: }
7560: }
7561: # look for any possible matching non extension_ package
7562: foreach my $package (@specifics) {
7563: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 7564: if (defined($packagetab{"$pack_type&$name&default"})) {
7565: return $packagetab{"$pack_type&$name&default"};
7566: }
1.585 albertel 7567: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 7568: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7569: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 7570: }
7571: }
1.738 albertel 7572: # look for any posible extension_ match
7573: foreach my $package (@extension) {
7574: my ($package,$pack_type)=@{$package};
7575: if (defined($packagetab{"$pack_type&$name&default"})) {
7576: return $packagetab{"$pack_type&$name&default"};
7577: }
7578: if (defined($packagetab{$package."&$name&default"})) {
7579: return $packagetab{$package."&$name&default"};
7580: }
7581: }
7582: # look for a global default setting
7583: if ($do_default && defined($packagetab{"default&$name&default"})) {
7584: return $packagetab{"default&$name&default"};
7585: }
1.395 albertel 7586: return undef;
7587: }
7588:
1.334 albertel 7589: sub add_prefix_and_part {
7590: my ($prefix,$part)=@_;
7591: my $keyroot;
7592: if (defined($prefix) && $prefix !~ /^__/) {
7593: # prefix that has a part already
7594: $keyroot=$prefix;
7595: } elsif (defined($prefix)) {
7596: # prefix that is missing a part
7597: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7598: } else {
7599: # no prefix at all
7600: if (defined($part)) { $keyroot='_'.$part; }
7601: }
7602: return $keyroot;
7603: }
7604:
1.71 www 7605: # ---------------------------------------------------------------- Get metadata
7606:
1.599 albertel 7607: my %metaentry;
1.71 www 7608: sub metadata {
1.176 www 7609: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 7610: $uri=&declutter($uri);
1.288 albertel 7611: # if it is a non metadata possible uri return quickly
1.529 albertel 7612: if (($uri eq '') ||
7613: (($uri =~ m|^/*adm/|) &&
1.698 albertel 7614: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 7615: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7616: return undef;
7617: }
7618: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7619: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 7620: return undef;
1.288 albertel 7621: }
1.73 www 7622: my $filename=$uri;
7623: $uri=~s/\.meta$//;
1.172 www 7624: #
7625: # Is the metadata already cached?
1.177 www 7626: # Look at timestamp of caching
1.172 www 7627: # Everything is cached by the main uri, libraries are never directly cached
7628: #
1.428 albertel 7629: if (!defined($liburi)) {
1.599 albertel 7630: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 7631: if (defined($cached)) { return $result->{':'.$what}; }
7632: }
7633: {
1.172 www 7634: #
7635: # Is this a recursive call for a library?
7636: #
1.599 albertel 7637: # if (! exists($metacache{$uri})) {
7638: # $metacache{$uri}={};
7639: # }
1.924 albertel 7640: my $cachetime = 60*60;
1.171 www 7641: if ($liburi) {
7642: $liburi=&declutter($liburi);
7643: $filename=$liburi;
1.401 bowersj2 7644: } else {
1.599 albertel 7645: &devalidate_cache_new('meta',$uri);
7646: undef(%metaentry);
1.401 bowersj2 7647: }
1.140 www 7648: my %metathesekeys=();
1.73 www 7649: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 7650: my $metastring;
1.924 albertel 7651: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 7652: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 7653: $metastring =
1.929 albertel 7654: &Apache::lonnet::ssi_body($which,
1.924 albertel 7655: ('grade_target' => 'meta'));
7656: $cachetime = 1; # only want this cached in the child not long term
7657: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 7658: my $file=&filelocation('',&clutter($filename));
1.599 albertel 7659: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 7660: $metastring=&getfile($file);
1.489 albertel 7661: }
1.208 albertel 7662: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 7663: my $token;
1.140 www 7664: undef %metathesekeys;
1.71 www 7665: while ($token=$parser->get_token) {
1.339 albertel 7666: if ($token->[0] eq 'S') {
7667: if (defined($token->[2]->{'package'})) {
1.172 www 7668: #
7669: # This is a package - get package info
7670: #
1.339 albertel 7671: my $package=$token->[2]->{'package'};
7672: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7673: if (defined($token->[2]->{'id'})) {
7674: $keyroot.='_'.$token->[2]->{'id'};
7675: }
1.599 albertel 7676: if ($metaentry{':packages'}) {
7677: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 7678: } else {
1.599 albertel 7679: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 7680: }
1.736 albertel 7681: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 7682: my $part=$keyroot;
7683: $part=~s/^\_//;
1.736 albertel 7684: if ($pack_entry=~/^\Q$package\E\&/ ||
7685: $pack_entry=~/^\Q$package\E_0\&/) {
7686: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 7687: # ignore package.tab specified default values
7688: # here &package_tab_default() will fetch those
7689: if ($subp eq 'default') { next; }
1.736 albertel 7690: my $value=$packagetab{$pack_entry};
1.432 albertel 7691: my $unikey;
7692: if ($pack =~ /_0$/) {
7693: $unikey='parameter_0_'.$name;
7694: $part=0;
7695: } else {
7696: $unikey='parameter'.$keyroot.'_'.$name;
7697: }
1.339 albertel 7698: if ($subp eq 'display') {
7699: $value.=' [Part: '.$part.']';
7700: }
1.599 albertel 7701: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 7702: $metathesekeys{$unikey}=1;
1.599 albertel 7703: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7704: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 7705: }
1.599 albertel 7706: if (defined($metaentry{':'.$unikey.'.default'})) {
7707: $metaentry{':'.$unikey}=
7708: $metaentry{':'.$unikey.'.default'};
1.356 albertel 7709: }
1.339 albertel 7710: }
7711: }
7712: } else {
1.172 www 7713: #
7714: # This is not a package - some other kind of start tag
1.339 albertel 7715: #
7716: my $entry=$token->[1];
7717: my $unikey;
7718: if ($entry eq 'import') {
7719: $unikey='';
7720: } else {
7721: $unikey=$entry;
7722: }
7723: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7724:
7725: if (defined($token->[2]->{'id'})) {
7726: $unikey.='_'.$token->[2]->{'id'};
7727: }
1.175 www 7728:
1.339 albertel 7729: if ($entry eq 'import') {
1.175 www 7730: #
7731: # Importing a library here
1.339 albertel 7732: #
7733: if ($depthcount<20) {
7734: my $location=$parser->get_text('/import');
7735: my $dir=$filename;
7736: $dir=~s|[^/]*$||;
7737: $location=&filelocation($dir,$location);
1.736 albertel 7738: my $metadata =
7739: &metadata($uri,'keys', $location,$unikey,
7740: $depthcount+1);
7741: foreach my $meta (split(',',$metadata)) {
7742: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7743: $metathesekeys{$meta}=1;
1.339 albertel 7744: }
7745: }
7746: } else {
7747:
7748: if (defined($token->[2]->{'name'})) {
7749: $unikey.='_'.$token->[2]->{'name'};
7750: }
7751: $metathesekeys{$unikey}=1;
1.736 albertel 7752: foreach my $param (@{$token->[3]}) {
7753: $metaentry{':'.$unikey.'.'.$param} =
7754: $token->[2]->{$param};
1.339 albertel 7755: }
7756: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 7757: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 7758: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7759: # only ws inside the tag, and not in default, so use default
7760: # as value
1.599 albertel 7761: $metaentry{':'.$unikey}=$default;
1.908 albertel 7762: } elsif ( $internaltext =~ /\S/ ) {
7763: # something interesting inside the tag
7764: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 7765: } else {
1.908 albertel 7766: # no interesting values, don't set a default
1.339 albertel 7767: }
1.172 www 7768: # end of not-a-package not-a-library import
1.339 albertel 7769: }
1.172 www 7770: # end of not-a-package start tag
1.339 albertel 7771: }
1.172 www 7772: # the next is the end of "start tag"
1.339 albertel 7773: }
7774: }
1.483 albertel 7775: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 7776: $extension = lc($extension);
7777: if ($extension eq 'htm') { $extension='html'; }
7778:
1.737 albertel 7779: foreach my $key (keys(%packagetab)) {
1.483 albertel 7780: #no specific packages #how's our extension
7781: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 7782: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 7783: \%metathesekeys);
7784: }
1.883 albertel 7785:
7786: if (!exists($metaentry{':packages'})
7787: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 7788: foreach my $key (keys(%packagetab)) {
1.483 albertel 7789: #no specific packages well let's get default then
7790: if ($key!~/^default&/) { next; }
1.488 albertel 7791: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 7792: \%metathesekeys);
7793: }
7794: }
1.338 www 7795: # are there custom rights to evaluate
1.599 albertel 7796: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 7797:
1.338 www 7798: #
7799: # Importing a rights file here
1.339 albertel 7800: #
7801: unless ($depthcount) {
1.599 albertel 7802: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 7803: my $dir=$filename;
7804: $dir=~s|[^/]*$||;
7805: $location=&filelocation($dir,$location);
1.736 albertel 7806: my $rights_metadata =
7807: &metadata($uri,'keys',$location,'_rights',
7808: $depthcount+1);
7809: foreach my $rights (split(',',$rights_metadata)) {
7810: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7811: $metathesekeys{$rights}=1;
1.339 albertel 7812: }
7813: }
7814: }
1.737 albertel 7815: # uniqifiy package listing
7816: my %seen;
7817: my @uniq_packages =
7818: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7819: $metaentry{':packages'} = join(',',@uniq_packages);
7820:
7821: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 7822: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7823: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 7824: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 7825: # this is the end of "was not already recently cached
1.71 www 7826: }
1.599 albertel 7827: return $metaentry{':'.$what};
1.261 albertel 7828: }
7829:
1.488 albertel 7830: sub metadata_create_package_def {
1.483 albertel 7831: my ($uri,$key,$package,$metathesekeys)=@_;
7832: my ($pack,$name,$subp)=split(/\&/,$key);
7833: if ($subp eq 'default') { next; }
7834:
1.599 albertel 7835: if (defined($metaentry{':packages'})) {
7836: $metaentry{':packages'}.=','.$package;
1.483 albertel 7837: } else {
1.599 albertel 7838: $metaentry{':packages'}=$package;
1.483 albertel 7839: }
7840: my $value=$packagetab{$key};
7841: my $unikey;
7842: $unikey='parameter_0_'.$name;
1.599 albertel 7843: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 7844: $$metathesekeys{$unikey}=1;
1.599 albertel 7845: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7846: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 7847: }
1.599 albertel 7848: if (defined($metaentry{':'.$unikey.'.default'})) {
7849: $metaentry{':'.$unikey}=
7850: $metaentry{':'.$unikey.'.default'};
1.483 albertel 7851: }
7852: }
7853:
1.261 albertel 7854: sub metadata_generate_part0 {
7855: my ($metadata,$metacache,$uri) = @_;
7856: my %allnames;
1.737 albertel 7857: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7858: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7859: my $part=$$metacache{':'.$metakey.'.part'};
7860: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7861: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7862: $allnames{$name}=$part;
7863: }
7864: }
7865: }
7866: foreach my $name (keys(%allnames)) {
7867: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7868: my $key=":parameter_0_$name";
1.261 albertel 7869: $$metacache{"$key.part"}='0';
7870: $$metacache{"$key.name"}=$name;
1.428 albertel 7871: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7872: $allnames{$name}.'_'.$name.
7873: '.type'};
1.428 albertel 7874: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7875: '.display'};
1.644 www 7876: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7877: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7878: $$metacache{"$key.display"}=$olddis;
7879: }
1.71 www 7880: }
7881:
1.764 albertel 7882: # ------------------------------------------------------ Devalidate title cache
7883:
7884: sub devalidate_title_cache {
7885: my ($url)=@_;
7886: if (!$env{'request.course.id'}) { return; }
7887: my $symb=&symbread($url);
7888: if (!$symb) { return; }
7889: my $key=$env{'request.course.id'}."\0".$symb;
7890: &devalidate_cache_new('title',$key);
7891: }
7892:
1.301 www 7893: # ------------------------------------------------- Get the title of a resource
7894:
7895: sub gettitle {
7896: my $urlsymb=shift;
7897: my $symb=&symbread($urlsymb);
1.534 albertel 7898: if ($symb) {
1.620 albertel 7899: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7900: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7901: if (defined($cached)) {
7902: return $result;
7903: }
1.534 albertel 7904: my ($map,$resid,$url)=&decode_symb($symb);
7905: my $title='';
1.907 albertel 7906: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7907: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7908: } else {
7909: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7910: &GDBM_READER(),0640)) {
7911: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7912: $title=$bighash{'title_'.$mapid.'.'.$resid};
7913: untie(%bighash);
7914: }
1.534 albertel 7915: }
7916: $title=~s/\&colon\;/\:/gs;
7917: if ($title) {
1.599 albertel 7918: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7919: }
7920: $urlsymb=$url;
7921: }
7922: my $title=&metadata($urlsymb,'title');
7923: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7924: return $title;
1.301 www 7925: }
1.613 albertel 7926:
1.614 albertel 7927: sub get_slot {
7928: my ($which,$cnum,$cdom)=@_;
7929: if (!$cnum || !$cdom) {
1.790 albertel 7930: (undef,my $courseid)=&whichuser();
1.620 albertel 7931: $cdom=$env{'course.'.$courseid.'.domain'};
7932: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7933: }
1.703 albertel 7934: my $key=join("\0",'slots',$cdom,$cnum,$which);
7935: my %slotinfo;
7936: if (exists($remembered{$key})) {
7937: $slotinfo{$which} = $remembered{$key};
7938: } else {
7939: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7940: &Apache::lonhomework::showhash(%slotinfo);
7941: my ($tmp)=keys(%slotinfo);
7942: if ($tmp=~/^error:/) { return (); }
7943: $remembered{$key} = $slotinfo{$which};
7944: }
1.616 albertel 7945: if (ref($slotinfo{$which}) eq 'HASH') {
7946: return %{$slotinfo{$which}};
7947: }
7948: return $slotinfo{$which};
1.614 albertel 7949: }
1.31 www 7950: # ------------------------------------------------- Update symbolic store links
7951:
7952: sub symblist {
7953: my ($mapname,%newhash)=@_;
1.438 www 7954: $mapname=&deversion(&declutter($mapname));
1.31 www 7955: my %hash;
1.620 albertel 7956: if (($env{'request.course.fn'}) && (%newhash)) {
7957: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7958: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 7959: foreach my $url (keys(%newhash)) {
1.711 albertel 7960: next if ($url eq 'last_known'
7961: && $env{'form.no_update_last_known'});
7962: $hash{declutter($url)}=&encode_symb($mapname,
7963: $newhash{$url}->[1],
7964: $newhash{$url}->[0]);
1.191 harris41 7965: }
1.31 www 7966: if (untie(%hash)) {
7967: return 'ok';
7968: }
7969: }
7970: }
7971: return 'error';
1.212 www 7972: }
7973:
7974: # --------------------------------------------------------------- Verify a symb
7975:
7976: sub symbverify {
1.510 www 7977: my ($symb,$thisurl)=@_;
7978: my $thisfn=$thisurl;
1.439 www 7979: $thisfn=&declutter($thisfn);
1.215 www 7980: # direct jump to resource in page or to a sequence - will construct own symbs
7981: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7982: # check URL part
1.409 www 7983: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7984:
1.431 www 7985: unless ($url eq $thisfn) { return 0; }
1.213 www 7986:
1.216 www 7987: $symb=&symbclean($symb);
1.510 www 7988: $thisurl=&deversion($thisurl);
1.439 www 7989: $thisfn=&deversion($thisfn);
1.213 www 7990:
7991: my %bighash;
7992: my $okay=0;
1.431 www 7993:
1.620 albertel 7994: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7995: &GDBM_READER(),0640)) {
1.510 www 7996: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7997: unless ($ids) {
1.510 www 7998: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7999: }
8000: if ($ids) {
8001: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8002: foreach my $id (split(/\,/,$ids)) {
8003: my ($mapid,$resid)=split(/\./,$id);
1.216 www 8004: if (
8005: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8006: eq $symb) {
1.620 albertel 8007: if (($env{'request.role.adv'}) ||
1.800 albertel 8008: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8009: $okay=1;
8010: }
8011: }
1.216 www 8012: }
8013: }
1.213 www 8014: untie(%bighash);
8015: }
8016: return $okay;
1.31 www 8017: }
8018:
1.210 www 8019: # --------------------------------------------------------------- Clean-up symb
8020:
8021: sub symbclean {
8022: my $symb=shift;
1.568 albertel 8023: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8024: # remove version from map
8025: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8026:
1.210 www 8027: # remove version from URL
8028: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8029:
1.507 www 8030: # remove wrapper
8031:
1.510 www 8032: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8033: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8034: return $symb;
1.409 www 8035: }
8036:
8037: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8038:
8039: sub encode_symb {
8040: my ($map,$resid,$url)=@_;
8041: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8042: }
1.409 www 8043:
8044: sub decode_symb {
1.568 albertel 8045: my $symb=shift;
8046: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8047: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8048: return (&fixversion($map),$resid,&fixversion($url));
8049: }
8050:
8051: sub fixversion {
8052: my $fn=shift;
1.609 banghart 8053: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8054: my %bighash;
8055: my $uri=&clutter($fn);
1.620 albertel 8056: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8057: # is this cached?
1.599 albertel 8058: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8059: if (defined($cached)) { return $result; }
8060: # unfortunately not cached, or expired
1.620 albertel 8061: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8062: &GDBM_READER(),0640)) {
8063: if ($bighash{'version_'.$uri}) {
8064: my $version=$bighash{'version_'.$uri};
1.444 www 8065: unless (($version eq 'mostrecent') ||
8066: ($version==&getversion($uri))) {
1.440 www 8067: $uri=~s/\.(\w+)$/\.$version\.$1/;
8068: }
8069: }
8070: untie %bighash;
1.413 www 8071: }
1.599 albertel 8072: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8073: }
8074:
8075: sub deversion {
8076: my $url=shift;
8077: $url=~s/\.\d+\.(\w+)$/\.$1/;
8078: return $url;
1.210 www 8079: }
8080:
1.31 www 8081: # ------------------------------------------------------ Return symb list entry
8082:
8083: sub symbread {
1.249 www 8084: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8085: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8086: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8087: # no filename provided? try from environment
1.44 www 8088: unless ($thisfn) {
1.620 albertel 8089: if ($env{'request.symb'}) {
8090: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8091: }
1.620 albertel 8092: $thisfn=$env{'request.filename'};
1.44 www 8093: }
1.569 albertel 8094: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8095: # is that filename actually a symb? Verify, clean, and return
8096: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8097: if (&symbverify($thisfn,$1)) {
1.620 albertel 8098: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8099: }
1.242 www 8100: }
1.44 www 8101: $thisfn=declutter($thisfn);
1.31 www 8102: my %hash;
1.37 www 8103: my %bighash;
8104: my $syval='';
1.620 albertel 8105: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8106: my $targetfn = $thisfn;
1.609 banghart 8107: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8108: $targetfn = 'adm/wrapper/'.$thisfn;
8109: }
1.687 albertel 8110: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8111: $targetfn=$1;
8112: }
1.620 albertel 8113: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8114: &GDBM_READER(),0640)) {
1.481 raeburn 8115: $syval=$hash{$targetfn};
1.37 www 8116: untie(%hash);
8117: }
8118: # ---------------------------------------------------------- There was an entry
8119: if ($syval) {
1.601 albertel 8120: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8121: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8122: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8123: #return $env{$cache_str}='';
1.601 albertel 8124: #}
8125: #$syval.=$1;
8126: #}
1.37 www 8127: } else {
8128: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8129: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8130: &GDBM_READER(),0640)) {
1.37 www 8131: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8132: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8133: unless ($ids) {
8134: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8135: }
8136: unless ($ids) {
8137: # alias?
8138: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8139: }
1.37 www 8140: if ($ids) {
8141: # ------------------------------------------------------------------- Has ID(s)
8142: my @possibilities=split(/\,/,$ids);
1.39 www 8143: if ($#possibilities==0) {
8144: # ----------------------------------------------- There is only one possibility
1.37 www 8145: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8146: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8147: $resid,$thisfn);
1.249 www 8148: } elsif (!$donotrecurse) {
1.39 www 8149: # ------------------------------------------ There is more than one possibility
8150: my $realpossible=0;
1.800 albertel 8151: foreach my $id (@possibilities) {
8152: my $file=$bighash{'src_'.$id};
1.39 www 8153: if (&allowed('bre',$file)) {
1.800 albertel 8154: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8155: if ($bighash{'map_type_'.$mapid} ne 'page') {
8156: $realpossible++;
1.626 albertel 8157: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8158: $resid,$thisfn);
1.39 www 8159: }
8160: }
1.191 harris41 8161: }
1.39 www 8162: if ($realpossible!=1) { $syval=''; }
1.249 www 8163: } else {
8164: $syval='';
1.37 www 8165: }
8166: }
8167: untie(%bighash)
1.481 raeburn 8168: }
1.31 www 8169: }
1.62 www 8170: if ($syval) {
1.620 albertel 8171: return $env{$cache_str}=$syval;
1.62 www 8172: }
1.31 www 8173: }
1.949 raeburn 8174: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8175: return $env{$cache_str}='';
1.31 www 8176: }
8177:
8178: # ---------------------------------------------------------- Return random seed
8179:
1.32 www 8180: sub numval {
8181: my $txt=shift;
8182: $txt=~tr/A-J/0-9/;
8183: $txt=~tr/a-j/0-9/;
8184: $txt=~tr/K-T/0-9/;
8185: $txt=~tr/k-t/0-9/;
8186: $txt=~tr/U-Z/0-5/;
8187: $txt=~tr/u-z/0-5/;
8188: $txt=~s/\D//g;
1.564 albertel 8189: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8190: return int($txt);
1.368 albertel 8191: }
8192:
1.484 albertel 8193: sub numval2 {
8194: my $txt=shift;
8195: $txt=~tr/A-J/0-9/;
8196: $txt=~tr/a-j/0-9/;
8197: $txt=~tr/K-T/0-9/;
8198: $txt=~tr/k-t/0-9/;
8199: $txt=~tr/U-Z/0-5/;
8200: $txt=~tr/u-z/0-5/;
8201: $txt=~s/\D//g;
8202: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8203: my $total;
8204: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8205: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 8206: return int($total);
8207: }
8208:
1.575 albertel 8209: sub numval3 {
8210: use integer;
8211: my $txt=shift;
8212: $txt=~tr/A-J/0-9/;
8213: $txt=~tr/a-j/0-9/;
8214: $txt=~tr/K-T/0-9/;
8215: $txt=~tr/k-t/0-9/;
8216: $txt=~tr/U-Z/0-5/;
8217: $txt=~tr/u-z/0-5/;
8218: $txt=~s/\D//g;
8219: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8220: my $total;
8221: foreach my $val (@txts) { $total+=$val; }
8222: if ($_64bit) { $total=(($total<<32)>>32); }
8223: return $total;
8224: }
8225:
1.675 albertel 8226: sub digest {
8227: my ($data)=@_;
8228: my $digest=&Digest::MD5::md5($data);
8229: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8230: my ($e,$f);
8231: {
8232: use integer;
8233: $e=($a+$b);
8234: $f=($c+$d);
8235: if ($_64bit) {
8236: $e=(($e<<32)>>32);
8237: $f=(($f<<32)>>32);
8238: }
8239: }
8240: if (wantarray) {
8241: return ($e,$f);
8242: } else {
8243: my $g;
8244: {
8245: use integer;
8246: $g=($e+$f);
8247: if ($_64bit) {
8248: $g=(($g<<32)>>32);
8249: }
8250: }
8251: return $g;
8252: }
8253: }
8254:
1.368 albertel 8255: sub latest_rnd_algorithm_id {
1.675 albertel 8256: return '64bit5';
1.366 albertel 8257: }
1.32 www 8258:
1.503 albertel 8259: sub get_rand_alg {
8260: my ($courseid)=@_;
1.790 albertel 8261: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 8262: if ($courseid) {
1.620 albertel 8263: return $env{"course.$courseid.rndseed"};
1.503 albertel 8264: }
8265: return &latest_rnd_algorithm_id();
8266: }
8267:
1.562 albertel 8268: sub validCODE {
8269: my ($CODE)=@_;
8270: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8271: return 0;
8272: }
8273:
1.491 albertel 8274: sub getCODE {
1.620 albertel 8275: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 8276: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8277: defined($Apache::lonhomework::parsing_a_task) ) &&
8278: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 8279: return $Apache::lonhomework::history{'resource.CODE'};
8280: }
8281: return undef;
8282: }
8283:
1.31 www 8284: sub rndseed {
1.155 albertel 8285: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8286: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8287: if (!defined($symb)) {
1.366 albertel 8288: unless ($symb=$wsymb) { return time; }
8289: }
8290: if (!$courseid) { $courseid=$wcourseid; }
8291: if (!$domain) { $domain=$wdomain; }
8292: if (!$username) { $username=$wusername }
1.503 albertel 8293: my $which=&get_rand_alg();
1.803 albertel 8294:
1.491 albertel 8295: if (defined(&getCODE())) {
1.675 albertel 8296: if ($which eq '64bit5') {
8297: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8298: } elsif ($which eq '64bit4') {
1.575 albertel 8299: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8300: } else {
8301: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8302: }
1.675 albertel 8303: } elsif ($which eq '64bit5') {
8304: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8305: } elsif ($which eq '64bit4') {
8306: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8307: } elsif ($which eq '64bit3') {
8308: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8309: } elsif ($which eq '64bit2') {
8310: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8311: } elsif ($which eq '64bit') {
8312: return &rndseed_64bit($symb,$courseid,$domain,$username);
8313: }
8314: return &rndseed_32bit($symb,$courseid,$domain,$username);
8315: }
8316:
8317: sub rndseed_32bit {
8318: my ($symb,$courseid,$domain,$username)=@_;
8319: {
8320: use integer;
8321: my $symbchck=unpack("%32C*",$symb) << 27;
8322: my $symbseed=numval($symb) << 22;
8323: my $namechck=unpack("%32C*",$username) << 17;
8324: my $nameseed=numval($username) << 12;
8325: my $domainseed=unpack("%32C*",$domain) << 7;
8326: my $courseseed=unpack("%32C*",$courseid);
8327: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8328: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8329: #&logthis("rndseed :$num:$symb");
1.564 albertel 8330: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8331: return $num;
8332: }
8333: }
8334:
8335: sub rndseed_64bit {
8336: my ($symb,$courseid,$domain,$username)=@_;
8337: {
8338: use integer;
8339: my $symbchck=unpack("%32S*",$symb) << 21;
8340: my $symbseed=numval($symb) << 10;
8341: my $namechck=unpack("%32S*",$username);
8342:
8343: my $nameseed=numval($username) << 21;
8344: my $domainseed=unpack("%32S*",$domain) << 10;
8345: my $courseseed=unpack("%32S*",$courseid);
8346:
8347: my $num1=$symbchck+$symbseed+$namechck;
8348: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8349: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8350: #&logthis("rndseed :$num:$symb");
1.564 albertel 8351: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8352: return "$num1,$num2";
1.155 albertel 8353: }
1.366 albertel 8354: }
8355:
1.443 albertel 8356: sub rndseed_64bit2 {
8357: my ($symb,$courseid,$domain,$username)=@_;
8358: {
8359: use integer;
8360: # strings need to be an even # of cahracters long, it it is odd the
8361: # last characters gets thrown away
8362: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8363: my $symbseed=numval($symb) << 10;
8364: my $namechck=unpack("%32S*",$username.' ');
8365:
8366: my $nameseed=numval($username) << 21;
1.501 albertel 8367: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8368: my $courseseed=unpack("%32S*",$courseid.' ');
8369:
8370: my $num1=$symbchck+$symbseed+$namechck;
8371: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8372: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8373: #&logthis("rndseed :$num:$symb");
1.803 albertel 8374: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8375: return "$num1,$num2";
8376: }
8377: }
8378:
8379: sub rndseed_64bit3 {
8380: my ($symb,$courseid,$domain,$username)=@_;
8381: {
8382: use integer;
8383: # strings need to be an even # of cahracters long, it it is odd the
8384: # last characters gets thrown away
8385: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8386: my $symbseed=numval2($symb) << 10;
8387: my $namechck=unpack("%32S*",$username.' ');
8388:
8389: my $nameseed=numval2($username) << 21;
1.443 albertel 8390: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8391: my $courseseed=unpack("%32S*",$courseid.' ');
8392:
8393: my $num1=$symbchck+$symbseed+$namechck;
8394: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8395: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8396: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8397: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8398:
1.503 albertel 8399: return "$num1:$num2";
1.443 albertel 8400: }
8401: }
8402:
1.575 albertel 8403: sub rndseed_64bit4 {
8404: my ($symb,$courseid,$domain,$username)=@_;
8405: {
8406: use integer;
8407: # strings need to be an even # of cahracters long, it it is odd the
8408: # last characters gets thrown away
8409: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8410: my $symbseed=numval3($symb) << 10;
8411: my $namechck=unpack("%32S*",$username.' ');
8412:
8413: my $nameseed=numval3($username) << 21;
8414: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8415: my $courseseed=unpack("%32S*",$courseid.' ');
8416:
8417: my $num1=$symbchck+$symbseed+$namechck;
8418: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8419: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8420: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 8421: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8422:
8423: return "$num1:$num2";
8424: }
8425: }
8426:
1.675 albertel 8427: sub rndseed_64bit5 {
8428: my ($symb,$courseid,$domain,$username)=@_;
8429: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8430: return "$num1:$num2";
8431: }
8432:
1.366 albertel 8433: sub rndseed_CODE_64bit {
8434: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 8435: {
1.366 albertel 8436: use integer;
1.443 albertel 8437: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 8438: my $symbseed=numval2($symb);
1.491 albertel 8439: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8440: my $CODEseed=numval(&getCODE());
1.443 albertel 8441: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 8442: my $num1=$symbseed+$CODEchck;
8443: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8444: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8445: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 8446: if ($_64bit) { $num1=(($num1<<32)>>32); }
8447: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 8448: return "$num1:$num2";
1.366 albertel 8449: }
8450: }
8451:
1.575 albertel 8452: sub rndseed_CODE_64bit4 {
8453: my ($symb,$courseid,$domain,$username)=@_;
8454: {
8455: use integer;
8456: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8457: my $symbseed=numval3($symb);
8458: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8459: my $CODEseed=numval3(&getCODE());
8460: my $courseseed=unpack("%32S*",$courseid.' ');
8461: my $num1=$symbseed+$CODEchck;
8462: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8463: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8464: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 8465: if ($_64bit) { $num1=(($num1<<32)>>32); }
8466: if ($_64bit) { $num2=(($num2<<32)>>32); }
8467: return "$num1:$num2";
8468: }
8469: }
8470:
1.675 albertel 8471: sub rndseed_CODE_64bit5 {
8472: my ($symb,$courseid,$domain,$username)=@_;
8473: my $code = &getCODE();
8474: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8475: return "$num1:$num2";
8476: }
8477:
1.366 albertel 8478: sub setup_random_from_rndseed {
8479: my ($rndseed)=@_;
1.503 albertel 8480: if ($rndseed =~/([,:])/) {
8481: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 8482: &Math::Random::random_set_seed(abs($num1),abs($num2));
8483: } else {
8484: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 8485: }
1.36 albertel 8486: }
8487:
1.474 albertel 8488: sub latest_receipt_algorithm_id {
1.835 albertel 8489: return 'receipt3';
1.474 albertel 8490: }
8491:
1.480 www 8492: sub recunique {
8493: my $fucourseid=shift;
8494: my $unique;
1.835 albertel 8495: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8496: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8497: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 8498: } else {
8499: $unique=$perlvar{'lonReceipt'};
8500: }
8501: return unpack("%32C*",$unique);
8502: }
8503:
8504: sub recprefix {
8505: my $fucourseid=shift;
8506: my $prefix;
1.835 albertel 8507: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8508: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8509: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 8510: } else {
8511: $prefix=$perlvar{'lonHostID'};
8512: }
8513: return unpack("%32C*",$prefix);
8514: }
8515:
1.76 www 8516: sub ireceipt {
1.474 albertel 8517: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 8518:
8519: my $return =&recprefix($fucourseid).'-';
8520:
8521: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8522: $env{'request.state'} eq 'construct') {
8523: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8524: return $return;
8525: }
8526:
1.76 www 8527: my $cuname=unpack("%32C*",$funame);
8528: my $cudom=unpack("%32C*",$fudom);
8529: my $cucourseid=unpack("%32C*",$fucourseid);
8530: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 8531: my $cunique=&recunique($fucourseid);
1.474 albertel 8532: my $cpart=unpack("%32S*",$part);
1.835 albertel 8533: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8534:
1.790 albertel 8535: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 8536:
8537: $return.= ($cunique%$cuname+
8538: $cunique%$cudom+
8539: $cusymb%$cuname+
8540: $cusymb%$cudom+
8541: $cucourseid%$cuname+
8542: $cucourseid%$cudom+
8543: $cpart%$cuname+
8544: $cpart%$cudom);
8545: } else {
8546: $return.= ($cunique%$cuname+
8547: $cunique%$cudom+
8548: $cusymb%$cuname+
8549: $cusymb%$cudom+
8550: $cucourseid%$cuname+
8551: $cucourseid%$cudom);
8552: }
8553: return $return;
1.76 www 8554: }
8555:
8556: sub receipt {
1.474 albertel 8557: my ($part)=@_;
1.790 albertel 8558: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 8559: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 8560: }
1.260 ng 8561:
1.790 albertel 8562: sub whichuser {
8563: my ($passedsymb)=@_;
8564: my ($symb,$courseid,$domain,$name,$publicuser);
8565: if (defined($env{'form.grade_symb'})) {
8566: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8567: my $allowed=&allowed('vgr',$tmp_courseid);
8568: if (!$allowed &&
8569: exists($env{'request.course.sec'}) &&
8570: $env{'request.course.sec'} !~ /^\s*$/) {
8571: $allowed=&allowed('vgr',$tmp_courseid.
8572: '/'.$env{'request.course.sec'});
8573: }
8574: if ($allowed) {
8575: ($symb)=&get_env_multiple('form.grade_symb');
8576: $courseid=$tmp_courseid;
8577: ($domain)=&get_env_multiple('form.grade_domain');
8578: ($name)=&get_env_multiple('form.grade_username');
8579: return ($symb,$courseid,$domain,$name,$publicuser);
8580: }
8581: }
8582: if (!$passedsymb) {
8583: $symb=&symbread();
8584: } else {
8585: $symb=$passedsymb;
8586: }
8587: $courseid=$env{'request.course.id'};
8588: $domain=$env{'user.domain'};
8589: $name=$env{'user.name'};
8590: if ($name eq 'public' && $domain eq 'public') {
8591: if (!defined($env{'form.username'})) {
8592: $env{'form.username'}.=time.rand(10000000);
8593: }
8594: $name.=$env{'form.username'};
8595: }
8596: return ($symb,$courseid,$domain,$name,$publicuser);
8597:
8598: }
8599:
1.36 albertel 8600: # ------------------------------------------------------------ Serves up a file
1.472 albertel 8601: # returns either the contents of the file or
8602: # -1 if the file doesn't exist
1.481 raeburn 8603: #
8604: # if the target is a file that was uploaded via DOCS,
8605: # a check will be made to see if a current copy exists on the local server,
8606: # if it does this will be served, otherwise a copy will be retrieved from
8607: # the home server for the course and stored in /home/httpd/html/userfiles on
8608: # the local server.
1.472 albertel 8609:
1.36 albertel 8610: sub getfile {
1.538 albertel 8611: my ($file) = @_;
1.609 banghart 8612: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 8613: &repcopy($file);
8614: return &readfile($file);
8615: }
8616:
8617: sub repcopy_userfile {
8618: my ($file)=@_;
1.609 banghart 8619: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 8620: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 8621: my ($cdom,$cnum,$filename) =
1.811 albertel 8622: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 8623: my $uri="/uploaded/$cdom/$cnum/$filename";
8624: if (-e "$file") {
1.828 www 8625: # we already have a local copy, check it out
1.538 albertel 8626: my @fileinfo = stat($file);
1.828 www 8627: my $rtncode;
8628: my $info;
1.538 albertel 8629: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 8630: if ($lwpresp ne 'ok') {
1.828 www 8631: # there is no such file anymore, even though we had a local copy
1.482 albertel 8632: if ($rtncode eq '404') {
1.538 albertel 8633: unlink($file);
1.482 albertel 8634: }
8635: return -1;
8636: }
8637: if ($info < $fileinfo[9]) {
1.828 www 8638: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 8639: return 'ok';
1.828 www 8640: } else {
8641: # the file is outdated, get rid of it
8642: unlink($file);
1.482 albertel 8643: }
1.828 www 8644: }
8645: # one way or the other, at this point, we don't have the file
8646: # construct the correct path for the file
8647: my @parts = ($cdom,$cnum);
8648: if ($filename =~ m|^(.+)/[^/]+$|) {
8649: push @parts, split(/\//,$1);
8650: }
8651: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8652: foreach my $part (@parts) {
8653: $path .= '/'.$part;
8654: if (!-e $path) {
8655: mkdir($path,0770);
1.482 albertel 8656: }
8657: }
1.828 www 8658: # now the path exists for sure
8659: # get a user agent
8660: my $ua=new LWP::UserAgent;
8661: my $transferfile=$file.'.in.transfer';
8662: # FIXME: this should flock
8663: if (-e $transferfile) { return 'ok'; }
8664: my $request;
8665: $uri=~s/^\///;
1.980 raeburn 8666: my $homeserver = &homeserver($cnum,$cdom);
8667: my $protocol = $protocol{$homeserver};
8668: $protocol = 'http' if ($protocol ne 'https');
8669: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 8670: my $response=$ua->request($request,$transferfile);
8671: # did it work?
8672: if ($response->is_error()) {
8673: unlink($transferfile);
8674: &logthis("Userfile repcopy failed for $uri");
8675: return -1;
8676: }
8677: # worked, rename the transfer file
8678: rename($transferfile,$file);
1.607 raeburn 8679: return 'ok';
1.481 raeburn 8680: }
8681:
1.517 albertel 8682: sub tokenwrapper {
8683: my $uri=shift;
1.980 raeburn 8684: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 8685: $uri=~s|^/||;
1.620 albertel 8686: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 8687: my $token=$1;
1.552 albertel 8688: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8689: if ($udom && $uname && $file) {
8690: $file=~s|(\?\.*)*$||;
1.949 raeburn 8691: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 8692: my $homeserver = &homeserver($uname,$udom);
8693: my $protocol = $protocol{$homeserver};
8694: $protocol = 'http' if ($protocol ne 'https');
8695: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 8696: (($uri=~/\?/)?'&':'?').'token='.$token.
8697: '&tokenissued='.$perlvar{'lonHostID'};
8698: } else {
8699: return '/adm/notfound.html';
8700: }
8701: }
8702:
1.828 www 8703: # call with reqtype HEAD: get last modification time
8704: # call with reqtype GET: get the file contents
8705: # Do not call this with reqtype GET for large files! It loads everything into memory
8706: #
1.481 raeburn 8707: sub getuploaded {
8708: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8709: $uri=~s/^\///;
1.980 raeburn 8710: my $homeserver = &homeserver($cnum,$cdom);
8711: my $protocol = $protocol{$homeserver};
8712: $protocol = 'http' if ($protocol ne 'https');
8713: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 8714: my $ua=new LWP::UserAgent;
8715: my $request=new HTTP::Request($reqtype,$uri);
8716: my $response=$ua->request($request);
8717: $$rtncode = $response->code;
1.482 albertel 8718: if (! $response->is_success()) {
8719: return 'failed';
8720: }
8721: if ($reqtype eq 'HEAD') {
1.486 www 8722: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 8723: } elsif ($reqtype eq 'GET') {
8724: $$info = $response->content;
1.472 albertel 8725: }
1.482 albertel 8726: return 'ok';
1.36 albertel 8727: }
8728:
1.481 raeburn 8729: sub readfile {
8730: my $file = shift;
8731: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8732: my $fh;
8733: open($fh,"<$file");
8734: my $a='';
1.800 albertel 8735: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 8736: return $a;
8737: }
8738:
1.36 albertel 8739: sub filelocation {
1.590 banghart 8740: my ($dir,$file) = @_;
8741: my $location;
8742: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 8743:
8744: if ($file =~ m-^/adm/-) {
8745: $file=~s-^/adm/wrapper/-/-;
8746: $file=~s-^/adm/coursedocs/showdoc/-/-;
8747: }
1.882 albertel 8748:
1.590 banghart 8749: if ($file=~m:^/~:) { # is a contruction space reference
8750: $location = $file;
8751: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 8752: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 8753: # is a correct contruction space reference
8754: $location = $file;
1.956 raeburn 8755: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8756: $location = $file;
1.609 banghart 8757: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 8758: my ($udom,$uname,$filename)=
1.811 albertel 8759: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 8760: my $home=&homeserver($uname,$udom);
8761: my $is_me=0;
8762: my @ids=¤t_machine_ids();
8763: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8764: if ($is_me) {
1.955 raeburn 8765: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 8766: } else {
8767: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8768: $udom.'/'.$uname.'/'.$filename;
8769: }
1.882 albertel 8770: } elsif ($file =~ m-^/adm/-) {
8771: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 8772: } else {
8773: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8774: $file=~s:^/res/:/:;
8775: if ( !( $file =~ m:^/:) ) {
8776: $location = $dir. '/'.$file;
8777: } else {
8778: $location = '/home/httpd/html/res'.$file;
8779: }
1.59 albertel 8780: }
1.590 banghart 8781: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 8782: while ($location=~m{/\.\./}) {
8783: if ($location =~ m{/[^/]+/\.\./}) {
8784: $location=~ s{/[^/]+/\.\./}{/}g;
8785: } else {
8786: $location=~ s{/\.\./}{/}g;
8787: }
8788: } #remove dir/..
1.590 banghart 8789: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
8790: return $location;
1.46 www 8791: }
1.36 albertel 8792:
1.46 www 8793: sub hreflocation {
8794: my ($dir,$file)=@_;
1.980 raeburn 8795: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 8796: $file=filelocation($dir,$file);
1.700 albertel 8797: } elsif ($file=~m-^/adm/-) {
8798: $file=~s-^/adm/wrapper/-/-;
8799: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 8800: }
8801: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8802: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 8803: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8804: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 8805: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 8806: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 8807: -/uploaded/$1/$2/-x;
1.46 www 8808: }
1.913 albertel 8809: if ($file=~ m{^/userfiles/}) {
8810: $file =~ s{^/userfiles/}{/uploaded/};
8811: }
1.462 albertel 8812: return $file;
1.465 albertel 8813: }
8814:
8815: sub current_machine_domains {
1.853 albertel 8816: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8817: }
8818:
8819: sub machine_domains {
8820: my ($hostname) = @_;
1.465 albertel 8821: my @domains;
1.838 albertel 8822: my %hostname = &all_hostnames();
1.465 albertel 8823: while( my($id, $name) = each(%hostname)) {
1.467 matthew 8824: # &logthis("-$id-$name-$hostname-");
1.465 albertel 8825: if ($hostname eq $name) {
1.844 albertel 8826: push(@domains,&host_domain($id));
1.465 albertel 8827: }
8828: }
8829: return @domains;
8830: }
8831:
8832: sub current_machine_ids {
1.853 albertel 8833: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8834: }
8835:
8836: sub machine_ids {
8837: my ($hostname) = @_;
8838: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 8839: my @ids;
1.888 albertel 8840: my %name_to_host = &all_names();
1.889 albertel 8841: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
8842: return @{ $name_to_host{$hostname} };
8843: }
8844: return;
1.31 www 8845: }
8846:
1.824 raeburn 8847: sub additional_machine_domains {
8848: my @domains;
8849: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
8850: while( my $line = <$fh>) {
8851: $line =~ s/\s//g;
8852: push(@domains,$line);
8853: }
8854: return @domains;
8855: }
8856:
8857: sub default_login_domain {
8858: my $domain = $perlvar{'lonDefDomain'};
8859: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8860: foreach my $posdom (¤t_machine_domains(),
8861: &additional_machine_domains()) {
8862: if (lc($posdom) eq lc($testdomain)) {
8863: $domain=$posdom;
8864: last;
8865: }
8866: }
8867: return $domain;
8868: }
8869:
1.31 www 8870: # ------------------------------------------------------------- Declutters URLs
8871:
8872: sub declutter {
8873: my $thisfn=shift;
1.569 albertel 8874: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8875: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8876: $thisfn=~s/^\///;
1.697 albertel 8877: $thisfn=~s|^adm/wrapper/||;
8878: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8879: $thisfn=~s/^res\///;
1.235 www 8880: $thisfn=~s/\?.+$//;
1.268 www 8881: return $thisfn;
8882: }
8883:
8884: # ------------------------------------------------------------- Clutter up URLs
8885:
8886: sub clutter {
8887: my $thisfn='/'.&declutter(shift);
1.887 albertel 8888: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8889: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8890: $thisfn='/res'.$thisfn;
8891: }
1.694 albertel 8892: if ($thisfn !~m|/adm|) {
1.695 albertel 8893: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8894: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8895: } else {
8896: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8897: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8898: if ($embstyle eq 'ssi'
8899: || ($embstyle eq 'hdn')
8900: || ($embstyle eq 'rat')
8901: || ($embstyle eq 'prv')
8902: || ($embstyle eq 'ign')) {
8903: #do nothing with these
8904: } elsif (($embstyle eq 'img')
1.695 albertel 8905: || ($embstyle eq 'emb')
8906: || ($embstyle eq 'wrp')) {
8907: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8908: } elsif ($embstyle eq 'unk'
8909: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8910: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8911: } else {
1.718 www 8912: # &logthis("Got a blank emb style");
1.695 albertel 8913: }
1.694 albertel 8914: }
8915: }
1.31 www 8916: return $thisfn;
1.12 www 8917: }
8918:
1.787 albertel 8919: sub clutter_with_no_wrapper {
8920: my $uri = &clutter(shift);
8921: if ($uri =~ m-^/adm/-) {
8922: $uri =~ s-^/adm/wrapper/-/-;
8923: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8924: }
8925: return $uri;
8926: }
8927:
1.557 albertel 8928: sub freeze_escape {
8929: my ($value)=@_;
8930: if (ref($value)) {
8931: $value=&nfreeze($value);
8932: return '__FROZEN__'.&escape($value);
8933: }
8934: return &escape($value);
8935: }
8936:
1.11 www 8937:
1.557 albertel 8938: sub thaw_unescape {
8939: my ($value)=@_;
8940: if ($value =~ /^__FROZEN__/) {
8941: substr($value,0,10,undef);
8942: $value=&unescape($value);
8943: return &thaw($value);
8944: }
8945: return &unescape($value);
8946: }
8947:
1.436 albertel 8948: sub correct_line_ends {
8949: my ($result)=@_;
8950: $$result =~s/\r\n/\n/mg;
8951: $$result =~s/\r/\n/mg;
1.415 albertel 8952: }
1.1 albertel 8953: # ================================================================ Main Program
8954:
1.184 www 8955: sub goodbye {
1.204 albertel 8956: &logthis("Starting Shut down");
1.443 albertel 8957: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8958: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8959: #converted
1.599 albertel 8960: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8961: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8962: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8963: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8964: #1.1 only
1.870 albertel 8965: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8966: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8967: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8968: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8969: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8970: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8971: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8972: &flushcourselogs();
8973: &logthis("Shutting down");
8974: }
8975:
1.852 albertel 8976: sub get_dns {
1.869 albertel 8977: my ($url,$func,$ignore_cache) = @_;
8978: if (!$ignore_cache) {
8979: my ($content,$cached)=
8980: &Apache::lonnet::is_cached_new('dns',$url);
8981: if ($cached) {
8982: &$func($content);
8983: return;
8984: }
8985: }
8986:
8987: my %alldns;
1.852 albertel 8988: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8989: foreach my $dns (<$config>) {
8990: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 8991: my $line = $1;
8992: my ($host,$protocol) = split(/:/,$line);
8993: if ($protocol ne 'https') {
8994: $protocol = 'http';
8995: }
8996: $alldns{$host} = $protocol;
1.869 albertel 8997: }
8998: while (%alldns) {
8999: my ($dns) = keys(%alldns);
1.852 albertel 9000: my $ua=new LWP::UserAgent;
1.979 raeburn 9001: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9002: my $response=$ua->request($request);
1.979 raeburn 9003: delete($alldns{$dns});
1.852 albertel 9004: next if ($response->is_error());
9005: my @content = split("\n",$response->content);
1.869 albertel 9006: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9007: &$func(\@content);
1.869 albertel 9008: return;
1.852 albertel 9009: }
9010: close($config);
1.871 albertel 9011: my $which = (split('/',$url))[3];
9012: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9013: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9014: my @content = <$config>;
9015: &$func(\@content);
9016: return;
1.852 albertel 9017: }
1.327 albertel 9018: # ------------------------------------------------------------ Read domain file
9019: {
1.852 albertel 9020: my $loaded;
1.846 albertel 9021: my %domain;
9022:
1.852 albertel 9023: sub parse_domain_tab {
9024: my ($lines) = @_;
9025: foreach my $line (@$lines) {
9026: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9027:
1.846 albertel 9028: chomp($line);
1.852 albertel 9029: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9030: my %this_domain;
9031: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9032: 'lang_def', 'city', 'longi', 'lati',
9033: 'primary') {
9034: $this_domain{$field} = shift(@elements);
9035: }
9036: $domain{$name} = \%this_domain;
1.852 albertel 9037: }
9038: }
1.864 albertel 9039:
9040: sub reset_domain_info {
9041: undef($loaded);
9042: undef(%domain);
9043: }
9044:
1.852 albertel 9045: sub load_domain_tab {
1.869 albertel 9046: my ($ignore_cache) = @_;
9047: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9048: my $fh;
9049: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9050: my @lines = <$fh>;
9051: &parse_domain_tab(\@lines);
1.448 albertel 9052: }
1.852 albertel 9053: close($fh);
9054: $loaded = 1;
1.327 albertel 9055: }
1.846 albertel 9056:
9057: sub domain {
1.852 albertel 9058: &load_domain_tab() if (!$loaded);
9059:
1.846 albertel 9060: my ($name,$what) = @_;
9061: return if ( !exists($domain{$name}) );
9062:
9063: if (!$what) {
9064: return $domain{$name}{'description'};
9065: }
9066: return $domain{$name}{$what};
9067: }
1.974 raeburn 9068:
9069: sub domain_info {
9070: &load_domain_tab() if (!$loaded);
9071: return %domain;
9072: }
9073:
1.327 albertel 9074: }
9075:
9076:
1.1 albertel 9077: # ------------------------------------------------------------- Read hosts file
9078: {
1.838 albertel 9079: my %hostname;
1.844 albertel 9080: my %hostdom;
1.845 albertel 9081: my %libserv;
1.852 albertel 9082: my $loaded;
1.888 albertel 9083: my %name_to_host;
1.852 albertel 9084:
9085: sub parse_hosts_tab {
9086: my ($file) = @_;
9087: foreach my $configline (@$file) {
9088: next if ($configline =~ /^(\#|\s*$ )/x);
9089: next if ($configline =~ /^\^/);
9090: chomp($configline);
1.968 raeburn 9091: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 9092: $name=~s/\s//g;
9093: if ($id && $domain && $role && $name) {
9094: $hostname{$id}=$name;
1.888 albertel 9095: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9096: $hostdom{$id}=$domain;
9097: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9098: if (defined($protocol)) {
9099: if ($protocol eq 'https') {
9100: $protocol{$id} = $protocol;
9101: } else {
9102: $protocol{$id} = 'http';
9103: }
1.968 raeburn 9104: } else {
1.969 raeburn 9105: $protocol{$id} = 'http';
1.968 raeburn 9106: }
1.852 albertel 9107: }
9108: }
9109: }
1.864 albertel 9110:
9111: sub reset_hosts_info {
1.897 albertel 9112: &purge_remembered();
1.864 albertel 9113: &reset_domain_info();
9114: &reset_hosts_ip_info();
1.892 albertel 9115: undef(%name_to_host);
1.864 albertel 9116: undef(%hostname);
9117: undef(%hostdom);
9118: undef(%libserv);
9119: undef($loaded);
9120: }
1.1 albertel 9121:
1.852 albertel 9122: sub load_hosts_tab {
1.869 albertel 9123: my ($ignore_cache) = @_;
9124: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9125: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9126: my @config = <$config>;
9127: &parse_hosts_tab(\@config);
9128: close($config);
9129: $loaded=1;
1.1 albertel 9130: }
1.852 albertel 9131:
1.838 albertel 9132: sub hostname {
1.852 albertel 9133: &load_hosts_tab() if (!$loaded);
9134:
1.838 albertel 9135: my ($lonid) = @_;
9136: return $hostname{$lonid};
9137: }
1.845 albertel 9138:
1.838 albertel 9139: sub all_hostnames {
1.852 albertel 9140: &load_hosts_tab() if (!$loaded);
9141:
1.838 albertel 9142: return %hostname;
9143: }
1.845 albertel 9144:
1.888 albertel 9145: sub all_names {
9146: &load_hosts_tab() if (!$loaded);
9147:
9148: return %name_to_host;
9149: }
9150:
1.974 raeburn 9151: sub all_host_domain {
9152: &load_hosts_tab() if (!$loaded);
9153: return %hostdom;
9154: }
9155:
1.845 albertel 9156: sub is_library {
1.852 albertel 9157: &load_hosts_tab() if (!$loaded);
9158:
1.845 albertel 9159: return exists($libserv{$_[0]});
9160: }
9161:
9162: sub all_library {
1.852 albertel 9163: &load_hosts_tab() if (!$loaded);
9164:
1.845 albertel 9165: return %libserv;
9166: }
9167:
1.841 albertel 9168: sub get_servers {
1.852 albertel 9169: &load_hosts_tab() if (!$loaded);
9170:
1.841 albertel 9171: my ($domain,$type) = @_;
9172: my %possible_hosts = ($type eq 'library') ? %libserv
9173: : %hostname;
9174: my %result;
1.842 albertel 9175: if (ref($domain) eq 'ARRAY') {
9176: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9177: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9178: $result{$host} = $hostname;
9179: }
9180: }
9181: } else {
9182: while ( my ($host,$hostname) = each(%possible_hosts)) {
9183: if ($hostdom{$host} eq $domain) {
9184: $result{$host} = $hostname;
9185: }
1.841 albertel 9186: }
9187: }
9188: return %result;
9189: }
1.845 albertel 9190:
1.844 albertel 9191: sub host_domain {
1.852 albertel 9192: &load_hosts_tab() if (!$loaded);
9193:
1.844 albertel 9194: my ($lonid) = @_;
9195: return $hostdom{$lonid};
9196: }
9197:
1.841 albertel 9198: sub all_domains {
1.852 albertel 9199: &load_hosts_tab() if (!$loaded);
9200:
1.841 albertel 9201: my %seen;
9202: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9203: return @uniq;
9204: }
1.1 albertel 9205: }
9206:
1.847 albertel 9207: {
9208: my %iphost;
1.856 albertel 9209: my %name_to_ip;
9210: my %lonid_to_ip;
1.869 albertel 9211:
1.847 albertel 9212: sub get_hosts_from_ip {
9213: my ($ip) = @_;
9214: my %iphosts = &get_iphost();
9215: if (ref($iphosts{$ip})) {
9216: return @{$iphosts{$ip}};
9217: }
9218: return;
1.839 albertel 9219: }
1.864 albertel 9220:
9221: sub reset_hosts_ip_info {
9222: undef(%iphost);
9223: undef(%name_to_ip);
9224: undef(%lonid_to_ip);
9225: }
1.856 albertel 9226:
9227: sub get_host_ip {
9228: my ($lonid) = @_;
9229: if (exists($lonid_to_ip{$lonid})) {
9230: return $lonid_to_ip{$lonid};
9231: }
9232: my $name=&hostname($lonid);
9233: my $ip = gethostbyname($name);
9234: return if (!$ip || length($ip) ne 4);
9235: $ip=inet_ntoa($ip);
9236: $name_to_ip{$name} = $ip;
9237: $lonid_to_ip{$lonid} = $ip;
9238: return $ip;
9239: }
1.847 albertel 9240:
9241: sub get_iphost {
1.869 albertel 9242: my ($ignore_cache) = @_;
1.894 albertel 9243:
1.869 albertel 9244: if (!$ignore_cache) {
9245: if (%iphost) {
9246: return %iphost;
9247: }
9248: my ($ip_info,$cached)=
9249: &Apache::lonnet::is_cached_new('iphost','iphost');
9250: if ($cached) {
9251: %iphost = %{$ip_info->[0]};
9252: %name_to_ip = %{$ip_info->[1]};
9253: %lonid_to_ip = %{$ip_info->[2]};
9254: return %iphost;
9255: }
9256: }
1.894 albertel 9257:
9258: # get yesterday's info for fallback
9259: my %old_name_to_ip;
9260: my ($ip_info,$cached)=
9261: &Apache::lonnet::is_cached_new('iphost','iphost');
9262: if ($cached) {
9263: %old_name_to_ip = %{$ip_info->[1]};
9264: }
9265:
1.888 albertel 9266: my %name_to_host = &all_names();
9267: foreach my $name (keys(%name_to_host)) {
1.847 albertel 9268: my $ip;
9269: if (!exists($name_to_ip{$name})) {
9270: $ip = gethostbyname($name);
9271: if (!$ip || length($ip) ne 4) {
1.894 albertel 9272: if (defined($old_name_to_ip{$name})) {
9273: $ip = $old_name_to_ip{$name};
9274: &logthis("Can't find $name defaulting to old $ip");
9275: } else {
9276: &logthis("Name $name no IP found");
9277: next;
9278: }
9279: } else {
9280: $ip=inet_ntoa($ip);
1.847 albertel 9281: }
9282: $name_to_ip{$name} = $ip;
9283: } else {
9284: $ip = $name_to_ip{$name};
1.653 albertel 9285: }
1.888 albertel 9286: foreach my $id (@{ $name_to_host{$name} }) {
9287: $lonid_to_ip{$id} = $ip;
9288: }
9289: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9290: }
1.869 albertel 9291: &Apache::lonnet::do_cache_new('iphost','iphost',
9292: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9293: 48*60*60);
1.869 albertel 9294:
1.847 albertel 9295: return %iphost;
1.598 albertel 9296: }
9297:
1.992 raeburn 9298: #
9299: # Given a DNS returns the loncapa host name for that DNS
9300: #
9301: sub host_from_dns {
9302: my ($dns) = @_;
9303: my @hosts;
9304: my $ip;
9305:
1.993 raeburn 9306: if (exists($name_to_ip{$dns})) {
1.992 raeburn 9307: $ip = $name_to_ip{$dns};
9308: }
9309: if (!$ip) {
9310: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9311: if (length($ip) == 4) {
9312: $ip = &IO::Socket::inet_ntoa($ip);
9313: }
9314: }
9315: if ($ip) {
9316: @hosts = get_hosts_from_ip($ip);
9317: return $hosts[0];
9318: }
9319: return undef;
1.986 foxr 9320: }
1.992 raeburn 9321:
1.986 foxr 9322: }
9323:
1.862 albertel 9324: BEGIN {
9325:
9326: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9327: unless ($readit) {
9328: {
9329: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9330: %perlvar = (%perlvar,%{$configvars});
9331: }
9332:
9333:
1.1 albertel 9334: # ------------------------------------------------------ Read spare server file
9335: {
1.448 albertel 9336: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9337:
9338: while (my $configline=<$config>) {
9339: chomp($configline);
1.284 matthew 9340: if ($configline) {
1.784 albertel 9341: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9342: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9343: push(@{ $spareid{$type} }, $host);
1.1 albertel 9344: }
9345: }
1.448 albertel 9346: close($config);
1.1 albertel 9347: }
1.11 www 9348: # ------------------------------------------------------------ Read permissions
9349: {
1.448 albertel 9350: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9351:
9352: while (my $configline=<$config>) {
1.448 albertel 9353: chomp($configline);
9354: if ($configline) {
9355: my ($role,$perm)=split(/ /,$configline);
9356: if ($perm ne '') { $pr{$role}=$perm; }
9357: }
1.11 www 9358: }
1.448 albertel 9359: close($config);
1.11 www 9360: }
9361:
9362: # -------------------------------------------- Read plain texts for permissions
9363: {
1.448 albertel 9364: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9365:
9366: while (my $configline=<$config>) {
1.448 albertel 9367: chomp($configline);
9368: if ($configline) {
1.742 raeburn 9369: my ($short,@plain)=split(/:/,$configline);
9370: %{$prp{$short}} = ();
9371: if (@plain > 0) {
9372: $prp{$short}{'std'} = $plain[0];
9373: for (my $i=1; $i<@plain; $i++) {
9374: $prp{$short}{'alt'.$i} = $plain[$i];
9375: }
9376: }
1.448 albertel 9377: }
1.135 www 9378: }
1.448 albertel 9379: close($config);
1.135 www 9380: }
9381:
9382: # ---------------------------------------------------------- Read package table
9383: {
1.448 albertel 9384: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9385:
9386: while (my $configline=<$config>) {
1.483 albertel 9387: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9388: chomp($configline);
9389: my ($short,$plain)=split(/:/,$configline);
9390: my ($pack,$name)=split(/\&/,$short);
9391: if ($plain ne '') {
9392: $packagetab{$pack.'&'.$name.'&name'}=$name;
9393: $packagetab{$short}=$plain;
9394: }
1.11 www 9395: }
1.448 albertel 9396: close($config);
1.329 matthew 9397: }
9398:
9399: # ------------- set up temporary directory
9400: {
9401: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9402:
1.11 www 9403: }
9404:
1.794 albertel 9405: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9406: 'compress_threshold'=> 20_000,
9407: });
1.185 www 9408:
1.281 www 9409: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 9410: $dumpcount=0;
1.958 www 9411: $locknum=0;
1.22 www 9412:
1.163 harris41 9413: &logtouch();
1.672 albertel 9414: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 9415: $readit=1;
1.564 albertel 9416: {
9417: use integer;
9418: my $test=(2**32)+1;
1.568 albertel 9419: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 9420: &logthis(" Detected 64bit platform ($_64bit)");
9421: }
1.195 www 9422: }
1.1 albertel 9423: }
1.179 www 9424:
1.1 albertel 9425: 1;
1.191 harris41 9426: __END__
9427:
1.243 albertel 9428: =pod
9429:
1.191 harris41 9430: =head1 NAME
9431:
1.243 albertel 9432: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 9433:
9434: =head1 SYNOPSIS
9435:
1.243 albertel 9436: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 9437:
9438: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9439:
1.243 albertel 9440: Common parameters:
9441:
9442: =over 4
9443:
9444: =item *
9445:
9446: $uname : an internal username (if $cname expecting a course Id specifically)
9447:
9448: =item *
9449:
9450: $udom : a domain (if $cdom expecting a course's domain specifically)
9451:
9452: =item *
9453:
9454: $symb : a resource instance identifier
9455:
9456: =item *
9457:
9458: $namespace : the name of a .db file that contains the data needed or
9459: being set.
9460:
9461: =back
9462:
1.394 bowersj2 9463: =head1 OVERVIEW
1.191 harris41 9464:
1.394 bowersj2 9465: lonnet provides subroutines which interact with the
9466: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9467: about classes, users, and resources.
1.243 albertel 9468:
9469: For many of these objects you can also use this to store data about
9470: them or modify them in various ways.
1.191 harris41 9471:
1.394 bowersj2 9472: =head2 Symbs
1.191 harris41 9473:
1.394 bowersj2 9474: To identify a specific instance of a resource, LON-CAPA uses symbols
9475: or "symbs"X<symb>. These identifiers are built from the URL of the
9476: map, the resource number of the resource in the map, and the URL of
9477: the resource itself. The latter is somewhat redundant, but might help
9478: if maps change.
9479:
9480: An example is
9481:
9482: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9483:
9484: The respective map entry is
9485:
9486: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9487: title="Problem 2">
9488: </resource>
9489:
9490: Symbs are used by the random number generator, as well as to store and
9491: restore data specific to a certain instance of for example a problem.
9492:
9493: =head2 Storing And Retrieving Data
9494:
9495: X<store()>X<cstore()>X<restore()>Three of the most important functions
9496: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9497: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9498: is is the non-critical message twin of cstore. These functions are for
9499: handlers to store a perl hash to a user's permanent data space in an
9500: easy manner, and to retrieve it again on another call. It is expected
9501: that a handler would use this once at the beginning to retrieve data,
9502: and then again once at the end to send only the new data back.
9503:
9504: The data is stored in the user's data directory on the user's
9505: homeserver under the ID of the course.
9506:
9507: The hash that is returned by restore will have all of the previous
9508: value for all of the elements of the hash.
9509:
9510: Example:
9511:
9512: #creating a hash
9513: my %hash;
9514: $hash{'foo'}='bar';
9515:
9516: #storing it
9517: &Apache::lonnet::cstore(\%hash);
9518:
9519: #changing a value
9520: $hash{'foo'}='notbar';
9521:
9522: #adding a new value
9523: $hash{'bar'}='foo';
9524: &Apache::lonnet::cstore(\%hash);
9525:
9526: #retrieving the hash
9527: my %history=&Apache::lonnet::restore();
9528:
9529: #print the hash
9530: foreach my $key (sort(keys(%history))) {
9531: print("\%history{$key} = $history{$key}");
9532: }
9533:
9534: Will print out:
1.191 harris41 9535:
1.394 bowersj2 9536: %history{1:foo} = bar
9537: %history{1:keys} = foo:timestamp
9538: %history{1:timestamp} = 990455579
9539: %history{2:bar} = foo
9540: %history{2:foo} = notbar
9541: %history{2:keys} = foo:bar:timestamp
9542: %history{2:timestamp} = 990455580
9543: %history{bar} = foo
9544: %history{foo} = notbar
9545: %history{timestamp} = 990455580
9546: %history{version} = 2
9547:
9548: Note that the special hash entries C<keys>, C<version> and
9549: C<timestamp> were added to the hash. C<version> will be equal to the
9550: total number of versions of the data that have been stored. The
9551: C<timestamp> attribute will be the UNIX time the hash was
9552: stored. C<keys> is available in every historical section to list which
9553: keys were added or changed at a specific historical revision of a
9554: hash.
9555:
9556: B<Warning>: do not store the hash that restore returns directly. This
9557: will cause a mess since it will restore the historical keys as if the
9558: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 9559:
1.394 bowersj2 9560: Calling convention:
1.191 harris41 9561:
1.394 bowersj2 9562: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9563: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 9564:
1.394 bowersj2 9565: For more detailed information, see lonnet specific documentation.
1.191 harris41 9566:
1.394 bowersj2 9567: =head1 RETURN MESSAGES
1.191 harris41 9568:
1.394 bowersj2 9569: =over 4
1.191 harris41 9570:
1.394 bowersj2 9571: =item * B<con_lost>: unable to contact remote host
1.191 harris41 9572:
1.394 bowersj2 9573: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9574: when the connection is brought back up
1.191 harris41 9575:
1.394 bowersj2 9576: =item * B<con_failed>: unable to contact remote host and unable to save message
9577: for later delivery
1.191 harris41 9578:
1.967 bisitz 9579: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 9580:
1.394 bowersj2 9581: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 9582: that was requested
1.191 harris41 9583:
1.243 albertel 9584: =back
1.191 harris41 9585:
1.243 albertel 9586: =head1 PUBLIC SUBROUTINES
1.191 harris41 9587:
1.243 albertel 9588: =head2 Session Environment Functions
1.191 harris41 9589:
1.243 albertel 9590: =over 4
1.191 harris41 9591:
1.394 bowersj2 9592: =item *
9593: X<appenv()>
1.949 raeburn 9594: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 9595: the user envirnoment file, and will be restored for each access this
1.620 albertel 9596: user makes during this session, also modifies the %env for the current
1.949 raeburn 9597: process. Optional rolesarrayref - if defined contains a reference to an array
9598: of roles which are exempt from the restriction on modifying user.role entries
9599: in the user's environment.db and in %env.
1.191 harris41 9600:
9601: =item *
1.394 bowersj2 9602: X<delenv()>
1.987 raeburn 9603: B<delenv($delthis,$regexp)>: removes all items from the session
9604: environment file that begin with $delthis. If the
9605: optional second arg - $regexp - is true, $delthis is treated as a
9606: regular expression, otherwise \Q$delthis\E is used.
9607: The values are also deleted from the current processes %env.
1.191 harris41 9608:
1.795 albertel 9609: =item * get_env_multiple($name)
9610:
9611: gets $name from the %env hash, it seemlessly handles the cases where multiple
9612: values may be defined and end up as an array ref.
9613:
9614: returns an array of values
9615:
1.243 albertel 9616: =back
9617:
9618: =head2 User Information
1.191 harris41 9619:
1.243 albertel 9620: =over 4
1.191 harris41 9621:
9622: =item *
1.394 bowersj2 9623: X<queryauthenticate()>
9624: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 9625: authentication scheme
9626:
9627: =item *
1.394 bowersj2 9628: X<authenticate()>
9629: B<authenticate($uname,$upass,$udom)>: try to
9630: authenticate user from domain's lib servers (first use the current
9631: one). C<$upass> should be the users password.
1.191 harris41 9632:
9633: =item *
1.394 bowersj2 9634: X<homeserver()>
9635: B<homeserver($uname,$udom)>: find the server which has
9636: the user's directory and files (there must be only one), this caches
9637: the answer, and also caches if there is a borken connection.
1.191 harris41 9638:
9639: =item *
1.394 bowersj2 9640: X<idget()>
9641: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9642: (IDs are a unique resource in a domain, there must be only 1 ID per
9643: username, and only 1 username per ID in a specific domain) (returns
9644: hash: id=>name,id=>name)
1.191 harris41 9645:
9646: =item *
1.394 bowersj2 9647: X<idrget()>
9648: B<idrget($udom,@unames)>: find the IDs behind a list of
9649: usernames (returns hash: name=>id,name=>id)
1.191 harris41 9650:
9651: =item *
1.394 bowersj2 9652: X<idput()>
9653: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 9654:
9655: =item *
1.394 bowersj2 9656: X<rolesinit()>
9657: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 9658:
9659: =item *
1.551 albertel 9660: X<getsection()>
9661: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 9662: course $cname, return section name/number or '' for "not in course"
9663: and '-1' for "no section"
9664:
9665: =item *
1.394 bowersj2 9666: X<userenvironment()>
9667: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 9668: passed in @what from the requested user's environment, returns a hash
9669:
1.858 raeburn 9670: =item *
9671: X<userlog_query()>
1.859 albertel 9672: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9673: activity.log file. %filters defines filters applied when parsing the
9674: log file. These can be start or end timestamps, or the type of action
9675: - log to look for Login or Logout events, check for Checkin or
9676: Checkout, role for role selection. The response is in the form
9677: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9678: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 9679:
1.243 albertel 9680: =back
9681:
9682: =head2 User Roles
9683:
9684: =over 4
9685:
9686: =item *
9687:
1.810 raeburn 9688: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 9689: F: full access
9690: U,I,K: authentication modes (cxx only)
9691: '': forbidden
9692: 1: user needs to choose course
9693: 2: browse allowed
1.766 albertel 9694: A: passphrase authentication needed
1.243 albertel 9695:
9696: =item *
9697:
9698: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9699: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9700: and course level
9701:
9702: =item *
9703:
1.988 raeburn 9704: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
9705: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 9706: $type is Course (default) or Community.
1.988 raeburn 9707: If $forcedefault evaluates to true, text returned will be default
9708: text for $type. Otherwise, if this is a course, the text returned
9709: will be a custom name for the role (if defined in the course's
9710: environment). If no custom name is defined the default is returned.
9711:
1.832 raeburn 9712: =item *
9713:
1.935 raeburn 9714: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 9715: All arguments are optional. Returns a hash of a roles, either for
9716: co-author/assistant author roles for a user's Construction Space
1.906 albertel 9717: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 9718: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9719: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9720: For each key, value is set to colon-separated start and end times for
9721: the role. If no username and domain are specified, will default to
1.934 raeburn 9722: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 9723: of role statuses (active, future or previous), roles
9724: (e.g., cc,in, st etc.) and domains of the roles which can be used
9725: to restrict the list of roles reported. If no array ref is
9726: provided for types, will default to return only active roles.
1.834 albertel 9727:
1.243 albertel 9728: =back
9729:
9730: =head2 User Modification
9731:
9732: =over 4
9733:
9734: =item *
9735:
1.957 raeburn 9736: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 9737: user for the level given by URL. Optional start and end dates (leave empty
9738: string or zero for "no date")
1.191 harris41 9739:
9740: =item *
9741:
1.243 albertel 9742: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9743: change a users, password, possible return values are: ok,
9744: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9745: refused
1.191 harris41 9746:
9747: =item *
9748:
1.243 albertel 9749: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 9750:
9751: =item *
9752:
1.963 raeburn 9753: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9754: $forceid,$desiredhome,$email,$inststatus) :
1.243 albertel 9755: modify user
1.191 harris41 9756:
9757: =item *
9758:
1.286 matthew 9759: modifystudent
9760:
1.957 raeburn 9761: modify a student's enrollment and identification information.
1.286 matthew 9762: The course id is resolved based on the current users environment.
9763: This means the envoking user must be a course coordinator or otherwise
9764: associated with a course.
9765:
1.297 matthew 9766: This call is essentially a wrapper for lonnet::modifyuser and
9767: lonnet::modify_student_enrollment
1.286 matthew 9768:
9769: Inputs:
9770:
9771: =over 4
9772:
1.957 raeburn 9773: =item B<$udom> Student's loncapa domain
1.286 matthew 9774:
1.957 raeburn 9775: =item B<$uname> Student's loncapa login name
1.286 matthew 9776:
1.964 bisitz 9777: =item B<$uid> Student/Employee ID
1.286 matthew 9778:
1.957 raeburn 9779: =item B<$umode> Student's authentication mode
1.286 matthew 9780:
1.957 raeburn 9781: =item B<$upass> Student's password
1.286 matthew 9782:
1.957 raeburn 9783: =item B<$first> Student's first name
1.286 matthew 9784:
1.957 raeburn 9785: =item B<$middle> Student's middle name
1.286 matthew 9786:
1.957 raeburn 9787: =item B<$last> Student's last name
1.286 matthew 9788:
1.957 raeburn 9789: =item B<$gene> Student's generation
1.286 matthew 9790:
1.957 raeburn 9791: =item B<$usec> Student's section in course
1.286 matthew 9792:
9793: =item B<$end> Unix time of the roles expiration
9794:
9795: =item B<$start> Unix time of the roles start date
9796:
9797: =item B<$forceid> If defined, allow $uid to be changed
9798:
9799: =item B<$desiredhome> server to use as home server for student
9800:
1.957 raeburn 9801: =item B<$email> Student's permanent e-mail address
9802:
9803: =item B<$type> Type of enrollment (auto or manual)
9804:
1.963 raeburn 9805: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
9806:
9807: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 9808:
1.963 raeburn 9809: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 9810:
1.963 raeburn 9811: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 9812:
1.963 raeburn 9813: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 9814:
1.286 matthew 9815: =back
1.297 matthew 9816:
9817: =item *
9818:
9819: modify_student_enrollment
9820:
9821: Change a students enrollment status in a class. The environment variable
9822: 'role.request.course' must be defined for this function to proceed.
9823:
9824: Inputs:
9825:
9826: =over 4
9827:
9828: =item $udom, students domain
9829:
9830: =item $uname, students name
9831:
9832: =item $uid, students user id
9833:
9834: =item $first, students first name
9835:
9836: =item $middle
9837:
9838: =item $last
9839:
9840: =item $gene
9841:
9842: =item $usec
9843:
9844: =item $end
9845:
9846: =item $start
9847:
1.957 raeburn 9848: =item $type
9849:
9850: =item $locktype
9851:
9852: =item $cid
9853:
9854: =item $selfenroll
9855:
9856: =item $context
9857:
1.297 matthew 9858: =back
9859:
1.191 harris41 9860:
9861: =item *
9862:
1.243 albertel 9863: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
9864: custom role; give a custom role to a user for the level given by URL. Specify
9865: name and domain of role author, and role name
1.191 harris41 9866:
9867: =item *
9868:
1.243 albertel 9869: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 9870:
9871: =item *
9872:
1.243 albertel 9873: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
9874:
9875: =back
9876:
9877: =head2 Course Infomation
9878:
9879: =over 4
1.191 harris41 9880:
9881: =item *
9882:
1.631 albertel 9883: coursedescription($courseid) : returns a hash of information about the
9884: specified course id, including all environment settings for the
9885: course, the description of the course will be in the hash under the
9886: key 'description'
1.191 harris41 9887:
9888: =item *
9889:
1.624 albertel 9890: resdata($name,$domain,$type,@which) : request for current parameter
9891: setting for a specific $type, where $type is either 'course' or 'user',
9892: @what should be a list of parameters to ask about. This routine caches
9893: answers for 5 minutes.
1.243 albertel 9894:
1.877 foxr 9895: =item *
9896:
9897: get_courseresdata($courseid, $domain) : dump the entire course resource
9898: data base, returning a hash that is keyed by the resource name and has
9899: values that are the resource value. I believe that the timestamps and
9900: versions are also returned.
9901:
9902:
1.243 albertel 9903: =back
9904:
9905: =head2 Course Modification
9906:
9907: =over 4
1.191 harris41 9908:
9909: =item *
9910:
1.243 albertel 9911: writecoursepref($courseid,%prefs) : write preferences (environment
9912: database) for a course
1.191 harris41 9913:
9914: =item *
9915:
1.243 albertel 9916: createcourse($udom,$description,$url) : make/modify course
9917:
9918: =back
9919:
9920: =head2 Resource Subroutines
9921:
9922: =over 4
1.191 harris41 9923:
9924: =item *
9925:
1.243 albertel 9926: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 9927:
9928: =item *
9929:
1.243 albertel 9930: repcopy($filename) : subscribes to the requested file, and attempts to
9931: replicate from the owning library server, Might return
1.607 raeburn 9932: 'unavailable', 'not_found', 'forbidden', 'ok', or
9933: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 9934: resource. Expects the local filesystem pathname
9935: (/home/httpd/html/res/....)
9936:
9937: =back
9938:
9939: =head2 Resource Information
9940:
9941: =over 4
1.191 harris41 9942:
9943: =item *
9944:
1.243 albertel 9945: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9946: a vairety of different possible values, $varname should be a request
9947: string, and the other parameters can be used to specify who and what
9948: one is asking about.
9949:
9950: Possible values for $varname are environment.lastname (or other item
9951: from the envirnment hash), user.name (or someother aspect about the
9952: user), resource.0.maxtries (or some other part and parameter of a
9953: resource)
1.204 albertel 9954:
9955: =item *
9956:
1.243 albertel 9957: directcondval($number) : get current value of a condition; reads from a state
9958: string
1.204 albertel 9959:
9960: =item *
9961:
1.243 albertel 9962: condval($condidx) : value of condition index based on state
1.204 albertel 9963:
9964: =item *
9965:
1.243 albertel 9966: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9967: resource's metadata, $what should be either a specific key, or either
9968: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9969: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9970:
9971: this function automatically caches all requests
1.191 harris41 9972:
9973: =item *
9974:
1.243 albertel 9975: metadata_query($query,$custom,$customshow) : make a metadata query against the
9976: network of library servers; returns file handle of where SQL and regex results
9977: will be stored for query
1.191 harris41 9978:
9979: =item *
9980:
1.243 albertel 9981: symbread($filename) : return symbolic list entry (filename argument optional);
9982: returns the data handle
1.191 harris41 9983:
9984: =item *
9985:
1.243 albertel 9986: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9987: a possible symb for the URL in $thisfn, and if is an encryypted
9988: resource that the user accessed using /enc/ returns a 1 on success, 0
9989: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9990: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9991:
1.191 harris41 9992:
9993: =item *
9994:
1.243 albertel 9995: symbclean($symb) : removes versions numbers from a symb, returns the
9996: cleaned symb
1.191 harris41 9997:
9998: =item *
9999:
1.243 albertel 10000: is_on_map($uri) : checks if the $uri is somewhere on the current
10001: course map, user must be in a course for it to work.
1.191 harris41 10002:
10003: =item *
10004:
1.243 albertel 10005: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10006:
10007: =item *
10008:
1.243 albertel 10009: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10010: a random seed, all arguments are optional, if they aren't sent it uses the
10011: environment to derive them. Note: if symb isn't sent and it can't get one
10012: from &symbread it will use the current time as its return value
1.191 harris41 10013:
10014: =item *
10015:
1.243 albertel 10016: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10017: unfakeable, receipt
1.191 harris41 10018:
10019: =item *
10020:
1.620 albertel 10021: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10022:
10023: =item *
10024:
1.243 albertel 10025: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10026:
10027: =item *
10028:
1.243 albertel 10029: 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 10030:
10031: =item *
10032:
1.243 albertel 10033: 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 10034:
10035: =item *
10036:
1.243 albertel 10037: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10038:
10039: =item *
10040:
1.243 albertel 10041: devalidate($symb) : devalidate temporary spreadsheet calculations,
10042: forcing spreadsheet to reevaluate the resource scores next time.
10043:
10044: =back
10045:
10046: =head2 Storing/Retreiving Data
10047:
10048: =over 4
1.191 harris41 10049:
10050: =item *
10051:
1.243 albertel 10052: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10053: for this url; hashref needs to be given and should be a \%hashname; the
10054: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10055: be derived from the env
1.191 harris41 10056:
10057: =item *
10058:
1.243 albertel 10059: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10060: uses critical subroutine
1.191 harris41 10061:
10062: =item *
10063:
1.243 albertel 10064: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10065: all args are optional
1.191 harris41 10066:
10067: =item *
10068:
1.717 albertel 10069: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10070: dumps the complete (or key matching regexp) namespace into a hash
10071: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10072: normally &store()ed into
10073:
10074: $range should be either an integer '100' (give me the first 100
10075: matching records)
10076: or be two integers sperated by a - with no spaces
10077: '30-50' (give me the 30th through the 50th matching
10078: records)
10079:
10080:
10081: =item *
10082:
10083: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10084: replaces a &store() version of data with a replacement set of data
10085: for a particular resource in a namespace passed in the $storehash hash
10086: reference
10087:
10088: =item *
10089:
1.243 albertel 10090: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10091: works very similar to store/cstore, but all data is stored in a
10092: temporary location and can be reset using tmpreset, $storehash should
10093: be a hash reference, returns nothing on success
1.191 harris41 10094:
10095: =item *
10096:
1.243 albertel 10097: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10098: similar to restore, but all data is stored in a temporary location and
10099: can be reset using tmpreset. Returns a hash of values on success,
10100: error string otherwise.
1.191 harris41 10101:
10102: =item *
10103:
1.243 albertel 10104: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10105: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 10106:
10107: =item *
10108:
1.243 albertel 10109: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10110: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 10111:
10112: =item *
10113:
1.243 albertel 10114: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10115: namesp ($udom and $uname are optional)
1.191 harris41 10116:
10117: =item *
10118:
1.702 albertel 10119: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 10120: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 10121: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 10122:
1.702 albertel 10123: $range should be either an integer '100' (give me the first 100
10124: matching records)
10125: or be two integers sperated by a - with no spaces
10126: '30-50' (give me the 30th through the 50th matching
10127: records)
1.449 matthew 10128: =item *
10129:
10130: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10131: $store can be a scalar, an array reference, or if the amount to be
10132: incremented is > 1, a hash reference.
10133:
10134: ($udom and $uname are optional)
1.191 harris41 10135:
10136: =item *
10137:
1.243 albertel 10138: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10139: ($udom and $uname are optional)
1.191 harris41 10140:
10141: =item *
10142:
1.243 albertel 10143: cput($namespace,$storehash,$udom,$uname) : critical put
10144: ($udom and $uname are optional)
1.191 harris41 10145:
10146: =item *
10147:
1.748 albertel 10148: newput($namespace,$storehash,$udom,$uname) :
10149:
10150: Attempts to store the items in the $storehash, but only if they don't
10151: currently exist, if this succeeds you can be certain that you have
10152: successfully created a new key value pair in the $namespace db.
10153:
10154:
10155: Args:
10156: $namespace: name of database to store values to
10157: $storehash: hashref to store to the db
10158: $udom: (optional) domain of user containing the db
10159: $uname: (optional) name of user caontaining the db
10160:
10161: Returns:
10162: 'ok' -> succeeded in storing all keys of $storehash
10163: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10164: least <key> already existed in the db (other
10165: requested keys may also already exist)
1.967 bisitz 10166: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 10167: 'con_lost' -> unable to contact request server
10168: 'refused' -> action was not allowed by remote machine
10169:
10170:
10171: =item *
10172:
1.243 albertel 10173: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10174: reference filled in from namesp (encrypts the return communication)
10175: ($udom and $uname are optional)
1.191 harris41 10176:
10177: =item *
10178:
1.243 albertel 10179: log($udom,$name,$home,$message) : write to permanent log for user; use
10180: critical subroutine
10181:
1.806 raeburn 10182: =item *
10183:
1.860 raeburn 10184: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10185: array reference filled in from namespace found in domain level on either
10186: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 10187:
10188: =item *
10189:
1.860 raeburn 10190: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10191: domain level either on specified domain server ($uhome) or primary domain
10192: server ($udom and $uhome are optional)
1.806 raeburn 10193:
1.943 raeburn 10194: =item *
10195:
10196: get_domain_defaults($target_domain) : returns hash with defaults for
10197: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10198: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10199: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10200: Values are retrieved from cache (if current), or from domain's configuration.db
10201: (if available), or lastly from values in lonTabs/dns_domain,tab,
10202: or lonTabs/domain.tab.
10203:
10204: %domdefaults = &get_auth_defaults($target_domain);
10205:
1.243 albertel 10206: =back
10207:
10208: =head2 Network Status Functions
10209:
10210: =over 4
1.191 harris41 10211:
10212: =item *
10213:
10214: dirlist($uri) : return directory list based on URI
10215:
10216: =item *
10217:
1.243 albertel 10218: spareserver() : find server with least workload from spare.tab
10219:
1.986 foxr 10220:
10221: =item *
10222:
10223: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10224: if there is no corresponding loncapa host.
10225:
1.243 albertel 10226: =back
10227:
1.986 foxr 10228:
1.243 albertel 10229: =head2 Apache Request
10230:
10231: =over 4
1.191 harris41 10232:
10233: =item *
10234:
1.243 albertel 10235: ssi($url,%hash) : server side include, does a complete request cycle on url to
10236: localhost, posts hash
10237:
10238: =back
10239:
10240: =head2 Data to String to Data
10241:
10242: =over 4
1.191 harris41 10243:
10244: =item *
10245:
1.243 albertel 10246: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10247: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 10248:
10249: =item *
10250:
1.243 albertel 10251: hashref2str($hashref) : convert a hashref into a string complete with
10252: escaping and '=' and '&' separators, supports elements that are
10253: arrayrefs and hashrefs
1.191 harris41 10254:
10255: =item *
10256:
1.243 albertel 10257: arrayref2str($arrayref) : convert an arrayref into a string complete
10258: with escaping and '&' separators, supports elements that are arrayrefs
10259: and hashrefs
1.191 harris41 10260:
10261: =item *
10262:
1.243 albertel 10263: str2hash($string) : convert string to hash using unescaping and
10264: splitting on '=' and '&', supports elements that are arrayrefs and
10265: hashrefs
1.191 harris41 10266:
10267: =item *
10268:
1.243 albertel 10269: str2array($string) : convert string to hash using unescaping and
10270: splitting on '&', supports elements that are arrayrefs and hashrefs
10271:
10272: =back
10273:
10274: =head2 Logging Routines
10275:
10276: =over 4
10277:
10278: These routines allow one to make log messages in the lonnet.log and
10279: lonnet.perm logfiles.
1.191 harris41 10280:
10281: =item *
10282:
1.243 albertel 10283: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 10284:
10285: =item *
10286:
1.243 albertel 10287: logthis() : append message to the normal lonnet.log file, it gets
10288: preiodically rolled over and deleted.
1.191 harris41 10289:
10290: =item *
10291:
1.243 albertel 10292: logperm() : append a permanent message to lonnet.perm.log, this log
10293: file never gets deleted by any automated portion of the system, only
10294: messages of critical importance should go in here.
10295:
10296: =back
10297:
10298: =head2 General File Helper Routines
10299:
10300: =over 4
1.191 harris41 10301:
10302: =item *
10303:
1.481 raeburn 10304: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10305: (a) files in /uploaded
10306: (i) If a local copy of the file exists -
10307: compares modification date of local copy with last-modified date for
10308: definitive version stored on home server for course. If local copy is
10309: stale, requests a new version from the home server and stores it.
10310: If the original has been removed from the home server, then local copy
10311: is unlinked.
10312: (ii) If local copy does not exist -
10313: requests the file from the home server and stores it.
10314:
10315: If $caller is 'uploadrep':
10316: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10317: for request for files originally uploaded via DOCS.
10318: - returns 'ok' if fresh local copy now available, -1 otherwise.
10319:
10320: Otherwise:
10321: This indicates a call from the content generation phase of the request.
10322: - returns the entire contents of the file or -1.
10323:
10324: (b) files in /res
10325: - returns the entire contents of a file or -1;
10326: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 10327:
1.712 albertel 10328:
10329: =item *
10330:
10331: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10332: reference
10333:
10334: returns either a stat() list of data about the file or an empty list
10335: if the file doesn't exist or couldn't find out about it (connection
10336: problems or user unknown)
10337:
1.191 harris41 10338: =item *
10339:
1.243 albertel 10340: filelocation($dir,$file) : returns file system location of a file
10341: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10342: directory that relative $file lookups are to looked in ($dir of /a/dir
10343: and a file of ../bob will become /a/bob)
1.191 harris41 10344:
10345: =item *
10346:
10347: hreflocation($dir,$file) : returns file system location or a URL; same as
10348: filelocation except for hrefs
10349:
10350: =item *
10351:
10352: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10353:
1.243 albertel 10354: =back
10355:
1.608 albertel 10356: =head2 Usererfile file routines (/uploaded*)
10357:
10358: =over 4
10359:
10360: =item *
10361:
10362: userfileupload(): main rotine for putting a file in a user or course's
10363: filespace, arguments are,
10364:
1.620 albertel 10365: formname - required - this is the name of the element in $env where the
1.608 albertel 10366: filename, and the contents of the file to create/modifed exist
1.620 albertel 10367: the filename is in $env{'form.'.$formname.'.filename'} and the
10368: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10369: coursedoc - if true, store the file in the course of the active role
10370: of the current user
10371: subdir - required - subdirectory to put the file in under ../userfiles/
10372: if undefined, it will be placed in "unknown"
10373:
10374: (This routine calls clean_filename() to remove any dangerous
10375: characters from the filename, and then calls finuserfileupload() to
10376: complete the transaction)
10377:
10378: returns either the url of the uploaded file (/uploaded/....) if successful
10379: and /adm/notfound.html if unsuccessful
10380:
10381: =item *
10382:
10383: clean_filename(): routine for cleaing a filename up for storage in
10384: userfile space, argument is:
10385:
10386: filename - proposed filename
10387:
10388: returns: the new clean filename
10389:
10390: =item *
10391:
10392: finishuserfileupload(): routine that creaes and sends the file to
10393: userspace, probably shouldn't be called directly
10394:
10395: docuname: username or courseid of destination for the file
10396: docudom: domain of user/course of destination for the file
10397: formname: same as for userfileupload()
10398: fname: filename (inculding subdirectories) for the file
10399:
10400: returns either the url of the uploaded file (/uploaded/....) if successful
10401: and /adm/notfound.html if unsuccessful
10402:
10403: =item *
10404:
10405: renameuserfile(): renames an existing userfile to a new name
10406:
10407: Args:
10408: docuname: username or courseid of destination for the file
10409: docudom: domain of user/course of destination for the file
10410: old: current file name (including any subdirs under userfiles)
10411: new: desired file name (including any subdirs under userfiles)
10412:
10413: =item *
10414:
10415: mkdiruserfile(): creates a directory is a userfiles dir
10416:
10417: Args:
10418: docuname: username or courseid of destination for the file
10419: docudom: domain of user/course of destination for the file
10420: dir: dir to create (including any subdirs under userfiles)
10421:
10422: =item *
10423:
10424: removeuserfile(): removes a file that exists in userfiles
10425:
10426: Args:
10427: docuname: username or courseid of destination for the file
10428: docudom: domain of user/course of destination for the file
10429: fname: filname to delete (including any subdirs under userfiles)
10430:
10431: =item *
10432:
10433: removeuploadedurl(): convience function for removeuserfile()
10434:
10435: Args:
10436: url: a full /uploaded/... url to delete
10437:
1.747 albertel 10438: =item *
10439:
10440: get_portfile_permissions():
10441: Args:
10442: domain: domain of user or course contain the portfolio files
10443: user: name of user or num of course contain the portfolio files
10444: Returns:
10445: hashref of a dump of the proper file_permissions.db
10446:
10447:
10448: =item *
10449:
10450: get_access_controls():
10451:
10452: Args:
10453: current_permissions: the hash ref returned from get_portfile_permissions()
10454: group: (optional) the group you want the files associated with
10455: file: (optional) the file you want access info on
10456:
10457: Returns:
1.749 raeburn 10458: a hash (keys are file names) of hashes containing
10459: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10460: values are XML containing access control settings (see below)
1.747 albertel 10461:
10462: Internal notes:
10463:
1.749 raeburn 10464: access controls are stored in file_permissions.db as key=value pairs.
10465: key -> path to file/file_name\0uniqueID:scope_end_start
10466: where scope -> public,guest,course,group,domains or users.
10467: end -> UNIX time for end of access (0 -> no end date)
10468: start -> UNIX time for start of access
10469:
10470: value -> XML description of access control
10471: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10472: <start></start>
10473: <end></end>
10474:
10475: <password></password> for scope type = guest
10476:
10477: <domain></domain> for scope type = course or group
10478: <number></number>
10479: <roles id="">
10480: <role></role>
10481: <access></access>
10482: <section></section>
10483: <group></group>
10484: </roles>
10485:
10486: <dom></dom> for scope type = domains
10487:
10488: <users> for scope type = users
10489: <user>
10490: <uname></uname>
10491: <udom></udom>
10492: </user>
10493: </users>
10494: </scope>
10495:
10496: Access data is also aggregated for each file in an additional key=value pair:
10497: key -> path to file/file_name\0accesscontrol
10498: value -> reference to hash
10499: hash contains key = value pairs
10500: where key = uniqueID:scope_end_start
10501: value = UNIX time record was last updated
10502:
10503: Used to improve speed of look-ups of access controls for each file.
10504:
10505: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10506:
10507: modify_access_controls():
10508:
10509: Modifies access controls for a portfolio file
10510: Args
10511: 1. file name
10512: 2. reference to hash of required changes,
10513: 3. domain
10514: 4. username
10515: where domain,username are the domain of the portfolio owner
10516: (either a user or a course)
10517:
10518: Returns:
10519: 1. result of additions or updates ('ok' or 'error', with error message).
10520: 2. result of deletions ('ok' or 'error', with error message).
10521: 3. reference to hash of any new or updated access controls.
10522: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10523: key = integer (inbound ID)
10524: value = uniqueID
1.747 albertel 10525:
1.608 albertel 10526: =back
10527:
1.243 albertel 10528: =head2 HTTP Helper Routines
10529:
10530: =over 4
10531:
1.191 harris41 10532: =item *
10533:
10534: escape() : unpack non-word characters into CGI-compatible hex codes
10535:
10536: =item *
10537:
10538: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10539:
1.243 albertel 10540: =back
10541:
10542: =head1 PRIVATE SUBROUTINES
10543:
10544: =head2 Underlying communication routines (Shouldn't call)
10545:
10546: =over 4
10547:
10548: =item *
10549:
10550: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10551:
10552: =item *
10553:
10554: reply() : uses subreply to send a message to remote machine, logs all failures
10555:
10556: =item *
10557:
10558: critical() : passes a critical message to another server; if cannot
10559: get through then place message in connection buffer directory and
10560: returns con_delayed, if incapable of saving message, returns
10561: con_failed
10562:
10563: =item *
10564:
10565: reconlonc() : tries to reconnect lonc client processes.
10566:
10567: =back
10568:
10569: =head2 Resource Access Logging
10570:
10571: =over 4
10572:
10573: =item *
10574:
10575: flushcourselogs() : flush (save) buffer logs and access logs
10576:
10577: =item *
10578:
10579: courselog($what) : save message for course in hash
10580:
10581: =item *
10582:
10583: courseacclog($what) : save message for course using &courselog(). Perform
10584: special processing for specific resource types (problems, exams, quizzes, etc).
10585:
1.191 harris41 10586: =item *
10587:
10588: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10589: as a PerlChildExitHandler
1.243 albertel 10590:
10591: =back
10592:
10593: =head2 Other
10594:
10595: =over 4
10596:
10597: =item *
10598:
10599: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 10600:
10601: =back
10602:
10603: =cut
1.877 foxr 10604:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>