Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.988
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.988 ! raeburn 4: # $Id: lonnet.pm,v 1.987 2009/02/18 06:54:22 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
1.986 foxr 77: use IO::Socket;
1.977 amueller 78:
1.486 www 79: # use Date::Parse;
1.871 albertel 80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968 raeburn 81: $_64bit %env %protocol);
1.871 albertel 82:
83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
84: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
85: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 86: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 87:
1.1 albertel 88: use IO::Socket;
1.31 www 89: use GDBM_File;
1.208 albertel 90: use HTML::LCParser;
1.88 www 91: use Fcntl qw(:flock);
1.870 albertel 92: use Storable qw(thaw nfreeze);
1.539 albertel 93: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 94: use Cache::Memcached;
1.676 albertel 95: use Digest::MD5;
1.790 albertel 96: use Math::Random;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.676 albertel 99:
1.195 www 100: my $readit;
1.550 foxr 101: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 102:
1.977 amueller 103: my $upload_photo_form = 0; #Variable to check when user upload a photo 0=not 1=true
104:
1.619 albertel 105: require Exporter;
106:
107: our @ISA = qw (Exporter);
108: our @EXPORT = qw(%env);
109:
1.449 matthew 110:
1.1 albertel 111: # --------------------------------------------------------------------- Logging
1.729 www 112: {
113: my $logid;
114: sub instructor_log {
1.957 raeburn 115: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
116: if (($cnum eq '') || ($cdom eq '')) {
117: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
118: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
119: }
1.729 www 120: $logid++;
1.957 raeburn 121: my $now = time();
122: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 123: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 124: { $id => {
125: 'exe_uname' => $env{'user.name'},
126: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 127: 'exe_time' => $now,
1.730 www 128: 'exe_ip' => $ENV{'REMOTE_ADDR'},
129: 'delflag' => $delflag,
130: 'logentry' => $storehash,
131: 'uname' => $uname,
132: 'udom' => $udom,
133: }
1.957 raeburn 134: },$cdom,$cnum);
1.729 www 135: }
136: }
1.1 albertel 137:
1.163 harris41 138: sub logtouch {
139: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 140: unless (-e "$execdir/logs/lonnet.log") {
141: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 142: close $fh;
143: }
144: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
145: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
146: }
147:
1.1 albertel 148: sub logthis {
149: my $message=shift;
150: my $execdir=$perlvar{'lonDaemons'};
151: my $now=time;
152: my $local=localtime($now);
1.448 albertel 153: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 154: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
155: print $fh $logstring;
1.448 albertel 156: close($fh);
157: }
1.1 albertel 158: return 1;
159: }
160:
161: sub logperm {
162: my $message=shift;
163: my $execdir=$perlvar{'lonDaemons'};
164: my $now=time;
165: my $local=localtime($now);
1.448 albertel 166: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
167: print $fh "$now:$message:$local\n";
168: close($fh);
169: }
1.1 albertel 170: return 1;
171: }
172:
1.850 albertel 173: sub create_connection {
1.853 albertel 174: my ($hostname,$lonid) = @_;
1.851 albertel 175: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 176: Type => SOCK_STREAM,
177: Timeout => 10);
178: return 0 if (!$client);
1.890 albertel 179: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 180: my $result = <$client>;
181: chomp($result);
182: return 1 if ($result eq 'done');
183: return 0;
184: }
185:
1.983 raeburn 186: sub get_server_timezone {
187: my ($cnum,$cdom) = @_;
188: my $home=&homeserver($cnum,$cdom);
189: if ($home ne 'no_host') {
190: my $cachetime = 24*3600;
191: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
192: if (defined($cached)) {
193: return $timezone;
194: } else {
195: my $timezone = &reply('servertimezone',$home);
196: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
197: }
198: }
199: }
1.850 albertel 200:
1.1 albertel 201: # -------------------------------------------------- Non-critical communication
202: sub subreply {
203: my ($cmd,$server)=@_;
1.838 albertel 204: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 205: #
206: # With loncnew process trimming, there's a timing hole between lonc server
207: # process exit and the master server picking up the listen on the AF_UNIX
208: # socket. In that time interval, a lock file will exist:
209:
210: my $lockfile=$peerfile.".lock";
211: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
212: sleep(1);
213: }
214: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 215: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 216: #
1.550 foxr 217: # We'll give the connection a few tries before abandoning it. If
218: # connection is not possible, we'll con_lost back to the client.
219: #
220: my $client;
221: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
222: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
223: Type => SOCK_STREAM,
224: Timeout => 10);
1.869 albertel 225: if ($client) {
1.550 foxr 226: last; # Connected!
1.850 albertel 227: } else {
1.853 albertel 228: &create_connection(&hostname($server),$server);
1.550 foxr 229: }
1.850 albertel 230: sleep(1); # Try again later if failed connection.
1.550 foxr 231: }
232: my $answer;
233: if ($client) {
1.704 albertel 234: print $client "sethost:$server:$cmd\n";
1.550 foxr 235: $answer=<$client>;
236: if (!$answer) { $answer="con_lost"; }
237: chomp($answer);
238: } else {
239: $answer = 'con_lost'; # Failed connection.
240: }
1.1 albertel 241: return $answer;
242: }
243:
244: sub reply {
245: my ($cmd,$server)=@_;
1.838 albertel 246: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 247: my $answer=subreply($cmd,$server);
1.65 www 248: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 249: &logthis("<font color=\"blue\">WARNING:".
1.12 www 250: " $cmd to $server returned $answer</font>");
251: }
1.1 albertel 252: return $answer;
253: }
254:
255: # ----------------------------------------------------------- Send USR1 to lonc
256:
257: sub reconlonc {
1.891 albertel 258: my ($lonid) = @_;
259: my $hostname = &hostname($lonid);
260: if ($lonid) {
261: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
262: if ($hostname && -e $peerfile) {
263: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
264: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
265: Type => SOCK_STREAM,
266: Timeout => 10);
267: if ($client) {
268: print $client ("reset_retries\n");
269: my $answer=<$client>;
270: #reset just this one.
271: }
272: }
273: return;
274: }
275:
1.836 www 276: &logthis("Trying to reconnect lonc");
1.1 albertel 277: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 278: if (open(my $fh,"<$loncfile")) {
1.1 albertel 279: my $loncpid=<$fh>;
280: chomp($loncpid);
281: if (kill 0 => $loncpid) {
282: &logthis("lonc at pid $loncpid responding, sending USR1");
283: kill USR1 => $loncpid;
284: sleep 1;
1.836 www 285: } else {
1.12 www 286: &logthis(
1.672 albertel 287: "<font color=\"blue\">WARNING:".
1.12 www 288: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 289: }
290: } else {
1.836 www 291: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 292: }
293: }
294:
295: # ------------------------------------------------------ Critical communication
1.12 www 296:
1.1 albertel 297: sub critical {
298: my ($cmd,$server)=@_;
1.838 albertel 299: unless (&hostname($server)) {
1.672 albertel 300: &logthis("<font color=\"blue\">WARNING:".
1.89 www 301: " Critical message to unknown server ($server)</font>");
302: return 'no_such_host';
303: }
1.1 albertel 304: my $answer=reply($cmd,$server);
305: if ($answer eq 'con_lost') {
306: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 307: my $answer=reply($cmd,$server);
1.1 albertel 308: if ($answer eq 'con_lost') {
309: my $now=time;
310: my $middlename=$cmd;
1.5 www 311: $middlename=substr($middlename,0,16);
1.1 albertel 312: $middlename=~s/\W//g;
313: my $dfilename=
1.305 www 314: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
315: $dumpcount++;
1.1 albertel 316: {
1.448 albertel 317: my $dfh;
318: if (open($dfh,">$dfilename")) {
319: print $dfh "$cmd\n";
320: close($dfh);
321: }
1.1 albertel 322: }
323: sleep 2;
324: my $wcmd='';
325: {
1.448 albertel 326: my $dfh;
327: if (open($dfh,"<$dfilename")) {
328: $wcmd=<$dfh>;
329: close($dfh);
330: }
1.1 albertel 331: }
332: chomp($wcmd);
1.7 www 333: if ($wcmd eq $cmd) {
1.672 albertel 334: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 335: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 336: &logperm("D:$server:$cmd");
337: return 'con_delayed';
338: } else {
1.672 albertel 339: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 340: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 341: &logperm("F:$server:$cmd");
342: return 'con_failed';
343: }
344: }
345: }
346: return $answer;
1.405 albertel 347: }
348:
1.755 albertel 349: # ------------------------------------------- check if return value is an error
350:
351: sub error {
352: my ($result) = @_;
1.756 albertel 353: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 354: if ($2 == 2) { return undef; }
355: return $1;
356: }
357: return undef;
358: }
359:
1.783 albertel 360: sub convert_and_load_session_env {
361: my ($lonidsdir,$handle)=@_;
362: my @profile;
363: {
1.917 albertel 364: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
365: if (!$opened) {
1.915 albertel 366: return 0;
367: }
1.783 albertel 368: flock($idf,LOCK_SH);
369: @profile=<$idf>;
370: close($idf);
371: }
372: my %temp_env;
373: foreach my $line (@profile) {
1.786 albertel 374: if ($line !~ m/=/) {
375: return 0;
376: }
1.783 albertel 377: chomp($line);
378: my ($envname,$envvalue)=split(/=/,$line,2);
379: $temp_env{&unescape($envname)} = &unescape($envvalue);
380: }
381: unlink("$lonidsdir/$handle.id");
382: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
383: 0640)) {
384: %disk_env = %temp_env;
385: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
386: untie(%disk_env);
387: }
1.786 albertel 388: return 1;
1.783 albertel 389: }
390:
1.374 www 391: # ------------------------------------------- Transfer profile into environment
1.780 albertel 392: my $env_loaded;
393: sub transfer_profile_to_env {
1.788 albertel 394: my ($lonidsdir,$handle,$force_transfer) = @_;
395: if (!$force_transfer && $env_loaded) { return; }
1.374 www 396:
1.720 albertel 397: if (!defined($lonidsdir)) {
398: $lonidsdir = $perlvar{'lonIDsDir'};
399: }
400: if (!defined($handle)) {
401: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
402: }
403:
1.786 albertel 404: my $convert;
405: {
1.917 albertel 406: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
407: if (!$opened) {
1.915 albertel 408: return;
409: }
1.786 albertel 410: flock($idf,LOCK_SH);
411: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
412: &GDBM_READER(),0640)) {
413: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
414: untie(%disk_env);
415: } else {
416: $convert = 1;
417: }
418: }
419: if ($convert) {
420: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
421: &logthis("Failed to load session, or convert session.");
422: }
1.374 www 423: }
1.783 albertel 424:
1.786 albertel 425: my %remove;
1.783 albertel 426: while ( my $envname = each(%env) ) {
1.433 matthew 427: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
428: if ($time < time-300) {
1.783 albertel 429: $remove{$key}++;
1.433 matthew 430: }
431: }
432: }
1.783 albertel 433:
1.619 albertel 434: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 435: $env_loaded=1;
1.783 albertel 436: foreach my $expired_key (keys(%remove)) {
1.433 matthew 437: &delenv($expired_key);
1.374 www 438: }
1.1 albertel 439: }
440:
1.916 albertel 441: # ---------------------------------------------------- Check for valid session
442: sub check_for_valid_session {
443: my ($r) = @_;
444: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
445: my $lonid=$cookies{'lonID'};
446: return undef if (!$lonid);
447:
448: my $handle=&LONCAPA::clean_handle($lonid->value);
449: my $lonidsdir=$r->dir_config('lonIDsDir');
450: return undef if (!-e "$lonidsdir/$handle.id");
451:
1.917 albertel 452: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
453: return undef if (!$opened);
1.916 albertel 454:
455: flock($idf,LOCK_SH);
456: my %disk_env;
457: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
458: &GDBM_READER(),0640)) {
459: return undef;
460: }
461:
462: if (!defined($disk_env{'user.name'})
463: || !defined($disk_env{'user.domain'})) {
464: return undef;
465: }
466: return $handle;
467: }
468:
1.830 albertel 469: sub timed_flock {
470: my ($file,$lock_type) = @_;
471: my $failed=0;
472: eval {
473: local $SIG{__DIE__}='DEFAULT';
474: local $SIG{ALRM}=sub {
475: $failed=1;
476: die("failed lock");
477: };
478: alarm(13);
479: flock($file,$lock_type);
480: alarm(0);
481: };
482: if ($failed) {
483: return undef;
484: } else {
485: return 1;
486: }
487: }
488:
1.5 www 489: # ---------------------------------------------------------- Append Environment
490:
491: sub appenv {
1.949 raeburn 492: my ($newenv,$roles) = @_;
493: if (ref($newenv) eq 'HASH') {
494: foreach my $key (keys(%{$newenv})) {
495: my $refused = 0;
496: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
497: $refused = 1;
498: if (ref($roles) eq 'ARRAY') {
499: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
500: if (grep(/^\Q$role\E$/,@{$roles})) {
501: $refused = 0;
502: }
503: }
504: }
505: if ($refused) {
506: &logthis("<font color=\"blue\">WARNING: ".
507: "Attempt to modify environment ".$key." to ".$newenv->{$key}
508: .'</font>');
509: delete($newenv->{$key});
510: } else {
511: $env{$key}=$newenv->{$key};
512: }
513: }
514: my $opened = open(my $env_file,'+<',$env{'user.environment'});
515: if ($opened
516: && &timed_flock($env_file,LOCK_EX)
517: &&
518: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
519: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
520: while (my ($key,$value) = each(%{$newenv})) {
521: $disk_env{$key} = $value;
522: }
523: untie(%disk_env);
1.35 www 524: }
1.191 harris41 525: }
1.56 www 526: return 'ok';
527: }
528: # ----------------------------------------------------- Delete from Environment
529:
530: sub delenv {
1.987 raeburn 531: my ($delthis,$regexp) = @_;
1.56 www 532: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 533: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 534: "Attempt to delete from environment ".$delthis);
535: return 'error';
536: }
1.917 albertel 537: my $opened = open(my $env_file,'+<',$env{'user.environment'});
538: if ($opened
1.915 albertel 539: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 540: &&
541: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
542: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 543: foreach my $key (keys(%disk_env)) {
1.987 raeburn 544: if ($regexp) {
545: if ($key=~/^$delthis/) {
546: delete($env{$key});
547: delete($disk_env{$key});
548: }
549: } else {
550: if ($key=~/^\Q$delthis\E/) {
551: delete($env{$key});
552: delete($disk_env{$key});
553: }
554: }
1.448 albertel 555: }
1.783 albertel 556: untie(%disk_env);
1.5 www 557: }
558: return 'ok';
1.369 albertel 559: }
560:
1.790 albertel 561: sub get_env_multiple {
562: my ($name) = @_;
563: my @values;
564: if (defined($env{$name})) {
565: # exists is it an array
566: if (ref($env{$name})) {
567: @values=@{ $env{$name} };
568: } else {
569: $values[0]=$env{$name};
570: }
571: }
572: return(@values);
573: }
574:
1.958 www 575: # ------------------------------------------------------------------- Locking
576:
577: sub set_lock {
578: my ($text)=@_;
579: $locknum++;
580: my $id=$$.'-'.$locknum;
581: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
582: 'session.lock.'.$id => $text});
583: return $id;
584: }
585:
586: sub get_locks {
587: my $num=0;
588: my %texts=();
589: foreach my $lock (split(/\,/,$env{'session.locks'})) {
590: if ($lock=~/\w/) {
591: $num++;
592: $texts{$lock}=$env{'session.lock.'.$lock};
593: }
594: }
595: return ($num,%texts);
596: }
597:
598: sub remove_lock {
599: my ($id)=@_;
600: my $newlocks='';
601: foreach my $lock (split(/\,/,$env{'session.locks'})) {
602: if (($lock=~/\w/) && ($lock ne $id)) {
603: $newlocks.=','.$lock;
604: }
605: }
606: &appenv({'session.locks' => $newlocks});
607: &delenv('session.lock.'.$id);
608: }
609:
610: sub remove_all_locks {
611: my $activelocks=$env{'session.locks'};
612: foreach my $lock (split(/\,/,$env{'session.locks'})) {
613: if ($lock=~/\w/) {
614: &remove_lock($lock);
615: }
616: }
617: }
618:
619:
1.369 albertel 620: # ------------------------------------------ Find out current server userload
621: sub userload {
622: my $numusers=0;
623: {
624: opendir(LONIDS,$perlvar{'lonIDsDir'});
625: my $filename;
626: my $curtime=time;
627: while ($filename=readdir(LONIDS)) {
1.925 albertel 628: next if ($filename eq '.' || $filename eq '..');
629: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 630: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 631: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 632: }
633: closedir(LONIDS);
634: }
635: my $userloadpercent=0;
636: my $maxuserload=$perlvar{'lonUserLoadLim'};
637: if ($maxuserload) {
1.371 albertel 638: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 639: }
1.372 albertel 640: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 641: return $userloadpercent;
1.283 www 642: }
643:
644: # ------------------------------------------ Fight off request when overloaded
645:
646: sub overloaderror {
647: my ($r,$checkserver)=@_;
648: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
649: my $loadavg;
650: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 651: open(my $loadfile,'/proc/loadavg');
1.283 www 652: $loadavg=<$loadfile>;
653: $loadavg =~ s/\s.*//g;
1.285 matthew 654: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 655: close($loadfile);
1.283 www 656: } else {
657: $loadavg=&reply('load',$checkserver);
658: }
1.285 matthew 659: my $overload=$loadavg-100;
1.283 www 660: if ($overload>0) {
1.285 matthew 661: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 662: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 663: return 413;
1.283 www 664: }
665: return '';
1.5 www 666: }
1.1 albertel 667:
668: # ------------------------------ Find server with least workload from spare.tab
1.11 www 669:
1.1 albertel 670: sub spareserver {
1.670 albertel 671: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 672: my $spare_server;
1.370 albertel 673: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 674: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
675: : $userloadpercent;
676:
677: foreach my $try_server (@{ $spareid{'primary'} }) {
678: ($spare_server, $lowest_load) =
679: &compare_server_load($try_server, $spare_server, $lowest_load);
680: }
681:
682: my $found_server = ($spare_server ne '' && $lowest_load < 100);
683:
684: if (!$found_server) {
685: foreach my $try_server (@{ $spareid{'default'} }) {
686: ($spare_server, $lowest_load) =
687: &compare_server_load($try_server, $spare_server, $lowest_load);
688: }
689: }
690:
691: if (!$want_server_name) {
1.968 raeburn 692: my $protocol = 'http';
693: if ($protocol{$spare_server} eq 'https') {
694: $protocol = $protocol{$spare_server};
695: }
696: $spare_server = $protocol.'://'.&hostname($spare_server);
1.784 albertel 697: }
698: return $spare_server;
699: }
700:
701: sub compare_server_load {
702: my ($try_server, $spare_server, $lowest_load) = @_;
703:
704: my $loadans = &reply('load', $try_server);
705: my $userloadans = &reply('userload',$try_server);
706:
707: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
708: next; #didn't get a number from the server
709: }
710:
711: my $load;
712: if ($loadans =~ /\d/) {
713: if ($userloadans =~ /\d/) {
714: #both are numbers, pick the bigger one
715: $load = ($loadans > $userloadans) ? $loadans
716: : $userloadans;
1.411 albertel 717: } else {
1.784 albertel 718: $load = $loadans;
1.411 albertel 719: }
1.784 albertel 720: } else {
721: $load = $userloadans;
722: }
723:
724: if (($load =~ /\d/) && ($load < $lowest_load)) {
725: $spare_server = $try_server;
726: $lowest_load = $load;
1.370 albertel 727: }
1.784 albertel 728: return ($spare_server,$lowest_load);
1.202 matthew 729: }
1.914 albertel 730:
731: # --------------------------- ask offload servers if user already has a session
732: sub find_existing_session {
733: my ($udom,$uname) = @_;
734: foreach my $try_server (@{ $spareid{'primary'} },
735: @{ $spareid{'default'} }) {
736: return $try_server if (&has_user_session($try_server, $udom, $uname));
737: }
738: return;
739: }
740:
741: # -------------------------------- ask if server already has a session for user
742: sub has_user_session {
743: my ($lonid,$udom,$uname) = @_;
744: my $result = &reply(join(':','userhassession',
745: map {&escape($_)} ($udom,$uname)),$lonid);
746: return 1 if ($result eq 'ok');
747:
748: return 0;
749: }
750:
1.202 matthew 751: # --------------------------------------------- Try to change a user's password
752:
753: sub changepass {
1.799 raeburn 754: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 755: $currentpass = &escape($currentpass);
756: $newpass = &escape($newpass);
1.799 raeburn 757: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 758: $server);
759: if (! $answer) {
760: &logthis("No reply on password change request to $server ".
761: "by $uname in domain $udom.");
762: } elsif ($answer =~ "^ok") {
763: &logthis("$uname in $udom successfully changed their password ".
764: "on $server.");
765: } elsif ($answer =~ "^pwchange_failure") {
766: &logthis("$uname in $udom was unable to change their password ".
767: "on $server. The action was blocked by either lcpasswd ".
768: "or pwchange");
769: } elsif ($answer =~ "^non_authorized") {
770: &logthis("$uname in $udom did not get their password correct when ".
771: "attempting to change it on $server.");
772: } elsif ($answer =~ "^auth_mode_error") {
773: &logthis("$uname in $udom attempted to change their password despite ".
774: "not being locally or internally authenticated on $server.");
775: } elsif ($answer =~ "^unknown_user") {
776: &logthis("$uname in $udom attempted to change their password ".
777: "on $server but were unable to because $server is not ".
778: "their home server.");
779: } elsif ($answer =~ "^refused") {
780: &logthis("$server refused to change $uname in $udom password because ".
781: "it was sent an unencrypted request to change the password.");
782: }
783: return $answer;
1.1 albertel 784: }
785:
1.169 harris41 786: # ----------------------- Try to determine user's current authentication scheme
787:
788: sub queryauthenticate {
789: my ($uname,$udom)=@_;
1.456 albertel 790: my $uhome=&homeserver($uname,$udom);
791: if (!$uhome) {
792: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
793: return 'no_host';
794: }
795: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
796: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
797: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 798: }
1.456 albertel 799: return $answer;
1.169 harris41 800: }
801:
1.1 albertel 802: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 803:
1.1 albertel 804: sub authenticate {
1.952 raeburn 805: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 806: $upass=&escape($upass);
807: $uname= &LONCAPA::clean_username($uname);
1.836 www 808: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 809: my $newhome;
1.836 www 810: if ((!$uhome) || ($uhome eq 'no_host')) {
811: # Maybe the machine was offline and only re-appeared again recently?
812: &reconlonc();
813: # One more
1.952 raeburn 814: $uhome=&homeserver($uname,$udom,1);
815: if (($uhome eq 'no_host') && $checkdefauth) {
816: if (defined(&domain($udom,'primary'))) {
817: $newhome=&domain($udom,'primary');
818: }
819: if ($newhome ne '') {
820: $uhome = $newhome;
821: }
822: }
1.836 www 823: if ((!$uhome) || ($uhome eq 'no_host')) {
824: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 825: return 'no_host';
826: }
1.1 albertel 827: }
1.952 raeburn 828: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 829: if ($answer eq 'authorized') {
1.952 raeburn 830: if ($newhome) {
831: &logthis("User $uname at $udom authorized by $uhome, but needs account");
832: return 'no_account_on_host';
833: } else {
834: &logthis("User $uname at $udom authorized by $uhome");
835: return $uhome;
836: }
1.471 albertel 837: }
838: if ($answer eq 'non_authorized') {
839: &logthis("User $uname at $udom rejected by $uhome");
840: return 'no_host';
1.9 www 841: }
1.471 albertel 842: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 843: return 'no_host';
844: }
845:
846: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 847:
1.599 albertel 848: my %homecache;
1.1 albertel 849: sub homeserver {
1.230 stredwic 850: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 851: my $index="$uname:$udom";
1.426 albertel 852:
1.599 albertel 853: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 854:
855: my %servers = &get_servers($udom,'library');
856: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 857: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 858: exists($badServerCache{$tryserver}));
1.841 albertel 859:
860: my $answer=reply("home:$udom:$uname",$tryserver);
861: if ($answer eq 'found') {
862: delete($badServerCache{$tryserver});
863: return $homecache{$index}=$tryserver;
864: } elsif ($answer eq 'no_host') {
865: $badServerCache{$tryserver}=1;
866: }
1.1 albertel 867: }
868: return 'no_host';
1.70 www 869: }
870:
871: # ------------------------------------- Find the usernames behind a list of IDs
872:
873: sub idget {
874: my ($udom,@ids)=@_;
875: my %returnhash=();
876:
1.841 albertel 877: my %servers = &get_servers($udom,'library');
878: foreach my $tryserver (keys(%servers)) {
879: my $idlist=join('&',@ids);
880: $idlist=~tr/A-Z/a-z/;
881: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
882: my @answer=();
883: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
884: @answer=split(/\&/,$reply);
885: } ;
886: my $i;
887: for ($i=0;$i<=$#ids;$i++) {
888: if ($answer[$i]) {
889: $returnhash{$ids[$i]}=$answer[$i];
890: }
891: }
892: }
1.70 www 893: return %returnhash;
894: }
895:
896: # ------------------------------------- Find the IDs behind a list of usernames
897:
898: sub idrget {
899: my ($udom,@unames)=@_;
900: my %returnhash=();
1.800 albertel 901: foreach my $uname (@unames) {
902: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 903: }
1.70 www 904: return %returnhash;
905: }
906:
907: # ------------------------------- Store away a list of names and associated IDs
908:
909: sub idput {
910: my ($udom,%ids)=@_;
911: my %servers=();
1.800 albertel 912: foreach my $uname (keys(%ids)) {
913: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
914: my $uhom=&homeserver($uname,$udom);
1.70 www 915: if ($uhom ne 'no_host') {
1.800 albertel 916: my $id=&escape($ids{$uname});
1.70 www 917: $id=~tr/A-Z/a-z/;
1.800 albertel 918: my $esc_unam=&escape($uname);
1.70 www 919: if ($servers{$uhom}) {
1.800 albertel 920: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 921: } else {
1.800 albertel 922: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 923: }
924: }
1.191 harris41 925: }
1.800 albertel 926: foreach my $server (keys(%servers)) {
927: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 928: }
1.344 www 929: }
930:
1.806 raeburn 931: # ------------------------------------------- get items from domain db files
932:
933: sub get_dom {
1.860 raeburn 934: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 935: my $items='';
936: foreach my $item (@$storearr) {
937: $items.=&escape($item).'&';
938: }
939: $items=~s/\&$//;
1.860 raeburn 940: if (!$udom) {
941: $udom=$env{'user.domain'};
942: if (defined(&domain($udom,'primary'))) {
943: $uhome=&domain($udom,'primary');
944: } else {
1.874 albertel 945: undef($uhome);
1.860 raeburn 946: }
947: } else {
948: if (!$uhome) {
949: if (defined(&domain($udom,'primary'))) {
950: $uhome=&domain($udom,'primary');
951: }
952: }
953: }
954: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 955: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 956: my %returnhash;
1.875 albertel 957: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 958: return %returnhash;
959: }
1.806 raeburn 960: my @pairs=split(/\&/,$rep);
961: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
962: return @pairs;
963: }
964: my $i=0;
965: foreach my $item (@$storearr) {
966: $returnhash{$item}=&thaw_unescape($pairs[$i]);
967: $i++;
968: }
969: return %returnhash;
970: } else {
1.880 banghart 971: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 972: }
973: }
974:
975: # -------------------------------------------- put items in domain db files
976:
977: sub put_dom {
1.860 raeburn 978: my ($namespace,$storehash,$udom,$uhome)=@_;
979: if (!$udom) {
980: $udom=$env{'user.domain'};
981: if (defined(&domain($udom,'primary'))) {
982: $uhome=&domain($udom,'primary');
983: } else {
1.874 albertel 984: undef($uhome);
1.860 raeburn 985: }
986: } else {
987: if (!$uhome) {
988: if (defined(&domain($udom,'primary'))) {
989: $uhome=&domain($udom,'primary');
990: }
991: }
992: }
993: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 994: my $items='';
995: foreach my $item (keys(%$storehash)) {
996: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
997: }
998: $items=~s/\&$//;
999: return &reply("putdom:$udom:$namespace:$items",$uhome);
1000: } else {
1.860 raeburn 1001: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1002: }
1003: }
1004:
1.837 raeburn 1005: sub retrieve_inst_usertypes {
1006: my ($udom) = @_;
1007: my (%returnhash,@order);
1.846 albertel 1008: if (defined(&domain($udom,'primary'))) {
1009: my $uhome=&domain($udom,'primary');
1.837 raeburn 1010: my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960 raeburn 1011: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1012: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1013: return (\%returnhash,\@order);
1014: }
1.837 raeburn 1015: my ($hashitems,$orderitems) = split(/:/,$rep);
1016: my @pairs=split(/\&/,$hashitems);
1017: foreach my $item (@pairs) {
1018: my ($key,$value)=split(/=/,$item,2);
1019: $key = &unescape($key);
1020: next if ($key =~ /^error: 2 /);
1021: $returnhash{$key}=&thaw_unescape($value);
1022: }
1023: my @esc_order = split(/\&/,$orderitems);
1024: foreach my $item (@esc_order) {
1025: push(@order,&unescape($item));
1026: }
1027: } else {
1028: &logthis("get_dom failed - no primary domain server for $udom");
1029: }
1030: return (\%returnhash,\@order);
1031: }
1032:
1.868 raeburn 1033: sub is_domainimage {
1034: my ($url) = @_;
1035: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1036: if (&domain($1) ne '') {
1037: return '1';
1038: }
1039: }
1040: return;
1041: }
1042:
1.899 raeburn 1043: sub inst_directory_query {
1044: my ($srch) = @_;
1045: my $udom = $srch->{'srchdomain'};
1046: my %results;
1047: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1048: my $outcome;
1.899 raeburn 1049: if ($homeserver ne '') {
1.904 albertel 1050: my $queryid=&reply("querysend:instdirsearch:".
1051: &escape($srch->{'srchby'}).':'.
1052: &escape($srch->{'srchterm'}).':'.
1053: &escape($srch->{'srchtype'}),$homeserver);
1054: my $host=&hostname($homeserver);
1055: if ($queryid !~/^\Q$host\E\_/) {
1056: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1057: return;
1058: }
1059: my $response = &get_query_reply($queryid);
1060: my $maxtries = 5;
1061: my $tries = 1;
1062: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1063: $response = &get_query_reply($queryid);
1064: $tries ++;
1065: }
1066:
1067: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1068: if ($response eq 'unavailable') {
1069: $outcome = $response;
1070: } else {
1071: $outcome = 'ok';
1072: my @matches = split(/\n/,$response);
1073: foreach my $match (@matches) {
1074: my ($key,$value) = split(/=/,$match);
1075: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1076: }
1.899 raeburn 1077: }
1078: }
1079: }
1.909 raeburn 1080: return ($outcome,%results);
1.899 raeburn 1081: }
1082:
1083: sub usersearch {
1084: my ($srch) = @_;
1085: my $dom = $srch->{'srchdomain'};
1086: my %results;
1087: my %libserv = &all_library();
1088: my $query = 'usersearch';
1089: foreach my $tryserver (keys(%libserv)) {
1090: if (&host_domain($tryserver) eq $dom) {
1091: my $host=&hostname($tryserver);
1092: my $queryid=
1.911 raeburn 1093: &reply("querysend:".&escape($query).':'.
1094: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1095: &escape($srch->{'srchtype'}).':'.
1096: &escape($srch->{'srchterm'}),$tryserver);
1097: if ($queryid !~/^\Q$host\E\_/) {
1098: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1099: next;
1.899 raeburn 1100: }
1101: my $reply = &get_query_reply($queryid);
1102: my $maxtries = 1;
1103: my $tries = 1;
1104: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1105: $reply = &get_query_reply($queryid);
1106: $tries ++;
1107: }
1108: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1109: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1110: } else {
1.911 raeburn 1111: my @matches;
1112: if ($reply =~ /\n/) {
1113: @matches = split(/\n/,$reply);
1114: } else {
1115: @matches = split(/\&/,$reply);
1116: }
1.899 raeburn 1117: foreach my $match (@matches) {
1118: my ($uname,$udom,%userhash);
1.911 raeburn 1119: foreach my $entry (split(/:/,$match)) {
1120: my ($key,$value) =
1121: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1122: $userhash{$key} = $value;
1123: if ($key eq 'username') {
1124: $uname = $value;
1125: } elsif ($key eq 'domain') {
1126: $udom = $value;
1.911 raeburn 1127: }
1.899 raeburn 1128: }
1129: $results{$uname.':'.$udom} = \%userhash;
1130: }
1131: }
1132: }
1133: }
1134: return %results;
1135: }
1136:
1.912 raeburn 1137: sub get_instuser {
1138: my ($udom,$uname,$id) = @_;
1139: my $homeserver = &domain($udom,'primary');
1140: my ($outcome,%results);
1141: if ($homeserver ne '') {
1142: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1143: &escape($id).':'.&escape($udom),$homeserver);
1144: my $host=&hostname($homeserver);
1145: if ($queryid !~/^\Q$host\E\_/) {
1146: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1147: return;
1148: }
1149: my $response = &get_query_reply($queryid);
1150: my $maxtries = 5;
1151: my $tries = 1;
1152: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1153: $response = &get_query_reply($queryid);
1154: $tries ++;
1155: }
1156: if (!&error($response) && $response ne 'refused') {
1157: if ($response eq 'unavailable') {
1158: $outcome = $response;
1159: } else {
1160: $outcome = 'ok';
1161: my @matches = split(/\n/,$response);
1162: foreach my $match (@matches) {
1163: my ($key,$value) = split(/=/,$match);
1164: $results{&unescape($key)} = &thaw_unescape($value);
1165: }
1166: }
1167: }
1168: }
1169: my %userinfo;
1170: if (ref($results{$uname}) eq 'HASH') {
1171: %userinfo = %{$results{$uname}};
1172: }
1173: return ($outcome,%userinfo);
1174: }
1175:
1176: sub inst_rulecheck {
1.923 raeburn 1177: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1178: my %returnhash;
1179: if ($udom ne '') {
1180: if (ref($rules) eq 'ARRAY') {
1181: @{$rules} = map {&escape($_);} (@{$rules});
1182: my $rulestr = join(':',@{$rules});
1183: my $homeserver=&domain($udom,'primary');
1184: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1185: my $response;
1186: if ($item eq 'username') {
1187: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1188: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1189: $homeserver));
1.923 raeburn 1190: } elsif ($item eq 'id') {
1191: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1192: ':'.&escape($id).':'.$rulestr,
1193: $homeserver));
1.945 raeburn 1194: } elsif ($item eq 'selfcreate') {
1195: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1196: &escape($udom).':'.&escape($uname).
1197: ':'.$rulestr,$homeserver));
1.923 raeburn 1198: }
1.912 raeburn 1199: if ($response ne 'refused') {
1200: my @pairs=split(/\&/,$response);
1201: foreach my $item (@pairs) {
1202: my ($key,$value)=split(/=/,$item,2);
1203: $key = &unescape($key);
1204: next if ($key =~ /^error: 2 /);
1205: $returnhash{$key}=&thaw_unescape($value);
1206: }
1207: }
1208: }
1209: }
1210: }
1211: return %returnhash;
1212: }
1213:
1214: sub inst_userrules {
1.923 raeburn 1215: my ($udom,$check) = @_;
1.912 raeburn 1216: my (%ruleshash,@ruleorder);
1217: if ($udom ne '') {
1218: my $homeserver=&domain($udom,'primary');
1219: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1220: my $response;
1221: if ($check eq 'id') {
1222: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1223: $homeserver);
1.943 raeburn 1224: } elsif ($check eq 'email') {
1225: $response=&reply('instemailrules:'.&escape($udom),
1226: $homeserver);
1.923 raeburn 1227: } else {
1228: $response=&reply('instuserrules:'.&escape($udom),
1229: $homeserver);
1230: }
1.912 raeburn 1231: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1232: ($response ne 'unknown_cmd') &&
1.912 raeburn 1233: ($response ne 'no_such_host')) {
1234: my ($hashitems,$orderitems) = split(/:/,$response);
1235: my @pairs=split(/\&/,$hashitems);
1236: foreach my $item (@pairs) {
1237: my ($key,$value)=split(/=/,$item,2);
1238: $key = &unescape($key);
1239: next if ($key =~ /^error: 2 /);
1240: $ruleshash{$key}=&thaw_unescape($value);
1241: }
1242: my @esc_order = split(/\&/,$orderitems);
1243: foreach my $item (@esc_order) {
1244: push(@ruleorder,&unescape($item));
1245: }
1246: }
1247: }
1248: }
1249: return (\%ruleshash,\@ruleorder);
1250: }
1251:
1.976 raeburn 1252: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1253:
1254: sub get_domain_defaults {
1255: my ($domain) = @_;
1256: my $cachetime = 60*60*24;
1257: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1258: if (defined($cached)) {
1259: if (ref($result) eq 'HASH') {
1260: return %{$result};
1261: }
1262: }
1263: my %domdefaults;
1264: my %domconfig =
1.976 raeburn 1265: &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943 raeburn 1266: if (ref($domconfig{'defaults'}) eq 'HASH') {
1267: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1268: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1269: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1270: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1271: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1272: } else {
1273: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1274: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1275: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1276: }
1.976 raeburn 1277: if (ref($domconfig{'quotas'}) eq 'HASH') {
1278: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1279: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1280: } else {
1281: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1282: }
1283: my @usertools = ('aboutme','blog','portfolio');
1284: foreach my $item (@usertools) {
1285: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1286: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1287: }
1288: }
1289: }
1.985 raeburn 1290: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1291: foreach my $item ('official','unofficial') {
1292: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1293: }
1294: }
1.943 raeburn 1295: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1296: $cachetime);
1297: return %domdefaults;
1298: }
1299:
1.344 www 1300: # --------------------------------------------------- Assign a key to a student
1301:
1302: sub assign_access_key {
1.364 www 1303: #
1304: # a valid key looks like uname:udom#comments
1305: # comments are being appended
1306: #
1.498 www 1307: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1308: $kdom=
1.620 albertel 1309: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1310: $knum=
1.620 albertel 1311: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1312: $cdom=
1.620 albertel 1313: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1314: $cnum=
1.620 albertel 1315: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1316: $udom=$env{'user.name'} unless (defined($udom));
1317: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1318: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1319: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1320: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1321: # assigned to this person
1322: # - this should not happen,
1.345 www 1323: # unless something went wrong
1324: # the first time around
1325: # ready to assign
1.364 www 1326: $logentry=$1.'; '.$logentry;
1.496 www 1327: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1328: $kdom,$knum) eq 'ok') {
1.345 www 1329: # key now belongs to user
1.346 www 1330: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1331: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1332: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1333: return 'ok';
1334: } else {
1335: return
1336: 'error: Count not permanently assign key, will need to be re-entered later.';
1337: }
1338: } else {
1339: return 'error: Could not assign key, try again later.';
1340: }
1.364 www 1341: } elsif (!$existing{$ckey}) {
1.345 www 1342: # the key does not exist
1343: return 'error: The key does not exist';
1344: } else {
1345: # the key is somebody else's
1346: return 'error: The key is already in use';
1347: }
1.344 www 1348: }
1349:
1.364 www 1350: # ------------------------------------------ put an additional comment on a key
1351:
1352: sub comment_access_key {
1353: #
1354: # a valid key looks like uname:udom#comments
1355: # comments are being appended
1356: #
1357: my ($ckey,$cdom,$cnum,$logentry)=@_;
1358: $cdom=
1.620 albertel 1359: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1360: $cnum=
1.620 albertel 1361: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1362: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1363: if ($existing{$ckey}) {
1364: $existing{$ckey}.='; '.$logentry;
1365: # ready to assign
1.367 www 1366: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1367: $cdom,$cnum) eq 'ok') {
1368: return 'ok';
1369: } else {
1370: return 'error: Count not store comment.';
1371: }
1372: } else {
1373: # the key does not exist
1374: return 'error: The key does not exist';
1375: }
1376: }
1377:
1.344 www 1378: # ------------------------------------------------------ Generate a set of keys
1379:
1380: sub generate_access_keys {
1.364 www 1381: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1382: $cdom=
1.620 albertel 1383: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1384: $cnum=
1.620 albertel 1385: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1386: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1387: unless (($cdom) && ($cnum)) { return 0; }
1388: if ($number>10000) { return 0; }
1389: sleep(2); # make sure don't get same seed twice
1390: srand(time()^($$+($$<<15))); # from "Programming Perl"
1391: my $total=0;
1392: for (my $i=1;$i<=$number;$i++) {
1393: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1394: sprintf("%lx",int(100000*rand)).'-'.
1395: sprintf("%lx",int(100000*rand));
1396: $newkey=~s/1/g/g; # folks mix up 1 and l
1397: $newkey=~s/0/h/g; # and also 0 and O
1398: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1399: if ($existing{$newkey}) {
1400: $i--;
1401: } else {
1.364 www 1402: if (&put('accesskeys',
1403: { $newkey => '# generated '.localtime().
1.620 albertel 1404: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1405: '; '.$logentry },
1406: $cdom,$cnum) eq 'ok') {
1.344 www 1407: $total++;
1408: }
1409: }
1410: }
1.620 albertel 1411: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1412: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1413: return $total;
1414: }
1415:
1416: # ------------------------------------------------------- Validate an accesskey
1417:
1418: sub validate_access_key {
1419: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1420: $cdom=
1.620 albertel 1421: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1422: $cnum=
1.620 albertel 1423: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1424: $udom=$env{'user.domain'} unless (defined($udom));
1425: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1426: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1427: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1428: }
1429:
1430: # ------------------------------------- Find the section of student in a course
1.652 albertel 1431: sub devalidate_getsection_cache {
1432: my ($udom,$unam,$courseid)=@_;
1433: my $hashid="$udom:$unam:$courseid";
1434: &devalidate_cache_new('getsection',$hashid);
1435: }
1.298 matthew 1436:
1.815 albertel 1437: sub courseid_to_courseurl {
1438: my ($courseid) = @_;
1439: #already url style courseid
1440: return $courseid if ($courseid =~ m{^/});
1441:
1442: if (exists($env{'course.'.$courseid.'.num'})) {
1443: my $cnum = $env{'course.'.$courseid.'.num'};
1444: my $cdom = $env{'course.'.$courseid.'.domain'};
1445: return "/$cdom/$cnum";
1446: }
1447:
1448: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1449: if (exists($courseinfo{'num'})) {
1450: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1451: }
1452:
1453: return undef;
1454: }
1455:
1.298 matthew 1456: sub getsection {
1457: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1458: my $cachetime=1800;
1.551 albertel 1459:
1460: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1461: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1462: if (defined($cached)) { return $result; }
1463:
1.298 matthew 1464: my %Pending;
1465: my %Expired;
1466: #
1467: # Each role can either have not started yet (pending), be active,
1468: # or have expired.
1469: #
1470: # If there is an active role, we are done.
1471: #
1472: # If there is more than one role which has not started yet,
1473: # choose the one which will start sooner
1474: # If there is one role which has not started yet, return it.
1475: #
1476: # If there is more than one expired role, choose the one which ended last.
1477: # If there is a role which has expired, return it.
1478: #
1.815 albertel 1479: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1480: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1481: foreach my $key (keys(%roleshash)) {
1.479 albertel 1482: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1483: my $section=$1;
1484: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1485: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1486: my $now=time;
1.548 albertel 1487: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1488: $Expired{$end}=$section;
1489: next;
1490: }
1.548 albertel 1491: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1492: $Pending{$start}=$section;
1493: next;
1494: }
1.599 albertel 1495: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1496: }
1497: #
1498: # Presumedly there will be few matching roles from the above
1499: # loop and the sorting time will be negligible.
1500: if (scalar(keys(%Pending))) {
1501: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1502: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1503: }
1504: if (scalar(keys(%Expired))) {
1505: my @sorted = sort {$a <=> $b} keys(%Expired);
1506: my $time = pop(@sorted);
1.599 albertel 1507: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1508: }
1.599 albertel 1509: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1510: }
1.70 www 1511:
1.599 albertel 1512: sub save_cache {
1513: &purge_remembered();
1.722 albertel 1514: #&Apache::loncommon::validate_page();
1.620 albertel 1515: undef(%env);
1.780 albertel 1516: undef($env_loaded);
1.599 albertel 1517: }
1.452 albertel 1518:
1.599 albertel 1519: my $to_remember=-1;
1520: my %remembered;
1521: my %accessed;
1522: my $kicks=0;
1523: my $hits=0;
1.849 albertel 1524: sub make_key {
1525: my ($name,$id) = @_;
1.872 albertel 1526: if (length($id) > 65
1527: && length(&escape($id)) > 200) {
1528: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1529: }
1.849 albertel 1530: return &escape($name.':'.$id);
1531: }
1532:
1.599 albertel 1533: sub devalidate_cache_new {
1534: my ($name,$id,$debug) = @_;
1535: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1536: $id=&make_key($name,$id);
1.599 albertel 1537: $memcache->delete($id);
1538: delete($remembered{$id});
1539: delete($accessed{$id});
1540: }
1541:
1542: sub is_cached_new {
1543: my ($name,$id,$debug) = @_;
1.849 albertel 1544: $id=&make_key($name,$id);
1.599 albertel 1545: if (exists($remembered{$id})) {
1546: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1547: $accessed{$id}=[&gettimeofday()];
1548: $hits++;
1549: return ($remembered{$id},1);
1550: }
1551: my $value = $memcache->get($id);
1552: if (!(defined($value))) {
1553: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1554: return (undef,undef);
1.416 albertel 1555: }
1.599 albertel 1556: if ($value eq '__undef__') {
1557: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1558: $value=undef;
1559: }
1560: &make_room($id,$value,$debug);
1561: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1562: return ($value,1);
1563: }
1564:
1565: sub do_cache_new {
1566: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1567: $id=&make_key($name,$id);
1.599 albertel 1568: my $setvalue=$value;
1569: if (!defined($setvalue)) {
1570: $setvalue='__undef__';
1571: }
1.623 albertel 1572: if (!defined($time) ) {
1573: $time=600;
1574: }
1.599 albertel 1575: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1576: my $result = $memcache->set($id,$setvalue,$time);
1577: if (! $result) {
1.872 albertel 1578: &logthis("caching of id -> $id failed");
1.910 albertel 1579: $memcache->disconnect_all();
1.872 albertel 1580: }
1.600 albertel 1581: # need to make a copy of $value
1.919 albertel 1582: &make_room($id,$value,$debug);
1.599 albertel 1583: return $value;
1584: }
1585:
1586: sub make_room {
1587: my ($id,$value,$debug)=@_;
1.919 albertel 1588:
1589: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1590: : $value;
1.599 albertel 1591: if ($to_remember<0) { return; }
1592: $accessed{$id}=[&gettimeofday()];
1593: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1594: my $to_kick;
1595: my $max_time=0;
1596: foreach my $other (keys(%accessed)) {
1597: if (&tv_interval($accessed{$other}) > $max_time) {
1598: $to_kick=$other;
1599: $max_time=&tv_interval($accessed{$other});
1600: }
1601: }
1602: delete($remembered{$to_kick});
1603: delete($accessed{$to_kick});
1604: $kicks++;
1605: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1606: return;
1607: }
1608:
1.599 albertel 1609: sub purge_remembered {
1.604 albertel 1610: #&logthis("Tossing ".scalar(keys(%remembered)));
1611: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1612: undef(%remembered);
1613: undef(%accessed);
1.428 albertel 1614: }
1.70 www 1615: # ------------------------------------- Read an entry from a user's environment
1616:
1617: sub userenvironment {
1618: my ($udom,$unam,@what)=@_;
1.976 raeburn 1619: my $items;
1620: foreach my $item (@what) {
1621: $items.=&escape($item).'&';
1622: }
1623: $items=~s/\&$//;
1.70 www 1624: my %returnhash=();
1625: my @answer=split(/\&/,
1.976 raeburn 1626: &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70 www 1627: &homeserver($unam,$udom)));
1628: my $i;
1629: for ($i=0;$i<=$#what;$i++) {
1630: $returnhash{$what[$i]}=&unescape($answer[$i]);
1631: }
1632: return %returnhash;
1.1 albertel 1633: }
1634:
1.617 albertel 1635: # ---------------------------------------------------------- Get a studentphoto
1636: sub studentphoto {
1637: my ($udom,$unam,$ext) = @_;
1638: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1639: if (defined($env{'request.course.id'})) {
1.708 raeburn 1640: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1641: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1642: return(&retrievestudentphoto($udom,$unam,$ext));
1643: } else {
1644: my ($result,$perm_reqd)=
1.707 albertel 1645: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1646: if ($result eq 'ok') {
1647: if (!($perm_reqd eq 'yes')) {
1648: return(&retrievestudentphoto($udom,$unam,$ext));
1649: }
1650: }
1651: }
1652: }
1653: } else {
1654: my ($result,$perm_reqd) =
1.707 albertel 1655: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1656: if ($result eq 'ok') {
1657: if (!($perm_reqd eq 'yes')) {
1658: return(&retrievestudentphoto($udom,$unam,$ext));
1659: }
1660: }
1661: }
1662: return '/adm/lonKaputt/lonlogo_broken.gif';
1663: }
1664:
1665: sub retrievestudentphoto {
1666: my ($udom,$unam,$ext,$type) = @_;
1667: my $home=&Apache::lonnet::homeserver($unam,$udom);
1668: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1669: if ($ret eq 'ok') {
1670: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1671: if ($type eq 'thumbnail') {
1672: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1673: }
1674: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1675: return $tokenurl;
1676: } else {
1677: if ($type eq 'thumbnail') {
1678: return '/adm/lonKaputt/genericstudent_tn.gif';
1679: } else {
1680: return '/adm/lonKaputt/lonlogo_broken.gif';
1681: }
1.617 albertel 1682: }
1683: }
1684:
1.263 www 1685: # -------------------------------------------------------------------- New chat
1686:
1687: sub chatsend {
1.724 raeburn 1688: my ($newentry,$anon,$group)=@_;
1.620 albertel 1689: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1690: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1691: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1692: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1693: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1694: &escape($newentry)).':'.$group,$chome);
1.292 www 1695: }
1696:
1697: # ------------------------------------------ Find current version of a resource
1698:
1699: sub getversion {
1700: my $fname=&clutter(shift);
1701: unless ($fname=~/^\/res\//) { return -1; }
1702: return ¤tversion(&filelocation('',$fname));
1703: }
1704:
1705: sub currentversion {
1706: my $fname=shift;
1.599 albertel 1707: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1708: if (defined($cached)) { return $result; }
1.292 www 1709: my $author=$fname;
1710: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1711: my ($udom,$uname)=split(/\//,$author);
1712: my $home=homeserver($uname,$udom);
1713: if ($home eq 'no_host') {
1714: return -1;
1715: }
1716: my $answer=reply("currentversion:$fname",$home);
1717: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1718: return -1;
1719: }
1.599 albertel 1720: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1721: }
1722:
1.1 albertel 1723: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1724:
1.1 albertel 1725: sub subscribe {
1726: my $fname=shift;
1.761 raeburn 1727: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1728: $fname=~s/[\n\r]//g;
1.1 albertel 1729: my $author=$fname;
1730: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1731: my ($udom,$uname)=split(/\//,$author);
1732: my $home=homeserver($uname,$udom);
1.335 albertel 1733: if ($home eq 'no_host') {
1734: return 'not_found';
1.1 albertel 1735: }
1736: my $answer=reply("sub:$fname",$home);
1.64 www 1737: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1738: $answer.=' by '.$home;
1739: }
1.1 albertel 1740: return $answer;
1741: }
1742:
1.8 www 1743: # -------------------------------------------------------------- Replicate file
1744:
1745: sub repcopy {
1746: my $filename=shift;
1.23 www 1747: $filename=~s/\/+/\//g;
1.607 raeburn 1748: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1749: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1750: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1751: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1752: return &repcopy_userfile($filename);
1753: }
1.532 albertel 1754: $filename=~s/[\n\r]//g;
1.8 www 1755: my $transname="$filename.in.transfer";
1.828 www 1756: # FIXME: this should flock
1.607 raeburn 1757: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1758: my $remoteurl=subscribe($filename);
1.64 www 1759: if ($remoteurl =~ /^con_lost by/) {
1760: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1761: return 'unavailable';
1.8 www 1762: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1763: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1764: return 'not_found';
1.64 www 1765: } elsif ($remoteurl =~ /^rejected by/) {
1766: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1767: return 'forbidden';
1.20 www 1768: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1769: return 'ok';
1.8 www 1770: } else {
1.290 www 1771: my $author=$filename;
1772: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1773: my ($udom,$uname)=split(/\//,$author);
1774: my $home=homeserver($uname,$udom);
1775: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1776: my @parts=split(/\//,$filename);
1777: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1778: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1779: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1780: return 'bad_request';
1.8 www 1781: }
1782: my $count;
1783: for ($count=5;$count<$#parts;$count++) {
1784: $path.="/$parts[$count]";
1785: if ((-e $path)!=1) {
1786: mkdir($path,0777);
1787: }
1788: }
1789: my $ua=new LWP::UserAgent;
1790: my $request=new HTTP::Request('GET',"$remoteurl");
1791: my $response=$ua->request($request,$transname);
1792: if ($response->is_error()) {
1793: unlink($transname);
1794: my $message=$response->status_line;
1.672 albertel 1795: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1796: ." LWP get: $message: $filename</font>");
1.607 raeburn 1797: return 'unavailable';
1.8 www 1798: } else {
1.16 www 1799: if ($remoteurl!~/\.meta$/) {
1800: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1801: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1802: if ($mresponse->is_error()) {
1803: unlink($filename.'.meta');
1804: &logthis(
1.672 albertel 1805: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1806: }
1807: }
1.8 www 1808: rename($transname,$filename);
1.607 raeburn 1809: return 'ok';
1.8 www 1810: }
1.290 www 1811: }
1.8 www 1812: }
1.330 www 1813: }
1814:
1815: # ------------------------------------------------ Get server side include body
1816: sub ssi_body {
1.381 albertel 1817: my ($filelink,%form)=@_;
1.606 matthew 1818: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1819: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1820: }
1.953 www 1821: my $output='';
1822: my $response;
1.980 raeburn 1823: if ($filelink=~/^https?\:/) {
1.954 raeburn 1824: ($output,$response)=&externalssi($filelink);
1.953 www 1825: } else {
1826: ($output,$response)=&ssi($filelink,%form);
1827: }
1.778 albertel 1828: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1829: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1830: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1831: if (wantarray) {
1832: return ($output, $response);
1833: } else {
1834: return $output;
1835: }
1.8 www 1836: }
1837:
1.15 www 1838: # --------------------------------------------------------- Server Side Include
1839:
1.782 albertel 1840: sub absolute_url {
1841: my ($host_name) = @_;
1842: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1843: if ($host_name eq '') {
1844: $host_name = $ENV{'SERVER_NAME'};
1845: }
1846: return $protocol.$host_name;
1847: }
1848:
1.942 foxr 1849: #
1850: # Server side include.
1851: # Parameters:
1852: # fn Possibly encrypted resource name/id.
1853: # form Hash that describes how the rendering should be done
1854: # and other things.
1.944 foxr 1855: # Returns:
1.950 raeburn 1856: # Scalar context: The content of the response.
1857: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1858: #
1.15 www 1859: sub ssi {
1860:
1.944 foxr 1861: my ($fn,%form)=@_;
1.15 www 1862: my $ua=new LWP::UserAgent;
1.23 www 1863: my $request;
1.711 albertel 1864:
1865: $form{'no_update_last_known'}=1;
1.895 albertel 1866: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1867: if (%form) {
1.782 albertel 1868: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1869: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1870: } else {
1.782 albertel 1871: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1872: }
1873:
1.15 www 1874: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1875: my $response=$ua->request($request);
1876:
1.944 foxr 1877: if (wantarray) {
1878: return ($response->content, $response);
1879: } else {
1880: return $response->content;
1.942 foxr 1881: }
1.324 www 1882: }
1883:
1884: sub externalssi {
1885: my ($url)=@_;
1886: my $ua=new LWP::UserAgent;
1887: my $request=new HTTP::Request('GET',$url);
1888: my $response=$ua->request($request);
1.954 raeburn 1889: if (wantarray) {
1890: return ($response->content, $response);
1891: } else {
1892: return $response->content;
1893: }
1.15 www 1894: }
1.254 www 1895:
1.492 albertel 1896: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1897:
1898: sub allowuploaded {
1899: my ($srcurl,$url)=@_;
1900: $url=&clutter(&declutter($url));
1901: my $dir=$url;
1902: $dir=~s/\/[^\/]+$//;
1903: my %httpref=();
1904: my $httpurl=&hreflocation('',$url);
1905: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 1906: &Apache::lonnet::appenv(\%httpref);
1.254 www 1907: }
1.477 raeburn 1908:
1.478 albertel 1909: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1910: # input: action, courseID, current domain, intended
1.637 raeburn 1911: # path to file, source of file, instruction to parse file for objects,
1912: # ref to hash for embedded objects,
1913: # ref to hash for codebase of java objects.
1914: #
1.485 raeburn 1915: # output: url to file (if action was uploaddoc),
1916: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1917: #
1.478 albertel 1918: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1919: # course.
1.477 raeburn 1920: #
1.478 albertel 1921: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1922: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1923: # course's home server.
1.477 raeburn 1924: #
1.478 albertel 1925: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1926: # be copied from $source (current location) to
1927: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1928: # and will then be copied to
1929: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1930: # course's home server.
1.485 raeburn 1931: #
1.481 raeburn 1932: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1933: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1934: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1935: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1936: # in course's home server.
1.637 raeburn 1937: #
1.477 raeburn 1938:
1939: sub process_coursefile {
1.638 albertel 1940: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1941: my $fetchresult;
1.638 albertel 1942: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1943: if ($action eq 'propagate') {
1.638 albertel 1944: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1945: $home);
1.481 raeburn 1946: } else {
1.477 raeburn 1947: my $fpath = '';
1948: my $fname = $file;
1.478 albertel 1949: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1950: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1951: my $filepath = &build_filepath($fpath);
1.481 raeburn 1952: if ($action eq 'copy') {
1953: if ($source eq '') {
1954: $fetchresult = 'no source file';
1955: return $fetchresult;
1956: } else {
1957: my $destination = $filepath.'/'.$fname;
1958: rename($source,$destination);
1959: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1960: $home);
1.481 raeburn 1961: }
1962: } elsif ($action eq 'uploaddoc') {
1963: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1964: print $fh $env{'form.'.$source};
1.481 raeburn 1965: close($fh);
1.637 raeburn 1966: if ($parser eq 'parse') {
1.961 raeburn 1967: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637 raeburn 1968: unless ($parse_result eq 'ok') {
1969: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1970: }
1971: }
1.477 raeburn 1972: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1973: $home);
1.481 raeburn 1974: if ($fetchresult eq 'ok') {
1975: return '/uploaded/'.$fpath.'/'.$fname;
1976: } else {
1977: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1978: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1979: return '/adm/notfound.html';
1980: }
1.477 raeburn 1981: }
1982: }
1.485 raeburn 1983: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1984: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1985: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1986: }
1987: return $fetchresult;
1988: }
1989:
1.637 raeburn 1990: sub build_filepath {
1991: my ($fpath) = @_;
1992: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1993: unless ($fpath eq '') {
1994: my @parts=split('/',$fpath);
1995: foreach my $part (@parts) {
1996: $filepath.= '/'.$part;
1997: if ((-e $filepath)!=1) {
1998: mkdir($filepath,0777);
1999: }
2000: }
2001: }
2002: return $filepath;
2003: }
2004:
2005: sub store_edited_file {
1.638 albertel 2006: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2007: my $file = $primary_url;
2008: $file =~ s#^/uploaded/$docudom/$docuname/##;
2009: my $fpath = '';
2010: my $fname = $file;
2011: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2012: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2013: my $filepath = &build_filepath($fpath);
2014: open(my $fh,'>'.$filepath.'/'.$fname);
2015: print $fh $content;
2016: close($fh);
1.638 albertel 2017: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2018: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2019: $home);
1.637 raeburn 2020: if ($$fetchresult eq 'ok') {
2021: return '/uploaded/'.$fpath.'/'.$fname;
2022: } else {
1.638 albertel 2023: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2024: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2025: return '/adm/notfound.html';
2026: }
2027: }
2028:
1.531 albertel 2029: sub clean_filename {
1.831 albertel 2030: my ($fname,$args)=@_;
1.315 www 2031: # Replace Windows backslashes by forward slashes
1.257 www 2032: $fname=~s/\\/\//g;
1.831 albertel 2033: if (!$args->{'keep_path'}) {
2034: # Get rid of everything but the actual filename
2035: $fname=~s/^.*\/([^\/]+)$/$1/;
2036: }
1.315 www 2037: # Replace spaces by underscores
2038: $fname=~s/\s+/\_/g;
2039: # Replace all other weird characters by nothing
1.831 albertel 2040: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2041: # Replace all .\d. sequences with _\d. so they no longer look like version
2042: # numbers
2043: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2044: return $fname;
2045: }
1.984 neumanie 2046: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
2047: sub resizeImage {
2048: my($img_url) = @_;
2049: my $ima = Image::Magick->new;
2050: $ima->Read($img_url);
2051: if($ima->Get('width') > 400)
2052: {
2053: my $factor = $ima->Get('width')/400;
2054: $ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
2055: }
2056: if($ima->Get('height') > 500)
2057: {
2058: my $factor = $ima->Get('height')/500;
2059: $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
2060: }
2061:
2062: $ima->Write($img_url);
2063: }
1.531 albertel 2064:
1.977 amueller 2065: #Wrapper function for userphotoupload
2066: sub userphotoupload
2067: {
2068: my($formname,$subdir) = @_;
2069: $upload_photo_form = 1;
2070: return &userfileupload($formname,undef,$subdir);
2071: }
2072:
1.608 albertel 2073: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2074: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2075: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2076: # $coursedoc - if true up to the current course
2077: # if false
2078: # $subdir - directory in userfile to store the file into
1.858 raeburn 2079: # $parser - instruction to parse file for objects ($parser = parse)
2080: # $allfiles - reference to hash for embedded objects
2081: # $codebase - reference to hash for codebase of java objects
2082: # $desuname - username for permanent storage of uploaded file
2083: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2084: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2085: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 2086: #
1.686 albertel 2087: # output: url of file in userspace, or error: <message>
2088: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2089:
2090:
1.531 albertel 2091: sub userfileupload {
1.860 raeburn 2092: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2093: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 2094: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2095: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2096: $fname=&clean_filename($fname);
1.315 www 2097: # See if there is anything left
1.257 www 2098: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2099: chop($env{'form.'.$formname});
1.523 raeburn 2100: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2101: my $now = time;
2102: my $filepath = 'tmp/helprequests/'.$now;
2103: my @parts=split(/\//,$filepath);
2104: my $fullpath = $perlvar{'lonDaemons'};
2105: for (my $i=0;$i<@parts;$i++) {
2106: $fullpath .= '/'.$parts[$i];
2107: if ((-e $fullpath)!=1) {
2108: mkdir($fullpath,0777);
2109: }
2110: }
2111: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2112: print $fh $env{'form.'.$formname};
1.523 raeburn 2113: close($fh);
1.741 raeburn 2114: return $fullpath.'/'.$fname;
2115: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2116: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2117: '_'.$env{'user.domain'}.'/pending';
2118: my @parts=split(/\//,$filepath);
2119: my $fullpath = $perlvar{'lonDaemons'};
2120: for (my $i=0;$i<@parts;$i++) {
2121: $fullpath .= '/'.$parts[$i];
2122: if ((-e $fullpath)!=1) {
2123: mkdir($fullpath,0777);
2124: }
2125: }
2126: open(my $fh,'>'.$fullpath.'/'.$fname);
2127: print $fh $env{'form.'.$formname};
2128: close($fh);
2129: return $fullpath.'/'.$fname;
1.523 raeburn 2130: }
1.719 banghart 2131:
1.258 www 2132: # Create the directory if not present
1.493 albertel 2133: $fname="$subdir/$fname";
1.259 www 2134: if ($coursedoc) {
1.638 albertel 2135: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2136: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2137: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2138: return &finishuserfileupload($docuname,$docudom,
2139: $formname,$fname,$parser,$allfiles,
1.860 raeburn 2140: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 2141: } else {
1.620 albertel 2142: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2143: return &process_coursefile('uploaddoc',$docuname,$docudom,
2144: $fname,$formname,$parser,
2145: $allfiles,$codebase);
1.481 raeburn 2146: }
1.719 banghart 2147: } elsif (defined($destuname)) {
2148: my $docuname=$destuname;
2149: my $docudom=$destudom;
1.860 raeburn 2150: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2151: $parser,$allfiles,$codebase,
2152: $thumbwidth,$thumbheight);
1.719 banghart 2153:
1.259 www 2154: } else {
1.638 albertel 2155: my $docuname=$env{'user.name'};
2156: my $docudom=$env{'user.domain'};
1.714 raeburn 2157: if (exists($env{'form.group'})) {
2158: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2159: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2160: }
1.860 raeburn 2161: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2162: $parser,$allfiles,$codebase,
2163: $thumbwidth,$thumbheight);
1.259 www 2164: }
1.271 www 2165: }
2166:
2167: sub finishuserfileupload {
1.860 raeburn 2168: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2169: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 2170: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2171: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2172:
1.860 raeburn 2173: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2174: $file=$fname;
2175: if ($fname=~m|/|) {
2176: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2177: $path.=$fnamepath.'/';
2178: }
1.259 www 2179: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2180: my $count;
2181: for ($count=4;$count<=$#parts;$count++) {
2182: $filepath.="/$parts[$count]";
2183: if ((-e $filepath)!=1) {
2184: mkdir($filepath,0777);
2185: }
2186: }
1.984 neumanie 2187:
1.258 www 2188: # Save the file
2189: {
1.701 albertel 2190: if (!open(FH,'>'.$filepath.'/'.$file)) {
2191: &logthis('Failed to create '.$filepath.'/'.$file);
2192: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2193: return '/adm/notfound.html';
2194: }
2195: if (!print FH ($env{'form.'.$formname})) {
2196: &logthis('Failed to write to '.$filepath.'/'.$file);
2197: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2198: return '/adm/notfound.html';
2199: }
1.570 albertel 2200: close(FH);
1.977 amueller 2201: if($upload_photo_form==1)
2202: {
1.984 neumanie 2203: resizeImage($filepath.'/'.$file);
1.977 amueller 2204: $upload_photo_form = 0;
2205: }
1.258 www 2206: }
1.637 raeburn 2207: if ($parser eq 'parse') {
1.961 raeburn 2208: my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638 albertel 2209: $codebase);
1.637 raeburn 2210: unless ($parse_result eq 'ok') {
1.638 albertel 2211: &logthis('Failed to parse '.$filepath.$file.
2212: ' for embedded media: '.$parse_result);
1.637 raeburn 2213: }
2214: }
1.860 raeburn 2215: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2216: my $input = $filepath.'/'.$file;
2217: my $output = $filepath.'/'.'tn-'.$file;
2218: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2219: system("convert -sample $thumbsize $input $output");
2220: if (-e $filepath.'/'.'tn-'.$file) {
2221: $fetchthumb = 1;
2222: }
2223: }
1.858 raeburn 2224:
1.259 www 2225: # Notify homeserver to grep it
2226: #
1.984 neumanie 2227: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2228: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2229: if ($fetchresult eq 'ok') {
1.860 raeburn 2230: if ($fetchthumb) {
2231: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2232: if ($thumbresult ne 'ok') {
2233: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2234: $docuhome.': '.$thumbresult);
2235: }
2236: }
1.259 www 2237: #
1.258 www 2238: # Return the URL to it
1.494 albertel 2239: return '/uploaded/'.$path.$file;
1.263 www 2240: } else {
1.494 albertel 2241: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2242: ': '.$fetchresult);
1.263 www 2243: return '/adm/notfound.html';
1.858 raeburn 2244: }
1.493 albertel 2245: }
2246:
1.637 raeburn 2247: sub extract_embedded_items {
1.961 raeburn 2248: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2249: my @state = ();
2250: my %javafiles = (
2251: codebase => '',
2252: code => '',
2253: archive => ''
2254: );
2255: my %mediafiles = (
2256: src => '',
2257: movie => '',
2258: );
1.648 raeburn 2259: my $p;
2260: if ($content) {
2261: $p = HTML::LCParser->new($content);
2262: } else {
1.961 raeburn 2263: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2264: }
1.641 albertel 2265: while (my $t=$p->get_token()) {
1.640 albertel 2266: if ($t->[0] eq 'S') {
2267: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2268: push(@state, $tagname);
1.648 raeburn 2269: if (lc($tagname) eq 'allow') {
2270: &add_filetype($allfiles,$attr->{'src'},'src');
2271: }
1.640 albertel 2272: if (lc($tagname) eq 'img') {
2273: &add_filetype($allfiles,$attr->{'src'},'src');
2274: }
1.886 albertel 2275: if (lc($tagname) eq 'a') {
2276: &add_filetype($allfiles,$attr->{'href'},'href');
2277: }
1.645 raeburn 2278: if (lc($tagname) eq 'script') {
2279: if ($attr->{'archive'} =~ /\.jar$/i) {
2280: &add_filetype($allfiles,$attr->{'archive'},'archive');
2281: } else {
2282: &add_filetype($allfiles,$attr->{'src'},'src');
2283: }
2284: }
2285: if (lc($tagname) eq 'link') {
2286: if (lc($attr->{'rel'}) eq 'stylesheet') {
2287: &add_filetype($allfiles,$attr->{'href'},'href');
2288: }
2289: }
1.640 albertel 2290: if (lc($tagname) eq 'object' ||
2291: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2292: foreach my $item (keys(%javafiles)) {
2293: $javafiles{$item} = '';
2294: }
2295: }
2296: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2297: my $name = lc($attr->{'name'});
2298: foreach my $item (keys(%javafiles)) {
2299: if ($name eq $item) {
2300: $javafiles{$item} = $attr->{'value'};
2301: last;
2302: }
2303: }
2304: foreach my $item (keys(%mediafiles)) {
2305: if ($name eq $item) {
2306: &add_filetype($allfiles, $attr->{'value'}, 'value');
2307: last;
2308: }
2309: }
2310: }
2311: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2312: foreach my $item (keys(%javafiles)) {
2313: if ($attr->{$item}) {
2314: $javafiles{$item} = $attr->{$item};
2315: last;
2316: }
2317: }
2318: foreach my $item (keys(%mediafiles)) {
2319: if ($attr->{$item}) {
2320: &add_filetype($allfiles,$attr->{$item},$item);
2321: last;
2322: }
2323: }
2324: }
2325: } elsif ($t->[0] eq 'E') {
2326: my ($tagname) = ($t->[1]);
2327: if ($javafiles{'codebase'} ne '') {
2328: $javafiles{'codebase'} .= '/';
2329: }
2330: if (lc($tagname) eq 'applet' ||
2331: lc($tagname) eq 'object' ||
2332: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2333: ) {
2334: foreach my $item (keys(%javafiles)) {
2335: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2336: my $file=$javafiles{'codebase'}.$javafiles{$item};
2337: &add_filetype($allfiles,$file,$item);
2338: }
2339: }
2340: }
2341: pop @state;
2342: }
2343: }
1.637 raeburn 2344: return 'ok';
2345: }
2346:
1.639 albertel 2347: sub add_filetype {
2348: my ($allfiles,$file,$type)=@_;
2349: if (exists($allfiles->{$file})) {
2350: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2351: push(@{$allfiles->{$file}}, &escape($type));
2352: }
2353: } else {
2354: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2355: }
2356: }
2357:
1.493 albertel 2358: sub removeuploadedurl {
1.984 neumanie 2359: my ($url)=@_;
2360: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2361: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2362: }
2363:
2364: sub removeuserfile {
2365: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2366: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2367: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2368: if ($result eq 'ok') {
1.798 raeburn 2369: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2370: my $metafile = $fname.'.meta';
2371: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2372: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2373: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2374: my $sqlresult =
1.823 albertel 2375: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2376: 'portfolio_metadata',$group,
2377: 'delete');
1.798 raeburn 2378: }
2379: }
2380: return $result;
1.257 www 2381: }
1.15 www 2382:
1.530 albertel 2383: sub mkdiruserfile {
2384: my ($docuname,$docudom,$dir)=@_;
2385: my $home=&homeserver($docuname,$docudom);
2386: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2387: }
2388:
1.531 albertel 2389: sub renameuserfile {
2390: my ($docuname,$docudom,$old,$new)=@_;
2391: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2392: my $result = &reply("renameuserfile:$docudom:$docuname:".
2393: &escape("$old").':'.&escape("$new"),$home);
2394: if ($result eq 'ok') {
2395: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2396: my $oldmeta = $old.'.meta';
2397: my $newmeta = $new.'.meta';
2398: my $metaresult =
2399: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2400: my $url = "/uploaded/$docudom/$docuname/$old";
2401: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2402: my $sqlresult =
1.823 albertel 2403: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2404: 'portfolio_metadata',$group,
2405: 'delete');
1.798 raeburn 2406: }
2407: }
2408: return $result;
1.531 albertel 2409: }
2410:
1.14 www 2411: # ------------------------------------------------------------------------- Log
2412:
2413: sub log {
2414: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2415: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2416: }
2417:
2418: # ------------------------------------------------------------------ Course Log
1.352 www 2419: #
2420: # This routine flushes several buffers of non-mission-critical nature
2421: #
1.157 www 2422:
2423: sub flushcourselogs {
1.352 www 2424: &logthis('Flushing log buffers');
2425: #
2426: # course logs
2427: # This is a log of all transactions in a course, which can be used
2428: # for data mining purposes
2429: #
2430: # It also collects the courseid database, which lists last transaction
2431: # times and course titles for all courseids
2432: #
2433: my %courseidbuffer=();
1.921 raeburn 2434: foreach my $crsid (keys(%courselogs)) {
1.352 www 2435: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2436: &escape($courselogs{$crsid}),
2437: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2438: delete $courselogs{$crsid};
2439: } else {
2440: &logthis('Failed to flush log buffer for '.$crsid);
2441: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2442: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2443: " exceeded maximum size, deleting.</font>");
2444: delete $courselogs{$crsid};
2445: }
1.352 www 2446: }
1.920 raeburn 2447: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2448: 'description' => $coursedescrbuf{$crsid},
2449: 'inst_code' => $courseinstcodebuf{$crsid},
2450: 'type' => $coursetypebuf{$crsid},
2451: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2452: };
1.191 harris41 2453: }
1.352 www 2454: #
2455: # Write course id database (reverse lookup) to homeserver of courses
2456: # Is used in pickcourse
2457: #
1.840 albertel 2458: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2459: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2460: $courseidbuffer{$crs_home},
2461: $crs_home,'timeonly');
1.352 www 2462: }
2463: #
2464: # File accesses
2465: # Writes to the dynamic metadata of resources to get hit counts, etc.
2466: #
1.449 matthew 2467: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2468: if ($entry =~ /___count$/) {
2469: my ($dom,$name);
1.807 albertel 2470: ($dom,$name,undef)=
1.811 albertel 2471: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2472: if (! defined($dom) || $dom eq '' ||
2473: ! defined($name) || $name eq '') {
1.620 albertel 2474: my $cid = $env{'request.course.id'};
2475: $dom = $env{'request.'.$cid.'.domain'};
2476: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2477: }
1.450 matthew 2478: my $value = $accesshash{$entry};
2479: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2480: my %temphash=($url => $value);
1.449 matthew 2481: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2482: if ($result eq 'ok') {
2483: delete $accesshash{$entry};
2484: } elsif ($result eq 'unknown_cmd') {
2485: # Target server has old code running on it.
1.450 matthew 2486: my %temphash=($entry => $value);
1.449 matthew 2487: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2488: delete $accesshash{$entry};
2489: }
2490: }
2491: } else {
1.811 albertel 2492: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2493: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2494: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2495: delete $accesshash{$entry};
2496: }
1.185 www 2497: }
1.191 harris41 2498: }
1.352 www 2499: #
2500: # Roles
2501: # Reverse lookup of user roles for course faculty/staff and co-authorship
2502: #
1.800 albertel 2503: foreach my $entry (keys(%userrolehash)) {
1.351 www 2504: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2505: split(/\:/,$entry);
2506: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2507: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2508: $rudom,$runame) eq 'ok') {
2509: delete $userrolehash{$entry};
2510: }
2511: }
1.662 raeburn 2512: #
2513: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2514: #
2515: my %domrolebuffer = ();
2516: foreach my $entry (keys %domainrolehash) {
1.901 albertel 2517: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2518: if ($domrolebuffer{$rudom}) {
2519: $domrolebuffer{$rudom}.='&'.&escape($entry).
2520: '='.&escape($domainrolehash{$entry});
2521: } else {
2522: $domrolebuffer{$rudom}.=&escape($entry).
2523: '='.&escape($domainrolehash{$entry});
2524: }
2525: delete $domainrolehash{$entry};
2526: }
2527: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2528: my %servers = &get_servers($dom,'library');
2529: foreach my $tryserver (keys(%servers)) {
2530: unless (&reply('domroleput:'.$dom.':'.
2531: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2532: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2533: }
1.662 raeburn 2534: }
2535: }
1.186 www 2536: $dumpcount++;
1.157 www 2537: }
2538:
2539: sub courselog {
2540: my $what=shift;
1.158 www 2541: $what=time.':'.$what;
1.620 albertel 2542: unless ($env{'request.course.id'}) { return ''; }
2543: $coursedombuf{$env{'request.course.id'}}=
2544: $env{'course.'.$env{'request.course.id'}.'.domain'};
2545: $coursenumbuf{$env{'request.course.id'}}=
2546: $env{'course.'.$env{'request.course.id'}.'.num'};
2547: $coursehombuf{$env{'request.course.id'}}=
2548: $env{'course.'.$env{'request.course.id'}.'.home'};
2549: $coursedescrbuf{$env{'request.course.id'}}=
2550: $env{'course.'.$env{'request.course.id'}.'.description'};
2551: $courseinstcodebuf{$env{'request.course.id'}}=
2552: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2553: $courseownerbuf{$env{'request.course.id'}}=
2554: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2555: $coursetypebuf{$env{'request.course.id'}}=
2556: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2557: if (defined $courselogs{$env{'request.course.id'}}) {
2558: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2559: } else {
1.620 albertel 2560: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2561: }
1.620 albertel 2562: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2563: &flushcourselogs();
2564: }
1.158 www 2565: }
2566:
2567: sub courseacclog {
2568: my $fnsymb=shift;
1.620 albertel 2569: unless ($env{'request.course.id'}) { return ''; }
2570: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2571: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2572: $what.=':POST';
1.583 matthew 2573: # FIXME: Probably ought to escape things....
1.800 albertel 2574: foreach my $key (keys(%env)) {
2575: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2576: my $formitem = $1;
2577: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2578: $what.=':'.$formitem.'='.$env{$key};
2579: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2580: $what.=':'.$formitem.'='.$env{$key};
2581: }
1.158 www 2582: }
1.191 harris41 2583: }
1.583 matthew 2584: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2585: # FIXME: We should not be depending on a form parameter that someone
2586: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2587: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2588: $what.= ':POST';
2589: # FIXME: Probably ought to escape things....
2590: foreach my $element ('courseexp','crsfulltext','crsrelated',
2591: 'crsdiscuss') {
1.620 albertel 2592: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2593: }
2594: }
1.158 www 2595: }
2596: &courselog($what);
1.149 www 2597: }
2598:
1.185 www 2599: sub countacc {
2600: my $url=&declutter(shift);
1.458 matthew 2601: return if (! defined($url) || $url eq '');
1.620 albertel 2602: unless ($env{'request.course.id'}) { return ''; }
2603: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2604: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2605: $accesshash{$key}++;
1.185 www 2606: }
1.349 www 2607:
1.361 www 2608: sub linklog {
2609: my ($from,$to)=@_;
2610: $from=&declutter($from);
2611: $to=&declutter($to);
2612: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2613: $accesshash{$to.'___'.$from.'___goto'}=1;
2614: }
2615:
1.349 www 2616: sub userrolelog {
2617: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2618: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2619: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2620: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2621: ($trole=~/^ta/)) {
1.350 www 2622: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2623: $userrolehash
2624: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2625: =$tend.':'.$tstart;
1.662 raeburn 2626: }
1.898 albertel 2627: if (($env{'request.role'} =~ /dc\./) &&
2628: (($trole=~/^au/) || ($trole=~/^in/) ||
2629: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2630: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2631: $userrolehash
2632: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2633: =$tend.':'.$tstart;
2634: }
1.662 raeburn 2635: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2636: ($trole=~/^li/) || ($trole=~/^li/) ||
2637: ($trole=~/^au/) || ($trole=~/^dg/) ||
2638: ($trole=~/^sc/)) {
2639: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2640: $domainrolehash
2641: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2642: = $tend.':'.$tstart;
2643: }
1.351 www 2644: }
2645:
1.957 raeburn 2646: sub courserolelog {
2647: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2648: if (($trole eq 'cc') || ($trole eq 'in') ||
2649: ($trole eq 'ep') || ($trole eq 'ad') ||
2650: ($trole eq 'ta') || ($trole eq 'st') ||
2651: ($trole=~/^cr/) || ($trole eq 'gr')) {
2652: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2653: my $cdom = $1;
2654: my $cnum = $2;
2655: my $sec = $3;
2656: my $namespace = 'rolelog';
2657: my %storehash = (
2658: role => $trole,
2659: start => $tstart,
2660: end => $tend,
2661: selfenroll => $selfenroll,
2662: context => $context,
2663: );
2664: if ($trole eq 'gr') {
2665: $namespace = 'groupslog';
2666: $storehash{'group'} = $sec;
2667: } else {
2668: $storehash{'section'} = $sec;
2669: }
2670: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
2671: }
2672: }
2673: return;
2674: }
2675:
1.351 www 2676: sub get_course_adv_roles {
1.948 raeburn 2677: my ($cid,$codes) = @_;
1.620 albertel 2678: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2679: my %coursehash=&coursedescription($cid);
1.988 ! raeburn 2680: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2681: my %nothide=();
1.800 albertel 2682: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2683: if ($user !~ /:/) {
2684: $nothide{join(':',split(/[\@]/,$user))}=1;
2685: } else {
2686: $nothide{$user}=1;
2687: }
1.470 www 2688: }
1.351 www 2689: my %returnhash=();
2690: my %dumphash=
2691: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2692: my $now=time;
1.800 albertel 2693: foreach my $entry (keys %dumphash) {
2694: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2695: if (($tstart) && ($tstart<0)) { next; }
2696: if (($tend) && ($tend<$now)) { next; }
2697: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2698: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2699: if ($username eq '' || $domain eq '') { next; }
1.470 www 2700: if ((&privileged($username,$domain)) &&
2701: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2702: if ($role eq 'cr') { next; }
1.948 raeburn 2703: if ($codes) {
2704: if ($section) { $role .= ':'.$section; }
2705: if ($returnhash{$role}) {
2706: $returnhash{$role}.=','.$username.':'.$domain;
2707: } else {
2708: $returnhash{$role}=$username.':'.$domain;
2709: }
1.351 www 2710: } else {
1.988 ! raeburn 2711: my $key=&plaintext($role,$crstype);
1.973 bisitz 2712: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2713: if ($returnhash{$key}) {
2714: $returnhash{$key}.=','.$username.':'.$domain;
2715: } else {
2716: $returnhash{$key}=$username.':'.$domain;
2717: }
1.351 www 2718: }
1.948 raeburn 2719: }
1.400 www 2720: return %returnhash;
2721: }
2722:
2723: sub get_my_roles {
1.937 raeburn 2724: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2725: unless (defined($uname)) { $uname=$env{'user.name'}; }
2726: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2727: my (%dumphash,%nothide);
1.858 raeburn 2728: if ($context eq 'userroles') {
2729: %dumphash = &dump('roles',$udom,$uname);
2730: } else {
2731: %dumphash=
1.400 www 2732: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2733: if ($hidepriv) {
2734: my %coursehash=&coursedescription($udom.'_'.$uname);
2735: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2736: if ($user !~ /:/) {
2737: $nothide{join(':',split(/[\@]/,$user))} = 1;
2738: } else {
2739: $nothide{$user} = 1;
2740: }
2741: }
2742: }
1.858 raeburn 2743: }
1.400 www 2744: my %returnhash=();
2745: my $now=time;
1.800 albertel 2746: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2747: my ($role,$tend,$tstart);
2748: if ($context eq 'userroles') {
2749: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2750: } else {
2751: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2752: }
1.400 www 2753: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2754: my $status = 'active';
1.939 raeburn 2755: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2756: $status = 'previous';
2757: }
2758: if (($tstart) && ($now<$tstart)) {
2759: $status = 'future';
2760: }
2761: if (ref($types) eq 'ARRAY') {
2762: if (!grep(/^\Q$status\E$/,@{$types})) {
2763: next;
2764: }
2765: } else {
2766: if ($status ne 'active') {
2767: next;
2768: }
2769: }
1.867 raeburn 2770: my ($rolecode,$username,$domain,$section,$area);
2771: if ($context eq 'userroles') {
2772: ($area,$rolecode) = split(/_/,$entry);
2773: (undef,$domain,$username,$section) = split(/\//,$area);
2774: } else {
2775: ($role,$username,$domain,$section) = split(/\:/,$entry);
2776: }
1.832 raeburn 2777: if (ref($roledoms) eq 'ARRAY') {
2778: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2779: next;
2780: }
2781: }
2782: if (ref($roles) eq 'ARRAY') {
2783: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2784: if ($role =~ /^cr\//) {
2785: if (!grep(/^cr$/,@{$roles})) {
2786: next;
2787: }
2788: } else {
2789: next;
2790: }
1.832 raeburn 2791: }
1.867 raeburn 2792: }
1.937 raeburn 2793: if ($hidepriv) {
2794: if ((&privileged($username,$domain)) &&
2795: (!$nothide{$username.':'.$domain})) {
2796: next;
2797: }
2798: }
1.933 raeburn 2799: if ($withsec) {
2800: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2801: $tstart.':'.$tend;
2802: } else {
2803: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2804: }
1.832 raeburn 2805: }
1.373 www 2806: return %returnhash;
1.399 www 2807: }
2808:
2809: # ----------------------------------------------------- Frontpage Announcements
2810: #
2811: #
2812:
2813: sub postannounce {
2814: my ($server,$text)=@_;
1.844 albertel 2815: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2816: unless ($text=~/\w/) { $text=''; }
2817: return &reply('setannounce:'.&escape($text),$server);
2818: }
2819:
2820: sub getannounce {
1.448 albertel 2821:
2822: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2823: my $announcement='';
1.800 albertel 2824: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2825: close($fh);
1.399 www 2826: if ($announcement=~/\w/) {
2827: return
2828: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2829: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2830: } else {
2831: return '';
2832: }
2833: } else {
2834: return '';
2835: }
1.351 www 2836: }
1.353 www 2837:
2838: # ---------------------------------------------------------- Course ID routines
2839: # Deal with domain's nohist_courseid.db files
2840: #
2841:
2842: sub courseidput {
1.921 raeburn 2843: my ($domain,$storehash,$coursehome,$caller) = @_;
2844: my $outcome;
2845: if ($caller eq 'timeonly') {
2846: my $cids = '';
2847: foreach my $item (keys(%$storehash)) {
2848: $cids.=&escape($item).'&';
2849: }
2850: $cids=~s/\&$//;
2851: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2852: $coursehome);
2853: } else {
2854: my $items = '';
2855: foreach my $item (keys(%$storehash)) {
2856: $items.= &escape($item).'='.
2857: &freeze_escape($$storehash{$item}).'&';
2858: }
2859: $items=~s/\&$//;
2860: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2861: $coursehome);
1.918 raeburn 2862: }
2863: if ($outcome eq 'unknown_cmd') {
2864: my $what;
2865: foreach my $cid (keys(%$storehash)) {
2866: $what .= &escape($cid).'=';
1.921 raeburn 2867: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 2868: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 2869: }
2870: $what =~ s/\:$/&/;
2871: }
2872: $what =~ s/\&$//;
2873: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2874: } else {
2875: return $outcome;
2876: }
1.353 www 2877: }
2878:
2879: sub courseiddump {
1.921 raeburn 2880: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 2881: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962 raeburn 2882: $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918 raeburn 2883: my $as_hash = 1;
2884: my %returnhash;
2885: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2886: my %libserv = &all_library();
2887: foreach my $tryserver (keys(%libserv)) {
2888: if ( ( $hostidflag == 1
2889: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2890: || (!defined($hostidflag)) ) {
2891:
1.918 raeburn 2892: if (($domfilter eq '') ||
2893: (&host_domain($tryserver) eq $domfilter)) {
2894: my $rep =
2895: &reply('courseiddump:'.&host_domain($tryserver).':'.
2896: $sincefilter.':'.&escape($descfilter).':'.
2897: &escape($instcodefilter).':'.&escape($ownerfilter).
2898: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 2899: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 2900: &escape($selfenrollonly).':'.&escape($catfilter).':'.
2901: $showhidden.':'.$caller,$tryserver);
1.918 raeburn 2902: my @pairs=split(/\&/,$rep);
2903: foreach my $item (@pairs) {
2904: my ($key,$value)=split(/\=/,$item,2);
2905: $key = &unescape($key);
2906: next if ($key =~ /^error: 2 /);
2907: my $result = &thaw_unescape($value);
2908: if (ref($result) eq 'HASH') {
2909: $returnhash{$key}=$result;
2910: } else {
1.921 raeburn 2911: my @responses = split(/:/,$value);
2912: my @items = ('description','inst_code','owner','type');
1.918 raeburn 2913: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 2914: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 2915: }
2916: }
1.353 www 2917: }
2918: }
2919: }
2920: }
2921: return %returnhash;
2922: }
2923:
1.658 raeburn 2924: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2925:
2926: sub dcmailput {
1.685 raeburn 2927: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2928: my $status = &Apache::lonnet::critical(
1.740 www 2929: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2930: &escape($message),$server);
1.662 raeburn 2931: return $status;
2932: }
2933:
1.658 raeburn 2934: sub dcmaildump {
2935: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2936: my %returnhash=();
1.846 albertel 2937:
2938: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2939: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2940: &escape($enddate).':';
2941: my @esc_senders=map { &escape($_)} @$senders;
2942: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2943: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2944: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2945: if (($key) && ($value)) {
2946: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2947: }
2948: }
2949: }
2950: return %returnhash;
2951: }
1.662 raeburn 2952: # ---------------------------------------------------------- Domain roles
2953:
2954: sub get_domain_roles {
2955: my ($dom,$roles,$startdate,$enddate)=@_;
2956: if (undef($startdate) || $startdate eq '') {
2957: $startdate = '.';
2958: }
2959: if (undef($enddate) || $enddate eq '') {
2960: $enddate = '.';
2961: }
1.922 raeburn 2962: my $rolelist;
2963: if (ref($roles) eq 'ARRAY') {
2964: $rolelist = join(':',@{$roles});
2965: }
1.662 raeburn 2966: my %personnel = ();
1.841 albertel 2967:
2968: my %servers = &get_servers($dom,'library');
2969: foreach my $tryserver (keys(%servers)) {
2970: %{$personnel{$tryserver}}=();
2971: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2972: &escape($startdate).':'.
2973: &escape($enddate).':'.
2974: &escape($rolelist), $tryserver))) {
2975: my ($key,$value) = split(/\=/,$line,2);
2976: if (($key) && ($value)) {
2977: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2978: }
2979: }
1.662 raeburn 2980: }
2981: return %personnel;
2982: }
1.658 raeburn 2983:
1.149 www 2984: # ----------------------------------------------------------- Check out an item
2985:
1.504 albertel 2986: sub get_first_access {
2987: my ($type,$argsymb)=@_;
1.790 albertel 2988: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2989: if ($argsymb) { $symb=$argsymb; }
2990: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 2991: if ($type eq 'course') {
2992: $res='course';
2993: } elsif ($type eq 'map') {
1.588 albertel 2994: $res=&symbread($map);
2995: } else {
2996: $res=$symb;
2997: }
2998: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2999: return $times{"$courseid\0$res"};
1.504 albertel 3000: }
3001:
3002: sub set_first_access {
3003: my ($type)=@_;
1.790 albertel 3004: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3005: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3006: if ($type eq 'course') {
3007: $res='course';
3008: } elsif ($type eq 'map') {
1.588 albertel 3009: $res=&symbread($map);
3010: } else {
3011: $res=$symb;
3012: }
3013: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3014: if (!$firstaccess) {
1.588 albertel 3015: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3016: }
3017: return 'already_set';
1.504 albertel 3018: }
3019:
1.149 www 3020: sub checkout {
3021: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3022: my $now=time;
3023: my $lonhost=$perlvar{'lonHostID'};
3024: my $infostr=&escape(
1.234 www 3025: 'CHECKOUTTOKEN&'.
1.149 www 3026: $tuname.'&'.
3027: $tudom.'&'.
3028: $tcrsid.'&'.
3029: $symb.'&'.
3030: $now.'&'.$ENV{'REMOTE_ADDR'});
3031: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3032: if ($token=~/^error\:/) {
1.672 albertel 3033: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3034: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3035: "</font>");
3036: return '';
3037: }
3038:
1.149 www 3039: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3040: $token=~tr/a-z/A-Z/;
3041:
1.153 www 3042: my %infohash=('resource.0.outtoken' => $token,
3043: 'resource.0.checkouttime' => $now,
3044: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3045:
3046: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3047: return '';
1.151 www 3048: } else {
1.672 albertel 3049: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3050: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3051: "</font>");
1.149 www 3052: }
3053:
3054: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3055: &escape('Checkout '.$infostr.' - '.
3056: $token)) ne 'ok') {
3057: return '';
1.151 www 3058: } else {
1.672 albertel 3059: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3060: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3061: "</font>");
1.149 www 3062: }
1.151 www 3063: return $token;
1.149 www 3064: }
3065:
3066: # ------------------------------------------------------------ Check in an item
3067:
3068: sub checkin {
3069: my $token=shift;
1.150 www 3070: my $now=time;
3071: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3072: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3073: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3074: $dtoken=~s/\W/\_/g;
1.234 www 3075: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3076: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3077:
1.154 www 3078: unless (($tuname) && ($tudom)) {
3079: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3080: return '';
3081: }
3082:
3083: unless (&allowed('mgr',$tcrsid)) {
3084: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3085: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3086: return '';
3087: }
3088:
1.153 www 3089: my %infohash=('resource.0.intoken' => $token,
3090: 'resource.0.checkintime' => $now,
3091: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3092:
3093: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3094: return '';
3095: }
3096:
3097: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3098: &escape('Checkin - '.$token)) ne 'ok') {
3099: return '';
3100: }
3101:
3102: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3103: }
3104:
3105: # --------------------------------------------- Set Expire Date for Spreadsheet
3106:
3107: sub expirespread {
3108: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3109: my $cid=$env{'request.course.id'};
1.110 www 3110: if ($cid) {
3111: my $now=time;
3112: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3113: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3114: $env{'course.'.$cid.'.num'}.
1.110 www 3115: ':nohist_expirationdates:'.
3116: &escape($key).'='.$now,
1.620 albertel 3117: $env{'course.'.$cid.'.home'})
1.110 www 3118: }
3119: return 'ok';
1.14 www 3120: }
3121:
1.109 www 3122: # ----------------------------------------------------- Devalidate Spreadsheets
3123:
3124: sub devalidate {
1.325 www 3125: my ($symb,$uname,$udom)=@_;
1.620 albertel 3126: my $cid=$env{'request.course.id'};
1.109 www 3127: if ($cid) {
1.391 matthew 3128: # delete the stored spreadsheets for
3129: # - the student level sheet of this user in course's homespace
3130: # - the assessment level sheet for this resource
3131: # for this user in user's homespace
1.553 albertel 3132: # - current conditional state info
1.325 www 3133: my $key=$uname.':'.$udom.':';
1.109 www 3134: my $status=
1.299 matthew 3135: &del('nohist_calculatedsheets',
1.391 matthew 3136: [$key.'studentcalc:'],
1.620 albertel 3137: $env{'course.'.$cid.'.domain'},
3138: $env{'course.'.$cid.'.num'})
1.133 albertel 3139: .' '.
3140: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3141: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3142: unless ($status eq 'ok ok') {
3143: &logthis('Could not devalidate spreadsheet '.
1.325 www 3144: $uname.' at '.$udom.' for '.
1.109 www 3145: $symb.': '.$status);
1.133 albertel 3146: }
1.553 albertel 3147: &delenv('user.state.'.$cid);
1.109 www 3148: }
3149: }
3150:
1.265 albertel 3151: sub get_scalar {
3152: my ($string,$end) = @_;
3153: my $value;
3154: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3155: $value = $1;
3156: } elsif ($$string =~ s/^([^&]*?)&//) {
3157: $value = $1;
3158: }
3159: return &unescape($value);
3160: }
3161:
3162: sub array2str {
3163: my (@array) = @_;
3164: my $result=&arrayref2str(\@array);
3165: $result=~s/^__ARRAY_REF__//;
3166: $result=~s/__END_ARRAY_REF__$//;
3167: return $result;
3168: }
3169:
1.204 albertel 3170: sub arrayref2str {
3171: my ($arrayref) = @_;
1.265 albertel 3172: my $result='__ARRAY_REF__';
1.204 albertel 3173: foreach my $elem (@$arrayref) {
1.265 albertel 3174: if(ref($elem) eq 'ARRAY') {
3175: $result.=&arrayref2str($elem).'&';
3176: } elsif(ref($elem) eq 'HASH') {
3177: $result.=&hashref2str($elem).'&';
3178: } elsif(ref($elem)) {
3179: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3180: } else {
3181: $result.=&escape($elem).'&';
3182: }
3183: }
3184: $result=~s/\&$//;
1.265 albertel 3185: $result .= '__END_ARRAY_REF__';
1.204 albertel 3186: return $result;
3187: }
3188:
1.168 albertel 3189: sub hash2str {
1.204 albertel 3190: my (%hash) = @_;
3191: my $result=&hashref2str(\%hash);
1.265 albertel 3192: $result=~s/^__HASH_REF__//;
3193: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3194: return $result;
3195: }
3196:
3197: sub hashref2str {
3198: my ($hashref)=@_;
1.265 albertel 3199: my $result='__HASH_REF__';
1.800 albertel 3200: foreach my $key (sort(keys(%$hashref))) {
3201: if (ref($key) eq 'ARRAY') {
3202: $result.=&arrayref2str($key).'=';
3203: } elsif (ref($key) eq 'HASH') {
3204: $result.=&hashref2str($key).'=';
3205: } elsif (ref($key)) {
1.265 albertel 3206: $result.='=';
1.800 albertel 3207: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3208: } else {
1.800 albertel 3209: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3210: }
3211:
1.800 albertel 3212: if(ref($hashref->{$key}) eq 'ARRAY') {
3213: $result.=&arrayref2str($hashref->{$key}).'&';
3214: } elsif(ref($hashref->{$key}) eq 'HASH') {
3215: $result.=&hashref2str($hashref->{$key}).'&';
3216: } elsif(ref($hashref->{$key})) {
1.265 albertel 3217: $result.='&';
1.800 albertel 3218: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3219: } else {
1.800 albertel 3220: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3221: }
3222: }
1.168 albertel 3223: $result=~s/\&$//;
1.265 albertel 3224: $result .= '__END_HASH_REF__';
1.168 albertel 3225: return $result;
3226: }
3227:
3228: sub str2hash {
1.265 albertel 3229: my ($string)=@_;
3230: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3231: return %$hash;
3232: }
3233:
3234: sub str2hashref {
1.168 albertel 3235: my ($string) = @_;
1.265 albertel 3236:
3237: my %hash;
3238:
3239: if($string !~ /^__HASH_REF__/) {
3240: if (! ($string eq '' || !defined($string))) {
3241: $hash{'error'}='Not hash reference';
3242: }
3243: return (\%hash, $string);
3244: }
3245:
3246: $string =~ s/^__HASH_REF__//;
3247:
3248: while($string !~ /^__END_HASH_REF__/) {
3249: #key
3250: my $key='';
3251: if($string =~ /^__HASH_REF__/) {
3252: ($key, $string)=&str2hashref($string);
3253: if(defined($key->{'error'})) {
3254: $hash{'error'}='Bad data';
3255: return (\%hash, $string);
3256: }
3257: } elsif($string =~ /^__ARRAY_REF__/) {
3258: ($key, $string)=&str2arrayref($string);
3259: if($key->[0] eq 'Array reference error') {
3260: $hash{'error'}='Bad data';
3261: return (\%hash, $string);
3262: }
3263: } else {
3264: $string =~ s/^(.*?)=//;
1.267 albertel 3265: $key=&unescape($1);
1.265 albertel 3266: }
3267: $string =~ s/^=//;
3268:
3269: #value
3270: my $value='';
3271: if($string =~ /^__HASH_REF__/) {
3272: ($value, $string)=&str2hashref($string);
3273: if(defined($value->{'error'})) {
3274: $hash{'error'}='Bad data';
3275: return (\%hash, $string);
3276: }
3277: } elsif($string =~ /^__ARRAY_REF__/) {
3278: ($value, $string)=&str2arrayref($string);
3279: if($value->[0] eq 'Array reference error') {
3280: $hash{'error'}='Bad data';
3281: return (\%hash, $string);
3282: }
3283: } else {
3284: $value=&get_scalar(\$string,'__END_HASH_REF__');
3285: }
3286: $string =~ s/^&//;
3287:
3288: $hash{$key}=$value;
1.204 albertel 3289: }
1.265 albertel 3290:
3291: $string =~ s/^__END_HASH_REF__//;
3292:
3293: return (\%hash, $string);
1.204 albertel 3294: }
3295:
3296: sub str2array {
1.265 albertel 3297: my ($string)=@_;
3298: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3299: return @$array;
3300: }
3301:
3302: sub str2arrayref {
1.204 albertel 3303: my ($string) = @_;
1.265 albertel 3304: my @array;
3305:
3306: if($string !~ /^__ARRAY_REF__/) {
3307: if (! ($string eq '' || !defined($string))) {
3308: $array[0]='Array reference error';
3309: }
3310: return (\@array, $string);
3311: }
3312:
3313: $string =~ s/^__ARRAY_REF__//;
3314:
3315: while($string !~ /^__END_ARRAY_REF__/) {
3316: my $value='';
3317: if($string =~ /^__HASH_REF__/) {
3318: ($value, $string)=&str2hashref($string);
3319: if(defined($value->{'error'})) {
3320: $array[0] ='Array reference error';
3321: return (\@array, $string);
3322: }
3323: } elsif($string =~ /^__ARRAY_REF__/) {
3324: ($value, $string)=&str2arrayref($string);
3325: if($value->[0] eq 'Array reference error') {
3326: $array[0] ='Array reference error';
3327: return (\@array, $string);
3328: }
3329: } else {
3330: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3331: }
3332: $string =~ s/^&//;
3333:
3334: push(@array, $value);
1.191 harris41 3335: }
1.265 albertel 3336:
3337: $string =~ s/^__END_ARRAY_REF__//;
3338:
3339: return (\@array, $string);
1.168 albertel 3340: }
3341:
1.167 albertel 3342: # -------------------------------------------------------------------Temp Store
3343:
1.168 albertel 3344: sub tmpreset {
3345: my ($symb,$namespace,$domain,$stuname) = @_;
3346: if (!$symb) {
3347: $symb=&symbread();
1.620 albertel 3348: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3349: }
3350: $symb=escape($symb);
3351:
1.620 albertel 3352: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3353: $namespace=~s/\//\_/g;
3354: $namespace=~s/\W//g;
3355:
1.620 albertel 3356: if (!$domain) { $domain=$env{'user.domain'}; }
3357: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3358: if ($domain eq 'public' && $stuname eq 'public') {
3359: $stuname=$ENV{'REMOTE_ADDR'};
3360: }
1.168 albertel 3361: my $path=$perlvar{'lonDaemons'}.'/tmp';
3362: my %hash;
3363: if (tie(%hash,'GDBM_File',
3364: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3365: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3366: foreach my $key (keys %hash) {
1.180 albertel 3367: if ($key=~ /:$symb/) {
1.168 albertel 3368: delete($hash{$key});
3369: }
3370: }
3371: }
3372: }
3373:
1.167 albertel 3374: sub tmpstore {
1.168 albertel 3375: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3376:
3377: if (!$symb) {
3378: $symb=&symbread();
1.620 albertel 3379: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3380: }
3381: $symb=escape($symb);
3382:
3383: if (!$namespace) {
3384: # I don't think we would ever want to store this for a course.
3385: # it seems this will only be used if we don't have a course.
1.620 albertel 3386: #$namespace=$env{'request.course.id'};
1.168 albertel 3387: #if (!$namespace) {
1.620 albertel 3388: $namespace=$env{'request.state'};
1.168 albertel 3389: #}
3390: }
3391: $namespace=~s/\//\_/g;
3392: $namespace=~s/\W//g;
1.620 albertel 3393: if (!$domain) { $domain=$env{'user.domain'}; }
3394: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3395: if ($domain eq 'public' && $stuname eq 'public') {
3396: $stuname=$ENV{'REMOTE_ADDR'};
3397: }
1.168 albertel 3398: my $now=time;
3399: my %hash;
3400: my $path=$perlvar{'lonDaemons'}.'/tmp';
3401: if (tie(%hash,'GDBM_File',
3402: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3403: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3404: $hash{"version:$symb"}++;
3405: my $version=$hash{"version:$symb"};
3406: my $allkeys='';
3407: foreach my $key (keys(%$storehash)) {
3408: $allkeys.=$key.':';
1.591 albertel 3409: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3410: }
3411: $hash{"$version:$symb:timestamp"}=$now;
3412: $allkeys.='timestamp';
3413: $hash{"$version:keys:$symb"}=$allkeys;
3414: if (untie(%hash)) {
3415: return 'ok';
3416: } else {
3417: return "error:$!";
3418: }
3419: } else {
3420: return "error:$!";
3421: }
3422: }
1.167 albertel 3423:
1.168 albertel 3424: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3425:
1.168 albertel 3426: sub tmprestore {
3427: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3428:
1.168 albertel 3429: if (!$symb) {
3430: $symb=&symbread();
1.620 albertel 3431: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3432: }
3433: $symb=escape($symb);
3434:
1.620 albertel 3435: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3436:
1.620 albertel 3437: if (!$domain) { $domain=$env{'user.domain'}; }
3438: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3439: if ($domain eq 'public' && $stuname eq 'public') {
3440: $stuname=$ENV{'REMOTE_ADDR'};
3441: }
1.168 albertel 3442: my %returnhash;
3443: $namespace=~s/\//\_/g;
3444: $namespace=~s/\W//g;
3445: my %hash;
3446: my $path=$perlvar{'lonDaemons'}.'/tmp';
3447: if (tie(%hash,'GDBM_File',
3448: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3449: &GDBM_READER(),0640)) {
1.168 albertel 3450: my $version=$hash{"version:$symb"};
3451: $returnhash{'version'}=$version;
3452: my $scope;
3453: for ($scope=1;$scope<=$version;$scope++) {
3454: my $vkeys=$hash{"$scope:keys:$symb"};
3455: my @keys=split(/:/,$vkeys);
3456: my $key;
3457: $returnhash{"$scope:keys"}=$vkeys;
3458: foreach $key (@keys) {
1.591 albertel 3459: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3460: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3461: }
3462: }
1.168 albertel 3463: if (!(untie(%hash))) {
3464: return "error:$!";
3465: }
3466: } else {
3467: return "error:$!";
3468: }
3469: return %returnhash;
1.167 albertel 3470: }
3471:
1.9 www 3472: # ----------------------------------------------------------------------- Store
3473:
3474: sub store {
1.124 www 3475: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3476: my $home='';
3477:
1.168 albertel 3478: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3479:
1.213 www 3480: $symb=&symbclean($symb);
1.122 albertel 3481: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3482:
1.620 albertel 3483: if (!$domain) { $domain=$env{'user.domain'}; }
3484: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3485:
3486: &devalidate($symb,$stuname,$domain);
1.109 www 3487:
3488: $symb=escape($symb);
1.187 www 3489: if (!$namespace) {
1.620 albertel 3490: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3491: return '';
3492: }
3493: }
1.620 albertel 3494: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3495:
3496: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3497: $$storehash{'host'}=$perlvar{'lonHostID'};
3498:
1.12 www 3499: my $namevalue='';
1.800 albertel 3500: foreach my $key (keys(%$storehash)) {
3501: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3502: }
1.12 www 3503: $namevalue=~s/\&$//;
1.187 www 3504: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3505: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3506: }
3507:
1.47 www 3508: # -------------------------------------------------------------- Critical Store
3509:
3510: sub cstore {
1.124 www 3511: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3512: my $home='';
3513:
1.168 albertel 3514: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3515:
1.213 www 3516: $symb=&symbclean($symb);
1.122 albertel 3517: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3518:
1.620 albertel 3519: if (!$domain) { $domain=$env{'user.domain'}; }
3520: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3521:
3522: &devalidate($symb,$stuname,$domain);
1.109 www 3523:
3524: $symb=escape($symb);
1.187 www 3525: if (!$namespace) {
1.620 albertel 3526: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3527: return '';
3528: }
3529: }
1.620 albertel 3530: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3531:
3532: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3533: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3534:
1.47 www 3535: my $namevalue='';
1.800 albertel 3536: foreach my $key (keys(%$storehash)) {
3537: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3538: }
1.47 www 3539: $namevalue=~s/\&$//;
1.187 www 3540: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3541: return critical
3542: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3543: }
3544:
1.9 www 3545: # --------------------------------------------------------------------- Restore
3546:
3547: sub restore {
1.124 www 3548: my ($symb,$namespace,$domain,$stuname) = @_;
3549: my $home='';
3550:
1.168 albertel 3551: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3552:
1.122 albertel 3553: if (!$symb) {
3554: unless ($symb=escape(&symbread())) { return ''; }
3555: } else {
1.213 www 3556: $symb=&escape(&symbclean($symb));
1.122 albertel 3557: }
1.188 www 3558: if (!$namespace) {
1.620 albertel 3559: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3560: return '';
3561: }
3562: }
1.620 albertel 3563: if (!$domain) { $domain=$env{'user.domain'}; }
3564: if (!$stuname) { $stuname=$env{'user.name'}; }
3565: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3566: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3567:
1.12 www 3568: my %returnhash=();
1.800 albertel 3569: foreach my $line (split(/\&/,$answer)) {
3570: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3571: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3572: }
1.75 www 3573: my $version;
3574: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3575: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3576: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3577: }
1.75 www 3578: }
1.13 www 3579: return %returnhash;
1.34 www 3580: }
3581:
3582: # ---------------------------------------------------------- Course Description
3583:
3584: sub coursedescription {
1.731 albertel 3585: my ($courseid,$args)=@_;
1.34 www 3586: $courseid=~s/^\///;
1.49 www 3587: $courseid=~s/\_/\//g;
1.34 www 3588: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3589: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3590: my $normalid=$cdomain.'_'.$cnum;
3591: # need to always cache even if we get errors otherwise we keep
3592: # trying and trying and trying to get the course description.
3593: my %envhash=();
3594: my %returnhash=();
1.731 albertel 3595:
3596: my $expiretime=600;
3597: if ($env{'request.course.id'} eq $normalid) {
3598: $expiretime=120;
3599: }
3600:
3601: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3602: if (!$args->{'freshen_cache'}
3603: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3604: foreach my $key (keys(%env)) {
3605: next if ($key !~ /^\Q$prefix\E(.*)/);
3606: my ($setting) = $1;
3607: $returnhash{$setting} = $env{$key};
3608: }
3609: return %returnhash;
3610: }
3611:
3612: # get the data agin
3613: if (!$args->{'one_time'}) {
3614: $envhash{'course.'.$normalid.'.last_cache'}=time;
3615: }
1.811 albertel 3616:
1.34 www 3617: if ($chome ne 'no_host') {
1.302 albertel 3618: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3619: if (!exists($returnhash{'con_lost'})) {
3620: $returnhash{'home'}= $chome;
3621: $returnhash{'domain'} = $cdomain;
3622: $returnhash{'num'} = $cnum;
1.741 raeburn 3623: if (!defined($returnhash{'type'})) {
3624: $returnhash{'type'} = 'Course';
3625: }
1.130 albertel 3626: while (my ($name,$value) = each %returnhash) {
1.53 www 3627: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3628: }
1.270 www 3629: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3630: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3631: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3632: $envhash{'course.'.$normalid.'.home'}=$chome;
3633: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3634: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3635: }
3636: }
1.731 albertel 3637: if (!$args->{'one_time'}) {
1.949 raeburn 3638: &appenv(\%envhash);
1.731 albertel 3639: }
1.302 albertel 3640: return %returnhash;
1.461 www 3641: }
3642:
3643: # -------------------------------------------------See if a user is privileged
3644:
3645: sub privileged {
3646: my ($username,$domain)=@_;
3647: my $rolesdump=&reply("dump:$domain:$username:roles",
3648: &homeserver($username,$domain));
3649: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3650: my $now=time;
3651: if ($rolesdump ne '') {
1.800 albertel 3652: foreach my $entry (split(/&/,$rolesdump)) {
3653: if ($entry!~/^rolesdef_/) {
3654: my ($area,$role)=split(/=/,$entry);
1.461 www 3655: $area=~s/\_\w\w$//;
3656: my ($trole,$tend,$tstart)=split(/_/,$role);
3657: if (($trole eq 'dc') || ($trole eq 'su')) {
3658: my $active=1;
3659: if ($tend) {
3660: if ($tend<$now) { $active=0; }
3661: }
3662: if ($tstart) {
3663: if ($tstart>$now) { $active=0; }
3664: }
3665: if ($active) { return 1; }
3666: }
3667: }
3668: }
3669: }
3670: return 0;
1.9 www 3671: }
1.1 albertel 3672:
1.103 harris41 3673: # -------------------------------------------------------- Get user privileges
1.11 www 3674:
3675: sub rolesinit {
3676: my ($domain,$username,$authhost)=@_;
1.966 raeburn 3677: my %userroles;
1.11 www 3678: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966 raeburn 3679: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11 www 3680: my %allroles=();
1.678 raeburn 3681: my %allgroups=();
1.11 www 3682: my $now=time;
1.966 raeburn 3683: %userroles = ('user.login.time' => $now);
1.678 raeburn 3684: my $group_privs;
1.11 www 3685:
3686: if ($rolesdump ne '') {
1.800 albertel 3687: foreach my $entry (split(/&/,$rolesdump)) {
3688: if ($entry!~/^rolesdef_/) {
3689: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3690: $area=~s/\_\w\w$//;
1.678 raeburn 3691: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3692: if ($role=~/^cr/) {
1.807 albertel 3693: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3694: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3695: ($tend,$tstart)=split('_',$trest);
3696: } else {
3697: $trole=$role;
3698: }
1.678 raeburn 3699: } elsif ($role =~ m|^gr/|) {
3700: ($trole,$tend,$tstart) = split(/_/,$role);
3701: ($trole,$group_privs) = split(/\//,$trole);
3702: $group_privs = &unescape($group_privs);
1.587 albertel 3703: } else {
3704: ($trole,$tend,$tstart)=split(/_/,$role);
3705: }
1.743 albertel 3706: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3707: $username);
3708: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3709: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3710: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3711: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3712: my $spec=$trole.'.'.$area;
3713: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3714: if ($trole =~ /^cr\//) {
1.567 raeburn 3715: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3716: } elsif ($trole eq 'gr') {
3717: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3718: } else {
1.567 raeburn 3719: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3720: }
1.12 www 3721: }
1.662 raeburn 3722: }
1.191 harris41 3723: }
1.743 albertel 3724: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3725: $userroles{'user.adv'} = $adv;
3726: $userroles{'user.author'} = $author;
1.620 albertel 3727: $env{'user.adv'}=$adv;
1.11 www 3728: }
1.743 albertel 3729: return \%userroles;
1.11 www 3730: }
3731:
1.567 raeburn 3732: sub set_arearole {
3733: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3734: # log the associated role with the area
3735: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3736: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3737: }
3738:
3739: sub custom_roleprivs {
3740: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3741: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3742: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3743: if (&hostname($homsvr) ne '') {
1.567 raeburn 3744: my ($rdummy,$roledef)=
3745: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3746: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3747: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3748: if (defined($syspriv)) {
3749: $$allroles{'cm./'}.=':'.$syspriv;
3750: $$allroles{$spec.'./'}.=':'.$syspriv;
3751: }
3752: if ($tdomain ne '') {
3753: if (defined($dompriv)) {
3754: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3755: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3756: }
3757: if (($trest ne '') && (defined($coursepriv))) {
3758: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3759: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3760: }
3761: }
3762: }
3763: }
3764: }
3765:
1.678 raeburn 3766: sub group_roleprivs {
3767: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3768: my $access = 1;
3769: my $now = time;
3770: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3771: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3772: if ($access) {
1.811 albertel 3773: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3774: $$allgroups{$course}{$group} .=':'.$group_privs;
3775: }
3776: }
1.567 raeburn 3777:
3778: sub standard_roleprivs {
3779: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3780: if (defined($pr{$trole.':s'})) {
3781: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3782: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3783: }
3784: if ($tdomain ne '') {
3785: if (defined($pr{$trole.':d'})) {
3786: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3787: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3788: }
3789: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3790: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3791: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3792: }
3793: }
3794: }
3795:
3796: sub set_userprivs {
1.678 raeburn 3797: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3798: my $author=0;
3799: my $adv=0;
1.678 raeburn 3800: my %grouproles = ();
3801: if (keys(%{$allgroups}) > 0) {
3802: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3803: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3804: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3805: $trole = $1;
3806: $area = $2;
1.681 raeburn 3807: $sec = $3;
3808: $extendedarea = $area.$sec;
3809: if (exists($$allgroups{$area})) {
3810: foreach my $group (keys(%{$$allgroups{$area}})) {
3811: my $spec = $trole.'.'.$extendedarea;
3812: $grouproles{$spec.'.'.$area.'/'.$group} =
3813: $$allgroups{$area}{$group};
1.678 raeburn 3814: }
3815: }
3816: }
3817: }
3818: }
1.800 albertel 3819: foreach my $group (keys(%grouproles)) {
3820: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3821: }
1.800 albertel 3822: foreach my $role (keys(%{$allroles})) {
3823: my %thesepriv;
1.941 raeburn 3824: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3825: foreach my $item (split(/:/,$$allroles{$role})) {
3826: if ($item ne '') {
3827: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3828: if ($restrictions eq '') {
3829: $thesepriv{$privilege}='F';
3830: } elsif ($thesepriv{$privilege} ne 'F') {
3831: $thesepriv{$privilege}.=$restrictions;
3832: }
3833: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3834: }
3835: }
3836: my $thesestr='';
1.800 albertel 3837: foreach my $priv (keys(%thesepriv)) {
3838: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3839: }
3840: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3841: }
3842: return ($author,$adv);
3843: }
3844:
1.12 www 3845: # --------------------------------------------------------------- get interface
3846:
3847: sub get {
1.131 albertel 3848: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3849: my $items='';
1.800 albertel 3850: foreach my $item (@$storearr) {
3851: $items.=&escape($item).'&';
1.191 harris41 3852: }
1.12 www 3853: $items=~s/\&$//;
1.620 albertel 3854: if (!$udomain) { $udomain=$env{'user.domain'}; }
3855: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3856: my $uhome=&homeserver($uname,$udomain);
3857:
1.133 albertel 3858: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3859: my @pairs=split(/\&/,$rep);
1.273 albertel 3860: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3861: return @pairs;
3862: }
1.15 www 3863: my %returnhash=();
1.42 www 3864: my $i=0;
1.800 albertel 3865: foreach my $item (@$storearr) {
3866: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3867: $i++;
1.191 harris41 3868: }
1.15 www 3869: return %returnhash;
1.27 www 3870: }
3871:
3872: # --------------------------------------------------------------- del interface
3873:
3874: sub del {
1.133 albertel 3875: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3876: my $items='';
1.800 albertel 3877: foreach my $item (@$storearr) {
3878: $items.=&escape($item).'&';
1.191 harris41 3879: }
1.984 neumanie 3880:
1.27 www 3881: $items=~s/\&$//;
1.620 albertel 3882: if (!$udomain) { $udomain=$env{'user.domain'}; }
3883: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3884: my $uhome=&homeserver($uname,$udomain);
3885: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3886: }
3887:
3888: # -------------------------------------------------------------- dump interface
3889:
3890: sub dump {
1.755 albertel 3891: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3892: if (!$udomain) { $udomain=$env{'user.domain'}; }
3893: if (!$uname) { $uname=$env{'user.name'}; }
3894: my $uhome=&homeserver($uname,$udomain);
3895: if ($regexp) {
3896: $regexp=&escape($regexp);
3897: } else {
3898: $regexp='.';
3899: }
3900: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3901: my @pairs=split(/\&/,$rep);
3902: my %returnhash=();
3903: foreach my $item (@pairs) {
3904: my ($key,$value)=split(/=/,$item,2);
3905: $key = &unescape($key);
3906: next if ($key =~ /^error: 2 /);
3907: $returnhash{$key}=&thaw_unescape($value);
3908: }
3909: return %returnhash;
1.407 www 3910: }
3911:
1.717 albertel 3912: # --------------------------------------------------------- dumpstore interface
3913:
3914: sub dumpstore {
3915: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3916: if (!$udomain) { $udomain=$env{'user.domain'}; }
3917: if (!$uname) { $uname=$env{'user.name'}; }
3918: my $uhome=&homeserver($uname,$udomain);
3919: if ($regexp) {
3920: $regexp=&escape($regexp);
3921: } else {
3922: $regexp='.';
3923: }
3924: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3925: my @pairs=split(/\&/,$rep);
3926: my %returnhash=();
3927: foreach my $item (@pairs) {
3928: my ($key,$value)=split(/=/,$item,2);
3929: next if ($key =~ /^error: 2 /);
3930: $returnhash{$key}=&thaw_unescape($value);
3931: }
3932: return %returnhash;
1.717 albertel 3933: }
3934:
1.407 www 3935: # -------------------------------------------------------------- keys interface
3936:
3937: sub getkeys {
3938: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3939: if (!$udomain) { $udomain=$env{'user.domain'}; }
3940: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3941: my $uhome=&homeserver($uname,$udomain);
3942: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3943: my @keyarray=();
1.800 albertel 3944: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3945: next if ($key =~ /^error: 2 /);
1.800 albertel 3946: push(@keyarray,&unescape($key));
1.407 www 3947: }
3948: return @keyarray;
1.318 matthew 3949: }
3950:
1.319 matthew 3951: # --------------------------------------------------------------- currentdump
3952: sub currentdump {
1.328 matthew 3953: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3954: $courseid = $env{'request.course.id'} if (! defined($courseid));
3955: $sdom = $env{'user.domain'} if (! defined($sdom));
3956: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3957: my $uhome = &homeserver($sname,$sdom);
3958: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3959: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3960: #
1.318 matthew 3961: my %returnhash=();
1.319 matthew 3962: #
3963: if ($rep eq "unknown_cmd") {
3964: # an old lond will not know currentdump
3965: # Do a dump and make it look like a currentdump
1.822 albertel 3966: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3967: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3968: my %hash = @tmp;
3969: @tmp=();
1.424 matthew 3970: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3971: } else {
3972: my @pairs=split(/\&/,$rep);
1.800 albertel 3973: foreach my $pair (@pairs) {
3974: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3975: my ($symb,$param) = split(/:/,$key);
3976: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3977: &thaw_unescape($value);
1.319 matthew 3978: }
1.191 harris41 3979: }
1.12 www 3980: return %returnhash;
1.424 matthew 3981: }
3982:
3983: sub convert_dump_to_currentdump{
3984: my %hash = %{shift()};
3985: my %returnhash;
3986: # Code ripped from lond, essentially. The only difference
3987: # here is the unescaping done by lonnet::dump(). Conceivably
3988: # we might run in to problems with parameter names =~ /^v\./
3989: while (my ($key,$value) = each(%hash)) {
3990: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3991: $symb = &unescape($symb);
3992: $param = &unescape($param);
1.424 matthew 3993: next if ($v eq 'version' || $symb eq 'keys');
3994: next if (exists($returnhash{$symb}) &&
3995: exists($returnhash{$symb}->{$param}) &&
3996: $returnhash{$symb}->{'v.'.$param} > $v);
3997: $returnhash{$symb}->{$param}=$value;
3998: $returnhash{$symb}->{'v.'.$param}=$v;
3999: }
4000: #
4001: # Remove all of the keys in the hashes which keep track of
4002: # the version of the parameter.
4003: while (my ($symb,$param_hash) = each(%returnhash)) {
4004: # use a foreach because we are going to delete from the hash.
4005: foreach my $key (keys(%$param_hash)) {
4006: delete($param_hash->{$key}) if ($key =~ /^v\./);
4007: }
4008: }
4009: return \%returnhash;
1.12 www 4010: }
4011:
1.627 albertel 4012: # ------------------------------------------------------ critical inc interface
4013:
4014: sub cinc {
4015: return &inc(@_,'critical');
4016: }
4017:
1.449 matthew 4018: # --------------------------------------------------------------- inc interface
4019:
4020: sub inc {
1.627 albertel 4021: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4022: if (!$udomain) { $udomain=$env{'user.domain'}; }
4023: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4024: my $uhome=&homeserver($uname,$udomain);
4025: my $items='';
4026: if (! ref($store)) {
4027: # got a single value, so use that instead
4028: $items = &escape($store).'=&';
4029: } elsif (ref($store) eq 'SCALAR') {
4030: $items = &escape($$store).'=&';
4031: } elsif (ref($store) eq 'ARRAY') {
4032: $items = join('=&',map {&escape($_);} @{$store});
4033: } elsif (ref($store) eq 'HASH') {
4034: while (my($key,$value) = each(%{$store})) {
4035: $items.= &escape($key).'='.&escape($value).'&';
4036: }
4037: }
4038: $items=~s/\&$//;
1.627 albertel 4039: if ($critical) {
4040: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4041: } else {
4042: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4043: }
1.449 matthew 4044: }
4045:
1.12 www 4046: # --------------------------------------------------------------- put interface
4047:
4048: sub put {
1.134 albertel 4049: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4050: if (!$udomain) { $udomain=$env{'user.domain'}; }
4051: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4052: my $uhome=&homeserver($uname,$udomain);
1.12 www 4053: my $items='';
1.800 albertel 4054: foreach my $item (keys(%$storehash)) {
4055: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4056: }
1.12 www 4057: $items=~s/\&$//;
1.134 albertel 4058: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4059: }
4060:
1.631 albertel 4061: # ------------------------------------------------------------ newput interface
4062:
4063: sub newput {
4064: my ($namespace,$storehash,$udomain,$uname)=@_;
4065: if (!$udomain) { $udomain=$env{'user.domain'}; }
4066: if (!$uname) { $uname=$env{'user.name'}; }
4067: my $uhome=&homeserver($uname,$udomain);
4068: my $items='';
4069: foreach my $key (keys(%$storehash)) {
4070: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4071: }
4072: $items=~s/\&$//;
4073: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4074: }
4075:
4076: # --------------------------------------------------------- putstore interface
4077:
1.524 raeburn 4078: sub putstore {
1.715 albertel 4079: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4080: if (!$udomain) { $udomain=$env{'user.domain'}; }
4081: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4082: my $uhome=&homeserver($uname,$udomain);
4083: my $items='';
1.715 albertel 4084: foreach my $key (keys(%$storehash)) {
4085: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4086: }
1.715 albertel 4087: $items=~s/\&$//;
1.716 albertel 4088: my $esc_symb=&escape($symb);
4089: my $esc_v=&escape($version);
1.715 albertel 4090: my $reply =
1.716 albertel 4091: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4092: $uhome);
4093: if ($reply eq 'unknown_cmd') {
1.716 albertel 4094: # gfall back to way things use to be done
1.715 albertel 4095: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4096: $uname);
1.524 raeburn 4097: }
1.715 albertel 4098: return $reply;
4099: }
4100:
4101: sub old_putstore {
1.716 albertel 4102: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4103: if (!$udomain) { $udomain=$env{'user.domain'}; }
4104: if (!$uname) { $uname=$env{'user.name'}; }
4105: my $uhome=&homeserver($uname,$udomain);
4106: my %newstorehash;
1.800 albertel 4107: foreach my $item (keys(%$storehash)) {
4108: my $key = $version.':'.&escape($symb).':'.$item;
4109: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4110: }
4111: my $items='';
4112: my %allitems = ();
1.800 albertel 4113: foreach my $item (keys(%newstorehash)) {
4114: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4115: my $key = $1.':keys:'.$2;
4116: $allitems{$key} .= $3.':';
4117: }
1.800 albertel 4118: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4119: }
1.800 albertel 4120: foreach my $item (keys(%allitems)) {
4121: $allitems{$item} =~ s/\:$//;
4122: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4123: }
4124: $items=~s/\&$//;
4125: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4126: }
4127:
1.47 www 4128: # ------------------------------------------------------ critical put interface
4129:
4130: sub cput {
1.134 albertel 4131: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4132: if (!$udomain) { $udomain=$env{'user.domain'}; }
4133: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4134: my $uhome=&homeserver($uname,$udomain);
1.47 www 4135: my $items='';
1.800 albertel 4136: foreach my $item (keys(%$storehash)) {
4137: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4138: }
1.47 www 4139: $items=~s/\&$//;
1.134 albertel 4140: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4141: }
4142:
4143: # -------------------------------------------------------------- eget interface
4144:
4145: sub eget {
1.133 albertel 4146: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4147: my $items='';
1.800 albertel 4148: foreach my $item (@$storearr) {
4149: $items.=&escape($item).'&';
1.191 harris41 4150: }
1.12 www 4151: $items=~s/\&$//;
1.620 albertel 4152: if (!$udomain) { $udomain=$env{'user.domain'}; }
4153: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4154: my $uhome=&homeserver($uname,$udomain);
4155: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4156: my @pairs=split(/\&/,$rep);
4157: my %returnhash=();
1.42 www 4158: my $i=0;
1.800 albertel 4159: foreach my $item (@$storearr) {
4160: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4161: $i++;
1.191 harris41 4162: }
1.12 www 4163: return %returnhash;
4164: }
4165:
1.667 albertel 4166: # ------------------------------------------------------------ tmpput interface
4167: sub tmpput {
1.802 raeburn 4168: my ($storehash,$server,$context)=@_;
1.667 albertel 4169: my $items='';
1.800 albertel 4170: foreach my $item (keys(%$storehash)) {
4171: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4172: }
4173: $items=~s/\&$//;
1.802 raeburn 4174: if (defined($context)) {
4175: $items .= ':'.&escape($context);
4176: }
1.667 albertel 4177: return &reply("tmpput:$items",$server);
4178: }
4179:
4180: # ------------------------------------------------------------ tmpget interface
4181: sub tmpget {
1.688 albertel 4182: my ($token,$server)=@_;
4183: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4184: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4185: my %returnhash;
4186: foreach my $item (split(/\&/,$rep)) {
4187: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4188: next if ($key =~ /^error: 2 /);
1.667 albertel 4189: $returnhash{&unescape($key)}=&thaw_unescape($value);
4190: }
4191: return %returnhash;
4192: }
4193:
1.688 albertel 4194: # ------------------------------------------------------------ tmpget interface
4195: sub tmpdel {
4196: my ($token,$server)=@_;
4197: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4198: return &reply("tmpdel:$token",$server);
4199: }
4200:
1.765 albertel 4201: # -------------------------------------------------- portfolio access checking
4202:
4203: sub portfolio_access {
1.766 albertel 4204: my ($requrl) = @_;
1.765 albertel 4205: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4206: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4207: if ($result) {
4208: my %setters;
4209: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4210: my ($startblock,$endblock) =
4211: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4212: if ($startblock && $endblock) {
4213: return 'B';
4214: }
4215: } else {
4216: my ($startblock,$endblock) =
4217: &Apache::loncommon::blockcheck(\%setters,'port');
4218: if ($startblock && $endblock) {
4219: return 'B';
4220: }
4221: }
4222: }
1.765 albertel 4223: if ($result eq 'ok') {
1.766 albertel 4224: return 'F';
1.765 albertel 4225: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4226: return 'A';
1.765 albertel 4227: }
1.766 albertel 4228: return '';
1.765 albertel 4229: }
4230:
4231: sub get_portfolio_access {
1.767 albertel 4232: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4233:
4234: if (!ref($access_hash)) {
4235: my $current_perms = &get_portfile_permissions($udom,$unum);
4236: my %access_controls = &get_access_controls($current_perms,$group,
4237: $file_name);
4238: $access_hash = $access_controls{$file_name};
4239: }
4240:
1.765 albertel 4241: my ($public,$guest,@domains,@users,@courses,@groups);
4242: my $now = time;
4243: if (ref($access_hash) eq 'HASH') {
4244: foreach my $key (keys(%{$access_hash})) {
4245: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4246: if ($start > $now) {
4247: next;
4248: }
4249: if ($end && $end<$now) {
4250: next;
4251: }
4252: if ($scope eq 'public') {
4253: $public = $key;
4254: last;
4255: } elsif ($scope eq 'guest') {
4256: $guest = $key;
4257: } elsif ($scope eq 'domains') {
4258: push(@domains,$key);
4259: } elsif ($scope eq 'users') {
4260: push(@users,$key);
4261: } elsif ($scope eq 'course') {
4262: push(@courses,$key);
4263: } elsif ($scope eq 'group') {
4264: push(@groups,$key);
4265: }
4266: }
4267: if ($public) {
4268: return 'ok';
4269: }
4270: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4271: if ($guest) {
4272: return $guest;
4273: }
4274: } else {
4275: if (@domains > 0) {
4276: foreach my $domkey (@domains) {
4277: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4278: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4279: return 'ok';
4280: }
4281: }
4282: }
4283: }
4284: if (@users > 0) {
4285: foreach my $userkey (@users) {
1.865 raeburn 4286: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4287: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4288: if (ref($item) eq 'HASH') {
4289: if (($item->{'uname'} eq $env{'user.name'}) &&
4290: ($item->{'udom'} eq $env{'user.domain'})) {
4291: return 'ok';
4292: }
4293: }
4294: }
4295: }
1.765 albertel 4296: }
4297: }
4298: my %roleshash;
4299: my @courses_and_groups = @courses;
4300: push(@courses_and_groups,@groups);
4301: if (@courses_and_groups > 0) {
4302: my (%allgroups,%allroles);
4303: my ($start,$end,$role,$sec,$group);
4304: foreach my $envkey (%env) {
1.811 albertel 4305: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4306: my $cid = $2.'_'.$3;
4307: if ($1 eq 'gr') {
4308: $group = $4;
4309: $allgroups{$cid}{$group} = $env{$envkey};
4310: } else {
4311: if ($4 eq '') {
4312: $sec = 'none';
4313: } else {
4314: $sec = $4;
4315: }
4316: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4317: }
1.811 albertel 4318: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4319: my $cid = $2.'_'.$3;
4320: if ($4 eq '') {
4321: $sec = 'none';
4322: } else {
4323: $sec = $4;
4324: }
4325: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4326: }
4327: }
4328: if (keys(%allroles) == 0) {
4329: return;
4330: }
4331: foreach my $key (@courses_and_groups) {
4332: my %content = %{$$access_hash{$key}};
4333: my $cnum = $content{'number'};
4334: my $cdom = $content{'domain'};
4335: my $cid = $cdom.'_'.$cnum;
4336: if (!exists($allroles{$cid})) {
4337: next;
4338: }
4339: foreach my $role_id (keys(%{$content{'roles'}})) {
4340: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4341: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4342: my @status = @{$content{'roles'}{$role_id}{'access'}};
4343: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4344: foreach my $role (keys(%{$allroles{$cid}})) {
4345: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4346: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4347: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4348: if (grep/^all$/,@sections) {
4349: return 'ok';
4350: } else {
4351: if (grep/^$sec$/,@sections) {
4352: return 'ok';
4353: }
4354: }
4355: }
4356: }
4357: if (keys(%{$allgroups{$cid}}) == 0) {
4358: if (grep/^none$/,@groups) {
4359: return 'ok';
4360: }
4361: } else {
4362: if (grep/^all$/,@groups) {
4363: return 'ok';
4364: }
4365: foreach my $group (keys(%{$allgroups{$cid}})) {
4366: if (grep/^$group$/,@groups) {
4367: return 'ok';
4368: }
4369: }
4370: }
4371: }
4372: }
4373: }
4374: }
4375: }
4376: if ($guest) {
4377: return $guest;
4378: }
4379: }
4380: }
4381: return;
4382: }
4383:
4384: sub course_group_datechecker {
4385: my ($dates,$now,$status) = @_;
4386: my ($start,$end) = split(/\./,$dates);
4387: if (!$start && !$end) {
4388: return 'ok';
4389: }
4390: if (grep/^active$/,@{$status}) {
4391: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4392: return 'ok';
4393: }
4394: }
4395: if (grep/^previous$/,@{$status}) {
4396: if ($end > $now ) {
4397: return 'ok';
4398: }
4399: }
4400: if (grep/^future$/,@{$status}) {
4401: if ($start > $now) {
4402: return 'ok';
4403: }
4404: }
4405: return;
4406: }
4407:
4408: sub parse_portfolio_url {
4409: my ($url) = @_;
4410:
4411: my ($type,$udom,$unum,$group,$file_name);
4412:
1.823 albertel 4413: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4414: $type = 1;
4415: $udom = $1;
4416: $unum = $2;
4417: $file_name = $3;
1.823 albertel 4418: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4419: $type = 2;
4420: $udom = $1;
4421: $unum = $2;
4422: $group = $3;
4423: $file_name = $3.'/'.$4;
4424: }
4425: if (wantarray) {
4426: return ($type,$udom,$unum,$file_name,$group);
4427: }
4428: return $type;
4429: }
4430:
4431: sub is_portfolio_url {
4432: my ($url) = @_;
4433: return scalar(&parse_portfolio_url($url));
4434: }
4435:
1.798 raeburn 4436: sub is_portfolio_file {
4437: my ($file) = @_;
1.820 raeburn 4438: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4439: return 1;
4440: }
4441: return;
4442: }
4443:
1.976 raeburn 4444: sub usertools_access {
1.985 raeburn 4445: my ($uname,$udom,$tool,$action,$context) = @_;
4446: my ($access,%tools);
4447: if ($context eq '') {
4448: $context = 'tools';
4449: }
4450: if ($context eq 'requestcourses') {
4451: %tools = (
4452: official => 1,
4453: unofficial => 1,
4454: );
4455: } else {
4456: %tools = (
4457: aboutme => 1,
4458: blog => 1,
4459: portfolio => 1,
4460: );
4461: }
1.976 raeburn 4462: return if (!defined($tools{$tool}));
4463:
4464: if ((!defined($udom)) || (!defined($uname))) {
4465: $udom = $env{'user.domain'};
4466: $uname = $env{'user.name'};
4467: }
4468:
1.978 raeburn 4469: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4470: if ($action ne 'reload') {
1.985 raeburn 4471: if ($context eq 'requestcourses') {
4472: return $env{'environment.canrequest.'.$tool};
4473: } else {
4474: return $env{'environment.availabletools.'.$tool};
4475: }
4476: }
1.976 raeburn 4477: }
4478:
4479: my ($toolstatus,$inststatus);
4480:
1.985 raeburn 4481: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4482: ($action ne 'reload')) {
4483: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4484: $inststatus = $env{'environment.inststatus'};
4485: } else {
1.985 raeburn 4486: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
4487: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4488: $inststatus = $userenv{'inststatus'};
4489: }
4490:
4491: if ($toolstatus ne '') {
4492: if ($toolstatus) {
4493: $access = 1;
4494: } else {
4495: $access = 0;
4496: }
4497: return $access;
4498: }
4499:
4500: my $is_adv = &is_advanced_user($udom,$uname);
4501: my %domdef = &get_domain_defaults($udom);
4502: if (ref($domdef{$tool}) eq 'HASH') {
4503: if ($is_adv) {
4504: if ($domdef{$tool}{'_LC_adv'} ne '') {
4505: if ($domdef{$tool}{'_LC_adv'}) {
4506: $access = 1;
4507: } else {
4508: $access = 0;
4509: }
4510: return $access;
4511: }
4512: }
4513: if ($inststatus ne '') {
4514: my ($hasaccess,$hasnoaccess);
4515: foreach my $affiliation (split(/:/,$inststatus)) {
4516: if ($domdef{$tool}{$affiliation} ne '') {
4517: if ($domdef{$tool}{$affiliation}) {
4518: $hasaccess = 1;
4519: } else {
4520: $hasnoaccess = 1;
4521: }
4522: }
4523: }
4524: if ($hasaccess || $hasnoaccess) {
4525: if ($hasaccess) {
4526: $access = 1;
4527: } elsif ($hasnoaccess) {
4528: $access = 0;
4529: }
4530: return $access;
4531: }
4532: } else {
4533: if ($domdef{$tool}{'default'} ne '') {
4534: if ($domdef{$tool}{'default'}) {
4535: $access = 1;
4536: } elsif ($domdef{$tool}{'default'} == 0) {
4537: $access = 0;
4538: }
4539: return $access;
4540: }
4541: }
4542: } else {
1.985 raeburn 4543: if ($context eq 'tools') {
4544: $access = 1;
4545: } else {
4546: $access = 0;
4547: }
1.976 raeburn 4548: return $access;
4549: }
4550: }
4551:
4552: sub is_advanced_user {
4553: my ($udom,$uname) = @_;
4554: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4555: my %allroles;
4556: my $is_adv;
4557: foreach my $role (keys(%roleshash)) {
4558: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4559: my $area = '/'.$tdomain.'/'.$trest;
4560: if ($sec ne '') {
4561: $area .= '/'.$sec;
4562: }
4563: if (($area ne '') && ($trole ne '')) {
4564: my $spec=$trole.'.'.$area;
4565: if ($trole =~ /^cr\//) {
4566: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4567: } elsif ($trole ne 'gr') {
4568: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4569: }
4570: }
4571: }
4572: foreach my $role (keys(%allroles)) {
4573: last if ($is_adv);
4574: foreach my $item (split(/:/,$allroles{$role})) {
4575: if ($item ne '') {
4576: my ($privilege,$restrictions)=split(/&/,$item);
4577: if ($privilege eq 'adv') {
4578: $is_adv = 1;
4579: last;
4580: }
4581: }
4582: }
4583: }
4584: return $is_adv;
4585: }
1.798 raeburn 4586:
1.341 www 4587: # ---------------------------------------------- Custom access rule evaluation
4588:
4589: sub customaccess {
4590: my ($priv,$uri)=@_;
1.807 albertel 4591: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4592: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4593: $udom = &LONCAPA::clean_domain($udom);
4594: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4595: my $access=0;
1.800 albertel 4596: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4597: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4598: if ($type eq 'user') {
4599: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4600: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4601: if ($tdom) {
4602: if ($tdom ne $env{'user.domain'}) { next; }
4603: }
1.896 albertel 4604: if ($tuname) {
4605: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4606: }
4607: $access=($effect eq 'allow');
4608: last;
4609: }
4610: } else {
4611: if ($role) {
4612: if ($role ne $urole) { next; }
4613: }
4614: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4615: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4616: if ($tdom) {
4617: if ($tdom ne $udom) { next; }
4618: }
4619: if ($tcrs) {
4620: if ($tcrs ne $ucrs) { next; }
4621: }
4622: if ($tsec) {
4623: if ($tsec ne $usec) { next; }
4624: }
4625: $access=($effect eq 'allow');
4626: last;
4627: }
4628: if ($realm eq '' && $role eq '') {
4629: $access=($effect eq 'allow');
4630: }
1.402 bowersj2 4631: }
1.341 www 4632: }
4633: return $access;
4634: }
4635:
1.103 harris41 4636: # ------------------------------------------------- Check for a user privilege
1.12 www 4637:
4638: sub allowed {
1.810 raeburn 4639: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4640: my $ver_orguri=$uri;
1.439 www 4641: $uri=&deversion($uri);
1.152 www 4642: my $orguri=$uri;
1.52 www 4643: $uri=&declutter($uri);
1.809 raeburn 4644:
1.810 raeburn 4645: if ($priv eq 'evb') {
4646: # Evade communication block restrictions for specified role in a course
4647: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4648: return $1;
4649: } else {
4650: return;
4651: }
4652: }
4653:
1.620 albertel 4654: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4655: # Free bre access to adm and meta resources
1.775 albertel 4656: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4657: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4658: && ($priv eq 'bre')) {
1.14 www 4659: return 'F';
1.159 www 4660: }
4661:
1.545 banghart 4662: # Free bre access to user's own portfolio contents
1.714 raeburn 4663: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4664: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4665: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4666: my %setters;
4667: my ($startblock,$endblock) =
4668: &Apache::loncommon::blockcheck(\%setters,'port');
4669: if ($startblock && $endblock) {
4670: return 'B';
4671: } else {
4672: return 'F';
4673: }
1.545 banghart 4674: }
4675:
1.762 raeburn 4676: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4677: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4678: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4679: if (exists($env{'request.course.id'})) {
4680: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4681: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4682: if (($domain eq $cdom) && ($name eq $cnum)) {
4683: my $courseprivid=$env{'request.course.id'};
4684: $courseprivid=~s/\_/\//;
4685: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4686: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4687: return $1;
1.762 raeburn 4688: } else {
4689: if ($env{'request.course.sec'}) {
4690: $courseprivid.='/'.$env{'request.course.sec'};
4691: }
4692: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4693: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4694: return $2;
4695: }
1.714 raeburn 4696: }
4697: }
4698: }
4699: }
4700:
1.159 www 4701: # Free bre to public access
4702:
4703: if ($priv eq 'bre') {
1.238 www 4704: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4705: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4706: return 'F';
4707: }
1.238 www 4708: if ($copyright eq 'priv') {
4709: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4710: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4711: return '';
4712: }
4713: }
4714: if ($copyright eq 'domain') {
4715: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4716: unless (($env{'user.domain'} eq $1) ||
4717: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4718: return '';
4719: }
1.262 matthew 4720: }
1.620 albertel 4721: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4722: # Library role, so allow browsing of resources in this domain.
4723: return 'F';
1.238 www 4724: }
1.341 www 4725: if ($copyright eq 'custom') {
4726: unless (&customaccess($priv,$uri)) { return ''; }
4727: }
1.14 www 4728: }
1.264 matthew 4729: # Domain coordinator is trying to create a course
1.620 albertel 4730: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4731: # uri is the requested domain in this case.
4732: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4733: # a role of dc for the domain in question.
1.620 albertel 4734: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4735: }
1.29 www 4736:
1.52 www 4737: my $thisallowed='';
4738: my $statecond=0;
4739: my $courseprivid='';
4740:
4741: # Course
4742:
1.620 albertel 4743: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4744: $thisallowed.=$1;
4745: }
1.29 www 4746:
1.52 www 4747: # Domain
4748:
1.620 albertel 4749: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4750: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4751: $thisallowed.=$1;
4752: }
1.52 www 4753:
4754: # Course: uri itself is a course
1.66 www 4755: my $courseuri=$uri;
4756: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4757: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4758:
1.620 albertel 4759: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4760: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4761: $thisallowed.=$1;
4762: }
1.29 www 4763:
1.665 albertel 4764: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4765: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4766: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4767: $thisallowed='';
1.671 raeburn 4768: my ($match)=&is_on_map($uri);
4769: if ($match) {
4770: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4771: =~/\Q$priv\E\&([^\:]*)/) {
4772: $thisallowed.=$1;
4773: }
4774: } else {
1.705 albertel 4775: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4776: if ($refuri) {
4777: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4778: $thisallowed='F';
1.671 raeburn 4779: } else {
4780: $refuri=&declutter($refuri);
4781: my ($match) = &is_on_map($refuri);
4782: if ($match) {
4783: $thisallowed='F';
4784: }
1.669 raeburn 4785: }
1.671 raeburn 4786: }
4787: }
1.314 www 4788: }
1.492 albertel 4789:
1.766 albertel 4790: if ($priv eq 'bre'
4791: && $thisallowed ne 'F'
4792: && $thisallowed ne '2'
4793: && &is_portfolio_url($uri)) {
4794: $thisallowed = &portfolio_access($uri);
4795: }
4796:
1.52 www 4797: # Full access at system, domain or course-wide level? Exit.
1.29 www 4798: if ($thisallowed=~/F/) {
4799: return 'F';
4800: }
4801:
1.52 www 4802: # If this is generating or modifying users, exit with special codes
1.29 www 4803:
1.643 www 4804: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4805: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4806: my ($audom,$auname)=split('/',$uri);
1.643 www 4807: # no author name given, so this just checks on the general right to make a co-author in this domain
4808: unless ($auname) { return $thisallowed; }
4809: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4810: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4811: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4812: ($audom ne $env{'request.role.domain'}))) { return ''; }
4813: }
1.52 www 4814: return $thisallowed;
4815: }
4816: #
1.103 harris41 4817: # Gathered so far: system, domain and course wide privileges
1.52 www 4818: #
4819: # Course: See if uri or referer is an individual resource that is part of
4820: # the course
4821:
1.620 albertel 4822: if ($env{'request.course.id'}) {
1.232 www 4823:
1.620 albertel 4824: $courseprivid=$env{'request.course.id'};
4825: if ($env{'request.course.sec'}) {
4826: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4827: }
4828: $courseprivid=~s/\_/\//;
4829: my $checkreferer=1;
1.232 www 4830: my ($match,$cond)=&is_on_map($uri);
4831: if ($match) {
4832: $statecond=$cond;
1.620 albertel 4833: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4834: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4835: $thisallowed.=$1;
4836: $checkreferer=0;
4837: }
1.29 www 4838: }
1.83 www 4839:
1.148 www 4840: if ($checkreferer) {
1.620 albertel 4841: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4842: unless ($refuri) {
1.800 albertel 4843: foreach my $key (keys(%env)) {
4844: if ($key=~/^httpref\..*\*/) {
4845: my $pattern=$key;
1.156 www 4846: $pattern=~s/^httpref\.\/res\///;
1.148 www 4847: $pattern=~s/\*/\[\^\/\]\+/g;
4848: $pattern=~s/\//\\\//g;
1.152 www 4849: if ($orguri=~/$pattern/) {
1.800 albertel 4850: $refuri=$env{$key};
1.148 www 4851: }
4852: }
1.191 harris41 4853: }
1.148 www 4854: }
1.232 www 4855:
1.148 www 4856: if ($refuri) {
1.152 www 4857: $refuri=&declutter($refuri);
1.232 www 4858: my ($match,$cond)=&is_on_map($refuri);
4859: if ($match) {
4860: my $refstatecond=$cond;
1.620 albertel 4861: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4862: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4863: $thisallowed.=$1;
1.53 www 4864: $uri=$refuri;
4865: $statecond=$refstatecond;
1.52 www 4866: }
4867: }
1.148 www 4868: }
1.29 www 4869: }
1.52 www 4870: }
1.29 www 4871:
1.52 www 4872: #
1.103 harris41 4873: # Gathered now: all privileges that could apply, and condition number
1.52 www 4874: #
4875: #
4876: # Full or no access?
4877: #
1.29 www 4878:
1.52 www 4879: if ($thisallowed=~/F/) {
4880: return 'F';
4881: }
1.29 www 4882:
1.52 www 4883: unless ($thisallowed) {
4884: return '';
4885: }
1.29 www 4886:
1.52 www 4887: # Restrictions exist, deal with them
4888: #
4889: # C:according to course preferences
4890: # R:according to resource settings
4891: # L:unless locked
4892: # X:according to user session state
4893: #
4894:
4895: # Possibly locked functionality, check all courses
1.54 www 4896: # Locks might take effect only after 10 minutes cache expiration for other
4897: # courses, and 2 minutes for current course
1.52 www 4898:
4899: my $envkey;
4900: if ($thisallowed=~/L/) {
1.620 albertel 4901: foreach $envkey (keys %env) {
1.54 www 4902: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4903: my $courseid=$2;
4904: my $roleid=$1.'.'.$2;
1.92 www 4905: $courseid=~s/^\///;
1.54 www 4906: my $expiretime=600;
1.620 albertel 4907: if ($env{'request.role'} eq $roleid) {
1.54 www 4908: $expiretime=120;
4909: }
4910: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4911: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4912: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4913: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4914: }
1.620 albertel 4915: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4916: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4917: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4918: &log($env{'user.domain'},$env{'user.name'},
4919: $env{'user.home'},
1.57 www 4920: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4921: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4922: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4923: return '';
4924: }
4925: }
1.620 albertel 4926: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4927: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4928: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4929: &log($env{'user.domain'},$env{'user.name'},
4930: $env{'user.home'},
1.57 www 4931: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4932: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4933: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4934: return '';
4935: }
4936: }
4937: }
1.29 www 4938: }
1.52 www 4939: }
4940:
4941: #
4942: # Rest of the restrictions depend on selected course
4943: #
4944:
1.620 albertel 4945: unless ($env{'request.course.id'}) {
1.766 albertel 4946: if ($thisallowed eq 'A') {
4947: return 'A';
1.814 raeburn 4948: } elsif ($thisallowed eq 'B') {
4949: return 'B';
1.766 albertel 4950: } else {
4951: return '1';
4952: }
1.52 www 4953: }
1.29 www 4954:
1.52 www 4955: #
4956: # Now user is definitely in a course
4957: #
1.53 www 4958:
4959:
4960: # Course preferences
4961:
4962: if ($thisallowed=~/C/) {
1.620 albertel 4963: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4964: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4965: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4966: =~/\Q$rolecode\E/) {
1.689 albertel 4967: if ($priv ne 'pch') {
4968: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4969: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4970: $env{'request.course.id'});
4971: }
1.237 www 4972: return '';
4973: }
4974:
1.620 albertel 4975: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4976: =~/\Q$unamedom\E/) {
1.689 albertel 4977: if ($priv ne 'pch') {
4978: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4979: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4980: $env{'request.course.id'});
4981: }
1.54 www 4982: return '';
4983: }
1.53 www 4984: }
4985:
4986: # Resource preferences
4987:
4988: if ($thisallowed=~/R/) {
1.620 albertel 4989: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4990: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4991: if ($priv ne 'pch') {
4992: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4993: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4994: }
4995: return '';
1.54 www 4996: }
1.53 www 4997: }
1.30 www 4998:
1.246 www 4999: # Restricted by state or randomout?
1.30 www 5000:
1.52 www 5001: if ($thisallowed=~/X/) {
1.620 albertel 5002: if ($env{'acc.randomout'}) {
1.579 albertel 5003: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5004: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5005: return '';
5006: }
1.247 www 5007: }
5008: if (&condval($statecond)) {
1.52 www 5009: return '2';
5010: } else {
5011: return '';
5012: }
5013: }
1.30 www 5014:
1.766 albertel 5015: if ($thisallowed eq 'A') {
5016: return 'A';
1.814 raeburn 5017: } elsif ($thisallowed eq 'B') {
5018: return 'B';
1.766 albertel 5019: }
1.52 www 5020: return 'F';
1.232 www 5021: }
5022:
1.710 albertel 5023: sub split_uri_for_cond {
5024: my $uri=&deversion(&declutter(shift));
5025: my @uriparts=split(/\//,$uri);
5026: my $filename=pop(@uriparts);
5027: my $pathname=join('/',@uriparts);
5028: return ($pathname,$filename);
5029: }
1.232 www 5030: # --------------------------------------------------- Is a resource on the map?
5031:
5032: sub is_on_map {
1.710 albertel 5033: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5034: #Trying to find the conditional for the file
1.620 albertel 5035: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5036: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5037: if ($match) {
1.289 bowersj2 5038: return (1,$1);
5039: } else {
1.434 www 5040: return (0,0);
1.289 bowersj2 5041: }
1.12 www 5042: }
5043:
1.427 www 5044: # --------------------------------------------------------- Get symb from alias
5045:
5046: sub get_symb_from_alias {
5047: my $symb=shift;
5048: my ($map,$resid,$url)=&decode_symb($symb);
5049: # Already is a symb
5050: if ($url) { return $symb; }
5051: # Must be an alias
5052: my $aliassymb='';
5053: my %bighash;
1.620 albertel 5054: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5055: &GDBM_READER(),0640)) {
5056: my $rid=$bighash{'mapalias_'.$symb};
5057: if ($rid) {
5058: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5059: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5060: $resid,$bighash{'src_'.$rid});
1.427 www 5061: }
5062: untie %bighash;
5063: }
5064: return $aliassymb;
5065: }
5066:
1.12 www 5067: # ----------------------------------------------------------------- Define Role
5068:
5069: sub definerole {
5070: if (allowed('mcr','/')) {
5071: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5072: foreach my $role (split(':',$sysrole)) {
5073: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5074: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5075: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5076: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5077: return "refused:s:$crole&$cqual";
5078: }
5079: }
1.191 harris41 5080: }
1.800 albertel 5081: foreach my $role (split(':',$domrole)) {
5082: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5083: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5084: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5085: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5086: return "refused:d:$crole&$cqual";
5087: }
5088: }
1.191 harris41 5089: }
1.800 albertel 5090: foreach my $role (split(':',$courole)) {
5091: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5092: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5093: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5094: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5095: return "refused:c:$crole&$cqual";
5096: }
5097: }
1.191 harris41 5098: }
1.620 albertel 5099: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5100: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5101: "rolesdef_$rolename=".
5102: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5103: return reply($command,$env{'user.home'});
1.12 www 5104: } else {
5105: return 'refused';
5106: }
1.105 harris41 5107: }
5108:
5109: # ---------------- Make a metadata query against the network of library servers
5110:
5111: sub metadata_query {
1.244 matthew 5112: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5113: my %rhash;
1.845 albertel 5114: my %libserv = &all_library();
1.244 matthew 5115: my @server_list = (defined($server_array) ? @$server_array
5116: : keys(%libserv) );
5117: for my $server (@server_list) {
1.118 harris41 5118: unless ($custom or $customshow) {
5119: my $reply=&reply("querysend:".&escape($query),$server);
5120: $rhash{$server}=$reply;
5121: }
5122: else {
5123: my $reply=&reply("querysend:".&escape($query).':'.
5124: &escape($custom).':'.&escape($customshow),
5125: $server);
5126: $rhash{$server}=$reply;
5127: }
1.112 harris41 5128: }
1.118 harris41 5129: return \%rhash;
1.240 www 5130: }
5131:
5132: # ----------------------------------------- Send log queries and wait for reply
5133:
5134: sub log_query {
5135: my ($uname,$udom,$query,%filters)=@_;
5136: my $uhome=&homeserver($uname,$udom);
5137: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5138: my $uhost=&hostname($uhome);
1.800 albertel 5139: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5140: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5141: $uhome);
1.479 albertel 5142: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5143: return get_query_reply($queryid);
5144: }
5145:
1.818 raeburn 5146: # -------------------------- Update MySQL table for portfolio file
5147:
5148: sub update_portfolio_table {
1.821 raeburn 5149: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5150: if ($group ne '') {
5151: $file_name =~s /^\Q$group\E//;
5152: }
1.818 raeburn 5153: my $homeserver = &homeserver($uname,$udom);
5154: my $queryid=
1.821 raeburn 5155: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5156: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5157: my $reply = &get_query_reply($queryid);
5158: return $reply;
5159: }
5160:
1.899 raeburn 5161: # -------------------------- Update MySQL allusers table
5162:
5163: sub update_allusers_table {
5164: my ($uname,$udom,$names) = @_;
5165: my $homeserver = &homeserver($uname,$udom);
5166: my $queryid=
5167: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5168: 'lastname='.&escape($names->{'lastname'}).'%%'.
5169: 'firstname='.&escape($names->{'firstname'}).'%%'.
5170: 'middlename='.&escape($names->{'middlename'}).'%%'.
5171: 'generation='.&escape($names->{'generation'}).'%%'.
5172: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5173: 'id='.&escape($names->{'id'}),$homeserver);
5174: my $reply = &get_query_reply($queryid);
5175: return $reply;
5176: }
5177:
1.508 raeburn 5178: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5179:
5180: sub fetch_enrollment_query {
1.511 raeburn 5181: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5182: my $homeserver;
1.547 raeburn 5183: my $maxtries = 1;
1.508 raeburn 5184: if ($context eq 'automated') {
5185: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5186: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5187: } else {
5188: $homeserver = &homeserver($cnum,$dom);
5189: }
1.838 albertel 5190: my $host=&hostname($homeserver);
1.506 raeburn 5191: my $cmd = '';
1.800 albertel 5192: foreach my $affiliate (keys %{$affiliatesref}) {
5193: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5194: }
5195: $cmd =~ s/%%$//;
5196: $cmd = &escape($cmd);
5197: my $query = 'fetchenrollment';
1.620 albertel 5198: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5199: unless ($queryid=~/^\Q$host\E\_/) {
5200: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5201: return 'error: '.$queryid;
5202: }
1.506 raeburn 5203: my $reply = &get_query_reply($queryid);
1.547 raeburn 5204: my $tries = 1;
5205: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5206: $reply = &get_query_reply($queryid);
5207: $tries ++;
5208: }
1.526 raeburn 5209: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5210: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5211: } else {
1.901 albertel 5212: my @responses = split(/:/,$reply);
1.515 raeburn 5213: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5214: foreach my $line (@responses) {
5215: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5216: $$replyref{$key} = $value;
5217: }
5218: } else {
1.506 raeburn 5219: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5220: foreach my $line (@responses) {
5221: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5222: $$replyref{$key} = $value;
5223: if ($value > 0) {
1.800 albertel 5224: foreach my $item (@{$$affiliatesref{$key}}) {
5225: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5226: my $destname = $pathname.'/'.$filename;
5227: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5228: if ($xml_classlist =~ /^error/) {
5229: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5230: } else {
1.506 raeburn 5231: if ( open(FILE,">$destname") ) {
5232: print FILE &unescape($xml_classlist);
5233: close(FILE);
1.526 raeburn 5234: } else {
5235: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5236: }
5237: }
5238: }
5239: }
5240: }
5241: }
5242: return 'ok';
5243: }
5244: return 'error';
5245: }
5246:
1.242 www 5247: sub get_query_reply {
5248: my $queryid=shift;
1.240 www 5249: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5250: my $reply='';
5251: for (1..100) {
5252: sleep 2;
5253: if (-e $replyfile.'.end') {
1.448 albertel 5254: if (open(my $fh,$replyfile)) {
1.904 albertel 5255: $reply = join('',<$fh>);
5256: close($fh);
1.240 www 5257: } else { return 'error: reply_file_error'; }
1.242 www 5258: return &unescape($reply);
5259: }
1.240 www 5260: }
1.242 www 5261: return 'timeout:'.$queryid;
1.240 www 5262: }
5263:
5264: sub courselog_query {
1.241 www 5265: #
5266: # possible filters:
5267: # url: url or symb
5268: # username
5269: # domain
5270: # action: view, submit, grade
5271: # start: timestamp
5272: # end: timestamp
5273: #
1.240 www 5274: my (%filters)=@_;
1.620 albertel 5275: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5276: if ($filters{'url'}) {
5277: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5278: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5279: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5280: }
1.620 albertel 5281: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5282: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5283: return &log_query($cname,$cdom,'courselog',%filters);
5284: }
5285:
5286: sub userlog_query {
1.858 raeburn 5287: #
5288: # possible filters:
5289: # action: log check role
5290: # start: timestamp
5291: # end: timestamp
5292: #
1.240 www 5293: my ($uname,$udom,%filters)=@_;
5294: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5295: }
5296:
1.506 raeburn 5297: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5298:
5299: sub auto_run {
1.508 raeburn 5300: my ($cnum,$cdom) = @_;
1.876 raeburn 5301: my $response = 0;
5302: my $settings;
5303: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5304: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5305: $settings = $domconfig{'autoenroll'};
5306: if ($settings->{'run'} eq '1') {
5307: $response = 1;
5308: }
5309: } else {
1.934 raeburn 5310: my $homeserver;
5311: if (&is_course($cdom,$cnum)) {
5312: $homeserver = &homeserver($cnum,$cdom);
5313: } else {
5314: $homeserver = &domain($cdom,'primary');
5315: }
5316: if ($homeserver ne 'no_host') {
5317: $response = &reply('autorun:'.$cdom,$homeserver);
5318: }
1.876 raeburn 5319: }
1.506 raeburn 5320: return $response;
5321: }
1.776 albertel 5322:
1.506 raeburn 5323: sub auto_get_sections {
1.508 raeburn 5324: my ($cnum,$cdom,$inst_coursecode) = @_;
5325: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 5326: my @secs = ();
1.511 raeburn 5327: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 5328: unless ($response eq 'refused') {
1.901 albertel 5329: @secs = split(/:/,$response);
1.506 raeburn 5330: }
5331: return @secs;
5332: }
1.776 albertel 5333:
1.506 raeburn 5334: sub auto_new_course {
1.508 raeburn 5335: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5336: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5337: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5338: return $response;
5339: }
1.776 albertel 5340:
1.506 raeburn 5341: sub auto_validate_courseID {
1.508 raeburn 5342: my ($cnum,$cdom,$inst_course_id) = @_;
5343: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5344: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5345: return $response;
5346: }
1.776 albertel 5347:
1.506 raeburn 5348: sub auto_create_password {
1.873 raeburn 5349: my ($cnum,$cdom,$authparam,$udom) = @_;
5350: my ($homeserver,$response);
1.506 raeburn 5351: my $create_passwd = 0;
5352: my $authchk = '';
1.873 raeburn 5353: if ($udom =~ /^$match_domain$/) {
5354: $homeserver = &domain($udom,'primary');
5355: }
5356: if ($homeserver eq '') {
5357: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5358: $homeserver = &homeserver($cnum,$cdom);
5359: }
5360: }
5361: if ($homeserver eq '') {
5362: $authchk = 'nodomain';
1.506 raeburn 5363: } else {
1.873 raeburn 5364: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5365: if ($response eq 'refused') {
5366: $authchk = 'refused';
5367: } else {
1.901 albertel 5368: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5369: }
1.506 raeburn 5370: }
5371: return ($authparam,$create_passwd,$authchk);
5372: }
5373:
1.706 raeburn 5374: sub auto_photo_permission {
5375: my ($cnum,$cdom,$students) = @_;
5376: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5377: my ($outcome,$perm_reqd,$conditions) =
5378: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5379: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5380: return (undef,undef);
5381: }
1.706 raeburn 5382: return ($outcome,$perm_reqd,$conditions);
5383: }
5384:
5385: sub auto_checkphotos {
5386: my ($uname,$udom,$pid) = @_;
5387: my $homeserver = &homeserver($uname,$udom);
5388: my ($result,$resulttype);
5389: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5390: &escape($uname).':'.&escape($pid),
5391: $homeserver));
1.709 albertel 5392: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5393: return (undef,undef);
5394: }
1.706 raeburn 5395: if ($outcome) {
5396: ($result,$resulttype) = split(/:/,$outcome);
5397: }
5398: return ($result,$resulttype);
5399: }
5400:
5401: sub auto_photochoice {
5402: my ($cnum,$cdom) = @_;
5403: my $homeserver = &homeserver($cnum,$cdom);
5404: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5405: &escape($cdom),
5406: $homeserver)));
1.709 albertel 5407: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5408: return (undef,undef);
5409: }
1.706 raeburn 5410: return ($update,$comment);
5411: }
5412:
5413: sub auto_photoupdate {
5414: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5415: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5416: my $host=&hostname($homeserver);
1.706 raeburn 5417: my $cmd = '';
5418: my $maxtries = 1;
1.800 albertel 5419: foreach my $affiliate (keys(%{$affiliatesref})) {
5420: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5421: }
5422: $cmd =~ s/%%$//;
5423: $cmd = &escape($cmd);
5424: my $query = 'institutionalphotos';
5425: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5426: unless ($queryid=~/^\Q$host\E\_/) {
5427: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5428: return 'error: '.$queryid;
5429: }
5430: my $reply = &get_query_reply($queryid);
5431: my $tries = 1;
5432: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5433: $reply = &get_query_reply($queryid);
5434: $tries ++;
5435: }
5436: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5437: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5438: } else {
5439: my @responses = split(/:/,$reply);
5440: my $outcome = shift(@responses);
5441: foreach my $item (@responses) {
5442: my ($key,$value) = split(/=/,$item);
5443: $$photo{$key} = $value;
5444: }
5445: return $outcome;
5446: }
5447: return 'error';
5448: }
5449:
1.521 raeburn 5450: sub auto_instcode_format {
1.793 albertel 5451: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5452: $cat_order) = @_;
1.521 raeburn 5453: my $courses = '';
1.772 raeburn 5454: my @homeservers;
1.521 raeburn 5455: if ($caller eq 'global') {
1.841 albertel 5456: my %servers = &get_servers($codedom,'library');
5457: foreach my $tryserver (keys(%servers)) {
5458: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5459: push(@homeservers,$tryserver);
5460: }
1.584 raeburn 5461: }
1.521 raeburn 5462: } else {
1.772 raeburn 5463: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5464: }
1.793 albertel 5465: foreach my $code (keys(%{$instcodes})) {
5466: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5467: }
5468: chop($courses);
1.772 raeburn 5469: my $ok_response = 0;
5470: my $response;
5471: while (@homeservers > 0 && $ok_response == 0) {
5472: my $server = shift(@homeservers);
5473: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5474: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5475: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5476: split(/:/,$response);
1.772 raeburn 5477: %{$codes} = (%{$codes},&str2hash($codes_str));
5478: push(@{$codetitles},&str2array($codetitles_str));
5479: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5480: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5481: $ok_response = 1;
5482: }
5483: }
5484: if ($ok_response) {
1.521 raeburn 5485: return 'ok';
1.772 raeburn 5486: } else {
5487: return $response;
1.521 raeburn 5488: }
5489: }
5490:
1.792 raeburn 5491: sub auto_instcode_defaults {
5492: my ($domain,$returnhash,$code_order) = @_;
5493: my @homeservers;
1.841 albertel 5494:
5495: my %servers = &get_servers($domain,'library');
5496: foreach my $tryserver (keys(%servers)) {
5497: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5498: push(@homeservers,$tryserver);
5499: }
1.792 raeburn 5500: }
1.841 albertel 5501:
1.792 raeburn 5502: my $response;
1.841 albertel 5503: foreach my $server (@homeservers) {
1.792 raeburn 5504: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5505: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5506:
5507: foreach my $pair (split(/\&/,$response)) {
5508: my ($name,$value)=split(/\=/,$pair);
5509: if ($name eq 'code_order') {
5510: @{$code_order} = split(/\&/,&unescape($value));
5511: } else {
5512: $returnhash->{&unescape($name)}=&unescape($value);
5513: }
5514: }
5515: return 'ok';
1.792 raeburn 5516: }
1.841 albertel 5517:
5518: return $response;
1.792 raeburn 5519: }
5520:
1.777 albertel 5521: sub auto_validate_class_sec {
1.918 raeburn 5522: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5523: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5524: my $ownerlist;
5525: if (ref($owners) eq 'ARRAY') {
5526: $ownerlist = join(',',@{$owners});
5527: } else {
5528: $ownerlist = $owners;
5529: }
1.773 raeburn 5530: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5531: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5532: return $response;
5533: }
5534:
1.679 raeburn 5535: # ------------------------------------------------------- Course Group routines
5536:
5537: sub get_coursegroups {
1.809 raeburn 5538: my ($cdom,$cnum,$group,$namespace) = @_;
5539: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5540: }
5541:
1.679 raeburn 5542: sub modify_coursegroup {
5543: my ($cdom,$cnum,$groupsettings) = @_;
5544: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5545: }
5546:
1.809 raeburn 5547: sub toggle_coursegroup_status {
5548: my ($cdom,$cnum,$group,$action) = @_;
5549: my ($from_namespace,$to_namespace);
5550: if ($action eq 'delete') {
5551: $from_namespace = 'coursegroups';
5552: $to_namespace = 'deleted_groups';
5553: } else {
5554: $from_namespace = 'deleted_groups';
5555: $to_namespace = 'coursegroups';
5556: }
5557: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5558: if (my $tmp = &error(%curr_group)) {
5559: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5560: return ('read error',$tmp);
5561: } else {
5562: my %savedsettings = %curr_group;
1.809 raeburn 5563: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5564: my $deloutcome;
5565: if ($result eq 'ok') {
1.809 raeburn 5566: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5567: } else {
5568: return ('write error',$result);
5569: }
5570: if ($deloutcome eq 'ok') {
5571: return 'ok';
5572: } else {
5573: return ('delete error',$deloutcome);
5574: }
5575: }
5576: }
5577:
1.679 raeburn 5578: sub modify_group_roles {
1.957 raeburn 5579: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 5580: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5581: my $role = 'gr/'.&escape($userprivs);
5582: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 5583: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 5584: if ($result eq 'ok') {
5585: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5586: }
1.679 raeburn 5587: return $result;
5588: }
5589:
5590: sub modify_coursegroup_membership {
5591: my ($cdom,$cnum,$membership) = @_;
5592: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5593: return $result;
5594: }
5595:
1.682 raeburn 5596: sub get_active_groups {
5597: my ($udom,$uname,$cdom,$cnum) = @_;
5598: my $now = time;
5599: my %groups = ();
5600: foreach my $key (keys(%env)) {
1.811 albertel 5601: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5602: my ($start,$end) = split(/\./,$env{$key});
5603: if (($end!=0) && ($end<$now)) { next; }
5604: if (($start!=0) && ($start>$now)) { next; }
5605: if ($1 eq $cdom && $2 eq $cnum) {
5606: $groups{$3} = $env{$key} ;
5607: }
5608: }
5609: }
5610: return %groups;
5611: }
5612:
1.683 raeburn 5613: sub get_group_membership {
5614: my ($cdom,$cnum,$group) = @_;
5615: return(&dump('groupmembership',$cdom,$cnum,$group));
5616: }
5617:
5618: sub get_users_groups {
5619: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5620: my @usersgroups;
1.683 raeburn 5621: my $cachetime=1800;
5622:
5623: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5624: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5625: if (defined($cached)) {
1.734 albertel 5626: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5627: } else {
5628: $grouplist = '';
1.816 raeburn 5629: my $courseurl = &courseid_to_courseurl($courseid);
5630: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5631: my $access_end = $env{'course.'.$courseid.
5632: '.default_enrollment_end_date'};
5633: my $now = time;
5634: foreach my $key (keys(%roleshash)) {
5635: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5636: my $group = $1;
5637: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5638: my $start = $2;
5639: my $end = $1;
5640: if ($start == -1) { next; } # deleted from group
5641: if (($start!=0) && ($start>$now)) { next; }
5642: if (($end!=0) && ($end<$now)) {
5643: if ($access_end && $access_end < $now) {
5644: if ($access_end - $end < 86400) {
5645: push(@usersgroups,$group);
1.733 raeburn 5646: }
5647: }
1.817 raeburn 5648: next;
1.733 raeburn 5649: }
1.817 raeburn 5650: push(@usersgroups,$group);
1.683 raeburn 5651: }
5652: }
5653: }
1.817 raeburn 5654: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5655: $grouplist = join(':',@usersgroups);
5656: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5657: }
1.733 raeburn 5658: return @usersgroups;
1.683 raeburn 5659: }
5660:
5661: sub devalidate_getgroups_cache {
5662: my ($udom,$uname,$cdom,$cnum)=@_;
5663: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5664:
1.683 raeburn 5665: my $hashid="$udom:$uname:$courseid";
5666: &devalidate_cache_new('getgroups',$hashid);
5667: }
5668:
1.12 www 5669: # ------------------------------------------------------------------ Plain Text
5670:
5671: sub plaintext {
1.988 ! raeburn 5672: my ($short,$type,$cid,$forcedefault) = @_;
1.758 albertel 5673: if ($short =~ /^cr/) {
5674: return (split('/',$short))[-1];
5675: }
1.742 raeburn 5676: if (!defined($cid)) {
5677: $cid = $env{'request.course.id'};
5678: }
1.988 ! raeburn 5679: if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
! 5680: unless ($forcedefault) {
! 5681: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
! 5682: &Apache::lonlocal::mt_escape(\$roletext);
! 5683: return &Apache::lonlocal::mt($roletext);
! 5684: }
1.742 raeburn 5685: }
5686: my %rolenames = (
5687: Course => 'std',
5688: Group => 'alt1',
5689: );
5690: if (defined($type) &&
5691: defined($rolenames{$type}) &&
5692: defined($prp{$short}{$rolenames{$type}})) {
5693: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5694: } else {
5695: return &Apache::lonlocal::mt($prp{$short}{'std'});
5696: }
1.12 www 5697: }
5698:
5699: # ----------------------------------------------------------------- Assign Role
5700:
5701: sub assignrole {
1.957 raeburn 5702: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
5703: $context)=@_;
1.21 www 5704: my $mrole;
5705: if ($role =~ /^cr\//) {
1.393 www 5706: my $cwosec=$url;
1.811 albertel 5707: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5708: unless (&allowed('ccr',$cwosec)) {
1.104 www 5709: &logthis('Refused custom assignrole: '.
5710: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5711: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5712: return 'refused';
5713: }
1.21 www 5714: $mrole='cr';
1.678 raeburn 5715: } elsif ($role =~ /^gr\//) {
5716: my $cwogrp=$url;
1.811 albertel 5717: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5718: unless (&allowed('mdg',$cwogrp)) {
5719: &logthis('Refused group assignrole: '.
5720: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5721: $env{'user.name'}.' at '.$env{'user.domain'});
5722: return 'refused';
5723: }
5724: $mrole='gr';
1.21 www 5725: } else {
1.82 www 5726: my $cwosec=$url;
1.811 albertel 5727: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 5728: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
5729: my $refused;
5730: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
5731: if (!(&allowed('c'.$role,$url))) {
5732: $refused = 1;
5733: }
5734: } else {
5735: $refused = 1;
5736: }
1.947 raeburn 5737: if ($refused) {
5738: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5739: $refused = '';
5740: } else {
5741: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
5742: ' '.$role.' '.$end.' '.$start.' by '.
5743: $env{'user.name'}.' at '.$env{'user.domain'});
5744: return 'refused';
5745: }
1.932 raeburn 5746: }
1.104 www 5747: }
1.21 www 5748: $mrole=$role;
5749: }
1.620 albertel 5750: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5751: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 5752: if ($end) { $command.='_'.$end; }
1.21 www 5753: if ($start) {
5754: if ($end) {
1.81 www 5755: $command.='_'.$start;
1.21 www 5756: } else {
1.81 www 5757: $command.='_0_'.$start;
1.21 www 5758: }
5759: }
1.739 raeburn 5760: my $origstart = $start;
5761: my $origend = $end;
1.957 raeburn 5762: my $delflag;
1.357 www 5763: # actually delete
5764: if ($deleteflag) {
1.373 www 5765: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 5766: # modify command to delete the role
1.620 albertel 5767: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 5768: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 5769: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 5770: # set start and finish to negative values for userrolelog
5771: $start=-1;
5772: $end=-1;
1.957 raeburn 5773: $delflag = 1;
1.357 www 5774: }
5775: }
5776: # send command
1.349 www 5777: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 5778: # log new user role if status is ok
1.349 www 5779: if ($answer eq 'ok') {
1.663 raeburn 5780: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 5781: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 5782: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 5783: unless ($role =~ /^gr/) {
5784: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 5785: $origstart,$selfenroll,$context);
1.739 raeburn 5786: }
1.349 www 5787: }
5788: return $answer;
1.169 harris41 5789: }
5790:
5791: # -------------------------------------------------- Modify user authentication
1.197 www 5792: # Overrides without validation
5793:
1.169 harris41 5794: sub modifyuserauth {
5795: my ($udom,$uname,$umode,$upass)=@_;
5796: my $uhome=&homeserver($uname,$udom);
1.197 www 5797: unless (&allowed('mau',$udom)) { return 'refused'; }
5798: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 5799: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5800: ' in domain '.$env{'request.role.domain'});
1.169 harris41 5801: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5802: &escape($upass),$uhome);
1.620 albertel 5803: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 5804: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5805: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5806: &log($udom,,$uname,$uhome,
1.620 albertel 5807: 'Authentication changed by '.$env{'user.domain'}.', '.
5808: $env{'user.name'}.', '.$umode.
1.197 www 5809: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 5810: unless ($reply eq 'ok') {
1.197 www 5811: &logthis('Authentication mode error: '.$reply);
1.169 harris41 5812: return 'error: '.$reply;
5813: }
1.170 harris41 5814: return 'ok';
1.80 www 5815: }
5816:
1.81 www 5817: # --------------------------------------------------------------- Modify a user
1.80 www 5818:
1.81 www 5819: sub modifyuser {
1.206 matthew 5820: my ($udom, $uname, $uid,
5821: $umode, $upass, $first,
5822: $middle, $last, $gene,
1.963 raeburn 5823: $forceid, $desiredhome, $email, $inststatus)=@_;
1.807 albertel 5824: $udom= &LONCAPA::clean_domain($udom);
5825: $uname=&LONCAPA::clean_username($uname);
1.81 www 5826: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5827: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 5828: $last.', '.$gene.'(forceid: '.$forceid.')'.
5829: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5830: ' desiredhome not specified').
1.620 albertel 5831: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5832: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 5833: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 5834: # ----------------------------------------------------------------- Create User
1.406 albertel 5835: if (($uhome eq 'no_host') &&
5836: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 5837: my $unhome='';
1.844 albertel 5838: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 5839: $unhome = $desiredhome;
1.620 albertel 5840: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5841: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 5842: } else { # load balancing routine for determining $unhome
1.81 www 5843: my $loadm=10000000;
1.841 albertel 5844: my %servers = &get_servers($udom,'library');
5845: foreach my $tryserver (keys(%servers)) {
5846: my $answer=reply('load',$tryserver);
5847: if (($answer=~/\d+/) && ($answer<$loadm)) {
5848: $loadm=$answer;
5849: $unhome=$tryserver;
5850: }
1.80 www 5851: }
5852: }
5853: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 5854: return 'error: unable to find a home server for '.$uname.
5855: ' in domain '.$udom;
1.80 www 5856: }
5857: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
5858: &escape($upass),$unhome);
5859: unless ($reply eq 'ok') {
5860: return 'error: '.$reply;
5861: }
1.230 stredwic 5862: $uhome=&homeserver($uname,$udom,'true');
1.80 www 5863: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 5864: return 'error: unable verify users home machine.';
1.80 www 5865: }
1.209 matthew 5866: } # End of creation of new user
1.80 www 5867: # ---------------------------------------------------------------------- Add ID
5868: if ($uid) {
5869: $uid=~tr/A-Z/a-z/;
5870: my %uidhash=&idrget($udom,$uname);
1.196 www 5871: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
5872: && (!$forceid)) {
1.80 www 5873: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 5874: return 'error: user id "'.$uid.'" does not match '.
5875: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 5876: }
5877: } else {
5878: &idput($udom,($uname => $uid));
5879: }
5880: }
5881: # -------------------------------------------------------------- Add names, etc
1.313 matthew 5882: my @tmp=&get('environment',
1.899 raeburn 5883: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 5884: 'permanentemail','inststatus'],
1.134 albertel 5885: $udom,$uname);
1.313 matthew 5886: my %names;
5887: if ($tmp[0] =~ m/^error:.*/) {
5888: %names=();
5889: } else {
5890: %names = @tmp;
5891: }
1.388 www 5892: #
5893: # Make sure to not trash student environment if instructor does not bother
5894: # to supply name and email information
5895: #
5896: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 5897: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 5898: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 5899: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 5900: if ($email) {
5901: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 5902: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 5903: }
1.899 raeburn 5904: if ($uid) { $names{'id'} = $uid; }
1.963 raeburn 5905: if (defined($inststatus)) { $names{'inststatus'} = $inststatus; }
1.134 albertel 5906: my $reply = &put('environment', \%names, $udom,$uname);
5907: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 5908: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 5909: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 5910: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
5911: $umode.', '.$first.', '.$middle.', '.
5912: $last.', '.$gene.', '.$email.', '.$inststatus;
5913: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
5914: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
5915: } else {
5916: $logmsg .= ' during self creation';
5917: }
5918: &logthis($logmsg);
1.134 albertel 5919: return 'ok';
1.80 www 5920: }
5921:
1.81 www 5922: # -------------------------------------------------------------- Modify student
1.80 www 5923:
1.81 www 5924: sub modifystudent {
5925: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 5926: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
5927: $selfenroll,$context)=@_;
1.455 albertel 5928: if (!$cid) {
1.620 albertel 5929: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5930: return 'not_in_class';
5931: }
1.80 www 5932: }
5933: # --------------------------------------------------------------- Make the user
1.81 www 5934: my $reply=&modifyuser
1.209 matthew 5935: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5936: $desiredhome,$email);
1.80 www 5937: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5938: # This will cause &modify_student_enrollment to get the uid from the
5939: # students environment
5940: $uid = undef if (!$forceid);
1.455 albertel 5941: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 5942: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 5943: return $reply;
5944: }
5945:
5946: sub modify_student_enrollment {
1.957 raeburn 5947: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 5948: my ($cdom,$cnum,$chome);
5949: if (!$cid) {
1.620 albertel 5950: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5951: return 'not_in_class';
5952: }
1.620 albertel 5953: $cdom=$env{'course.'.$cid.'.domain'};
5954: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5955: } else {
5956: ($cdom,$cnum)=split(/_/,$cid);
5957: }
1.620 albertel 5958: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5959: if (!$chome) {
1.457 raeburn 5960: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5961: }
1.455 albertel 5962: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5963: # Make sure the user exists
1.81 www 5964: my $uhome=&homeserver($uname,$udom);
5965: if (($uhome eq '') || ($uhome eq 'no_host')) {
5966: return 'error: no such user';
5967: }
1.297 matthew 5968: # Get student data if we were not given enough information
5969: if (!defined($first) || $first eq '' ||
5970: !defined($last) || $last eq '' ||
5971: !defined($uid) || $uid eq '' ||
5972: !defined($middle) || $middle eq '' ||
5973: !defined($gene) || $gene eq '') {
1.294 matthew 5974: # They did not supply us with enough data to enroll the student, so
5975: # we need to pick up more information.
1.297 matthew 5976: my %tmp = &get('environment',
1.294 matthew 5977: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5978: ,$udom,$uname);
5979:
1.800 albertel 5980: #foreach my $key (keys(%tmp)) {
5981: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5982: #}
1.294 matthew 5983: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5984: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5985: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5986: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5987: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5988: }
1.556 albertel 5989: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5990: my $reply=cput('classlist',
5991: {"$uname:$udom" =>
1.515 raeburn 5992: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5993: $cdom,$cnum);
1.81 www 5994: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5995: return 'error: '.$reply;
1.652 albertel 5996: } else {
5997: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5998: }
1.297 matthew 5999: # Add student role to user
1.83 www 6000: my $uurl='/'.$cid;
1.81 www 6001: $uurl=~s/\_/\//g;
6002: if ($usec) {
6003: $uurl.='/'.$usec;
6004: }
1.957 raeburn 6005: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6006: }
6007:
1.556 albertel 6008: sub format_name {
6009: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6010: my $name;
6011: if ($first ne 'lastname') {
6012: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6013: } else {
6014: if ($lastname=~/\S/) {
6015: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6016: $name=~s/\s+,/,/;
6017: } else {
6018: $name.= $firstname.' '.$middlename.' '.$generation;
6019: }
6020: }
6021: $name=~s/^\s+//;
6022: $name=~s/\s+$//;
6023: $name=~s/\s+/ /g;
6024: return $name;
6025: }
6026:
1.84 www 6027: # ------------------------------------------------- Write to course preferences
6028:
6029: sub writecoursepref {
6030: my ($courseid,%prefs)=@_;
6031: $courseid=~s/^\///;
6032: $courseid=~s/\_/\//g;
6033: my ($cdomain,$cnum)=split(/\//,$courseid);
6034: my $chome=homeserver($cnum,$cdomain);
6035: if (($chome eq '') || ($chome eq 'no_host')) {
6036: return 'error: no such course';
6037: }
6038: my $cstring='';
1.800 albertel 6039: foreach my $pref (keys(%prefs)) {
6040: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6041: }
1.84 www 6042: $cstring=~s/\&$//;
6043: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6044: }
6045:
6046: # ---------------------------------------------------------- Make/modify course
6047:
6048: sub createcourse {
1.741 raeburn 6049: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
6050: $course_owner,$crstype)=@_;
1.84 www 6051: $url=&declutter($url);
6052: my $cid='';
1.264 matthew 6053: unless (&allowed('ccc',$udom)) {
1.84 www 6054: return 'refused';
6055: }
6056: # ------------------------------------------------------------------- Create ID
1.674 www 6057: my $uname=int(1+rand(9)).
6058: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6059: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 6060: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6061: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 6062: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6063: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6064: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
6065: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 6066: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6067: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6068: return 'error: unable to generate unique course-ID';
6069: }
6070: }
1.264 matthew 6071: # ------------------------------------------------ Check supplied server name
1.620 albertel 6072: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 6073: if (! &is_library($course_server)) {
1.264 matthew 6074: return 'error:bad server name '.$course_server;
6075: }
1.84 www 6076: # ------------------------------------------------------------- Make the course
6077: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6078: $course_server);
1.84 www 6079: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 6080: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6081: if (($uhome eq '') || ($uhome eq 'no_host')) {
6082: return 'error: no such course';
6083: }
1.271 www 6084: # ----------------------------------------------------------------- Course made
1.516 raeburn 6085: # log existence
1.918 raeburn 6086: my $newcourse = {
6087: $udom.'_'.$uname => {
1.921 raeburn 6088: description => $description,
6089: inst_code => $inst_code,
6090: owner => $course_owner,
6091: type => $crstype,
1.918 raeburn 6092: },
6093: };
1.921 raeburn 6094: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6095: # set toplevel url
1.271 www 6096: my $topurl=$url;
6097: unless ($nonstandard) {
6098: # ------------------------------------------ For standard courses, make top url
6099: my $mapurl=&clutter($url);
1.278 www 6100: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6101: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6102: <map>
6103: <resource id="1" type="start"></resource>
6104: <resource id="2" src="$mapurl"></resource>
6105: <resource id="3" type="finish"></resource>
6106: <link index="1" from="1" to="2"></link>
6107: <link index="2" from="2" to="3"></link>
6108: </map>
6109: ENDINITMAP
6110: $topurl=&declutter(
1.638 albertel 6111: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6112: );
6113: }
6114: # ----------------------------------------------------------- Write preferences
1.84 www 6115: &writecoursepref($udom.'_'.$uname,
6116: ('description' => $description,
1.271 www 6117: 'url' => $topurl));
1.84 www 6118: return '/'.$udom.'/'.$uname;
6119: }
6120:
1.813 albertel 6121: sub is_course {
6122: my ($cdom,$cnum) = @_;
6123: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6124: undef,'.');
1.813 albertel 6125: if (exists($courses{$cdom.'_'.$cnum})) {
6126: return 1;
6127: }
6128: return 0;
6129: }
6130:
1.21 www 6131: # ---------------------------------------------------------- Assign Custom Role
6132:
6133: sub assigncustomrole {
1.957 raeburn 6134: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6135: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6136: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6137: }
6138:
6139: # ----------------------------------------------------------------- Revoke Role
6140:
6141: sub revokerole {
1.957 raeburn 6142: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6143: my $now=time;
1.965 raeburn 6144: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6145: }
6146:
6147: # ---------------------------------------------------------- Revoke Custom Role
6148:
6149: sub revokecustomrole {
1.957 raeburn 6150: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6151: my $now=time;
1.357 www 6152: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6153: $deleteflag,$selfenroll,$context);
1.17 www 6154: }
6155:
1.533 banghart 6156: # ------------------------------------------------------------ Disk usage
1.535 albertel 6157: sub diskusage {
1.955 raeburn 6158: my ($udom,$uname,$directorypath,$getpropath)=@_;
6159: $directorypath =~ s/\/$//;
6160: my $listing=&reply('du2:'.&escape($directorypath).':'
6161: .&escape($getpropath).':'.&escape($uname).':'
6162: .&escape($udom),homeserver($uname,$udom));
6163: if ($listing eq 'unknown_cmd') {
6164: if ($getpropath) {
6165: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6166: }
6167: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6168: }
1.514 albertel 6169: return $listing;
1.512 banghart 6170: }
6171:
1.566 banghart 6172: sub is_locked {
6173: my ($file_name, $domain, $user) = @_;
6174: my @check;
6175: my $is_locked;
6176: push @check, $file_name;
1.613 albertel 6177: my %locked = &get('file_permissions',\@check,
1.620 albertel 6178: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6179: my ($tmp)=keys(%locked);
6180: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6181:
1.566 banghart 6182: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6183: $is_locked = 'false';
6184: foreach my $entry (@{$locked{$file_name}}) {
6185: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6186: $is_locked = 'true';
6187: last;
1.745 raeburn 6188: }
6189: }
1.566 banghart 6190: } else {
6191: $is_locked = 'false';
6192: }
6193: }
6194:
1.759 albertel 6195: sub declutter_portfile {
6196: my ($file) = @_;
1.833 albertel 6197: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6198: return $file;
6199: }
6200:
1.559 banghart 6201: # ------------------------------------------------------------- Mark as Read Only
6202:
6203: sub mark_as_readonly {
6204: my ($domain,$user,$files,$what) = @_;
1.613 albertel 6205: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6206: my ($tmp)=keys(%current_permissions);
6207: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 6208: foreach my $file (@{$files}) {
1.759 albertel 6209: $file = &declutter_portfile($file);
1.561 banghart 6210: push(@{$current_permissions{$file}},$what);
1.559 banghart 6211: }
1.613 albertel 6212: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6213: return;
6214: }
6215:
1.572 banghart 6216: # ------------------------------------------------------------Save Selected Files
6217:
6218: sub save_selected_files {
6219: my ($user, $path, @files) = @_;
6220: my $filename = $user."savedfiles";
1.573 banghart 6221: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 6222: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 6223: foreach my $file (@files) {
1.620 albertel 6224: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 6225: }
6226: foreach my $file (@other_files) {
1.574 banghart 6227: print (OUT $file."\n");
1.572 banghart 6228: }
1.574 banghart 6229: close (OUT);
1.572 banghart 6230: return 'ok';
6231: }
6232:
1.574 banghart 6233: sub clear_selected_files {
6234: my ($user) = @_;
6235: my $filename = $user."savedfiles";
6236: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6237: print (OUT undef);
6238: close (OUT);
6239: return ("ok");
6240: }
6241:
1.572 banghart 6242: sub files_in_path {
6243: my ($user, $path) = @_;
6244: my $filename = $user."savedfiles";
6245: my %return_files;
1.574 banghart 6246: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 6247: while (my $line_in = <IN>) {
1.574 banghart 6248: chomp ($line_in);
6249: my @paths_and_file = split (m!/!, $line_in);
6250: my $file_part = pop (@paths_and_file);
6251: my $path_part = join ('/', @paths_and_file);
1.573 banghart 6252: $path_part.='/';
6253: my $path_and_file = $path_part.$file_part;
6254: if ($path_part eq $path) {
6255: $return_files{$file_part}= 'selected';
6256: }
6257: }
1.574 banghart 6258: close (IN);
6259: return (\%return_files);
1.572 banghart 6260: }
6261:
6262: # called in portfolio select mode, to show files selected NOT in current directory
6263: sub files_not_in_path {
6264: my ($user, $path) = @_;
6265: my $filename = $user."savedfiles";
6266: my @return_files;
6267: my $path_part;
1.800 albertel 6268: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6269: while (my $line = <IN>) {
1.572 banghart 6270: #ok, I know it's clunky, but I want it to work
1.800 albertel 6271: my @paths_and_file = split(m|/|, $line);
6272: my $file_part = pop(@paths_and_file);
6273: chomp($file_part);
6274: my $path_part = join('/', @paths_and_file);
1.572 banghart 6275: $path_part .= '/';
6276: my $path_and_file = $path_part.$file_part;
6277: if ($path_part ne $path) {
1.800 albertel 6278: push(@return_files, ($path_and_file));
1.572 banghart 6279: }
6280: }
1.800 albertel 6281: close(OUT);
1.574 banghart 6282: return (@return_files);
1.572 banghart 6283: }
6284:
1.745 raeburn 6285: #----------------------------------------------Get portfolio file permissions
1.629 banghart 6286:
1.745 raeburn 6287: sub get_portfile_permissions {
6288: my ($domain,$user) = @_;
1.613 albertel 6289: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6290: my ($tmp)=keys(%current_permissions);
6291: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6292: return \%current_permissions;
6293: }
6294:
6295: #---------------------------------------------Get portfolio file access controls
6296:
1.749 raeburn 6297: sub get_access_controls {
1.745 raeburn 6298: my ($current_permissions,$group,$file) = @_;
1.769 albertel 6299: my %access;
6300: my $real_file = $file;
6301: $file =~ s/\.meta$//;
1.745 raeburn 6302: if (defined($file)) {
1.749 raeburn 6303: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6304: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 6305: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 6306: }
6307: }
1.745 raeburn 6308: } else {
1.749 raeburn 6309: foreach my $key (keys(%{$current_permissions})) {
6310: if ($key =~ /\0accesscontrol$/) {
6311: if (defined($group)) {
6312: if ($key !~ m-^\Q$group\E/-) {
6313: next;
6314: }
6315: }
6316: my ($fullpath) = split(/\0/,$key);
6317: if (ref($$current_permissions{$key}) eq 'HASH') {
6318: foreach my $control (keys(%{$$current_permissions{$key}})) {
6319: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6320: }
6321: }
6322: }
6323: }
6324: }
6325: return %access;
6326: }
6327:
6328: sub modify_access_controls {
6329: my ($file_name,$changes,$domain,$user)=@_;
6330: my ($outcome,$deloutcome);
6331: my %store_permissions;
6332: my %new_values;
6333: my %new_control;
6334: my %translation;
6335: my @deletions = ();
6336: my $now = time;
6337: if (exists($$changes{'activate'})) {
6338: if (ref($$changes{'activate'}) eq 'HASH') {
6339: my @newitems = sort(keys(%{$$changes{'activate'}}));
6340: my $numnew = scalar(@newitems);
6341: for (my $i=0; $i<$numnew; $i++) {
6342: my $newkey = $newitems[$i];
6343: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 6344: if ($newkey =~ /^\d+:/) {
6345: $newkey =~ s/^(\d+)/$newid/;
6346: $translation{$1} = $newid;
6347: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6348: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6349: $translation{$1} = $newid;
6350: }
1.749 raeburn 6351: $new_values{$file_name."\0".$newkey} =
6352: $$changes{'activate'}{$newitems[$i]};
6353: $new_control{$newkey} = $now;
6354: }
6355: }
6356: }
6357: my %todelete;
6358: my %changed_items;
6359: foreach my $action ('delete','update') {
6360: if (exists($$changes{$action})) {
6361: if (ref($$changes{$action}) eq 'HASH') {
6362: foreach my $key (keys(%{$$changes{$action}})) {
6363: my ($itemnum) = ($key =~ /^([^:]+):/);
6364: if ($action eq 'delete') {
6365: $todelete{$itemnum} = 1;
6366: } else {
6367: $changed_items{$itemnum} = $key;
6368: }
6369: }
1.745 raeburn 6370: }
6371: }
1.749 raeburn 6372: }
6373: # get lock on access controls for file.
6374: my $lockhash = {
6375: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6376: ':'.$env{'user.domain'},
6377: };
6378: my $tries = 0;
6379: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6380:
6381: while (($gotlock ne 'ok') && $tries <3) {
6382: $tries ++;
6383: sleep 1;
6384: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6385: }
6386: if ($gotlock eq 'ok') {
6387: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6388: my ($tmp)=keys(%curr_permissions);
6389: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6390: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6391: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6392: if (ref($curr_controls) eq 'HASH') {
6393: foreach my $control_item (keys(%{$curr_controls})) {
6394: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6395: if (defined($todelete{$itemnum})) {
6396: push(@deletions,$file_name."\0".$control_item);
6397: } else {
6398: if (defined($changed_items{$itemnum})) {
6399: $new_control{$changed_items{$itemnum}} = $now;
6400: push(@deletions,$file_name."\0".$control_item);
6401: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6402: } else {
6403: $new_control{$control_item} = $$curr_controls{$control_item};
6404: }
6405: }
1.745 raeburn 6406: }
6407: }
6408: }
1.970 raeburn 6409: my ($group);
6410: if (&is_course($domain,$user)) {
6411: ($group,my $file) = split(/\//,$file_name,2);
6412: }
1.749 raeburn 6413: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6414: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6415: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6416: # remove lock
6417: my @del_lock = ($file_name."\0".'locked_access_records');
6418: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 6419: my $sqlresult =
1.970 raeburn 6420: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 6421: $group);
1.749 raeburn 6422: } else {
6423: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 6424: }
1.749 raeburn 6425: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 6426: }
6427:
1.827 raeburn 6428: sub make_public_indefinitely {
6429: my ($requrl) = @_;
6430: my $now = time;
6431: my $action = 'activate';
6432: my $aclnum = 0;
6433: if (&is_portfolio_url($requrl)) {
6434: my (undef,$udom,$unum,$file_name,$group) =
6435: &parse_portfolio_url($requrl);
6436: my $current_perms = &get_portfile_permissions($udom,$unum);
6437: my %access_controls = &get_access_controls($current_perms,
6438: $group,$file_name);
6439: foreach my $key (keys(%{$access_controls{$file_name}})) {
6440: my ($num,$scope,$end,$start) =
6441: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6442: if ($scope eq 'public') {
6443: if ($start <= $now && $end == 0) {
6444: $action = 'none';
6445: } else {
6446: $action = 'update';
6447: $aclnum = $num;
6448: }
6449: last;
6450: }
6451: }
6452: if ($action eq 'none') {
6453: return 'ok';
6454: } else {
6455: my %changes;
6456: my $newend = 0;
6457: my $newstart = $now;
6458: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6459: $changes{$action}{$newkey} = {
6460: type => 'public',
6461: time => {
6462: start => $newstart,
6463: end => $newend,
6464: },
6465: };
6466: my ($outcome,$deloutcome,$new_values,$translation) =
6467: &modify_access_controls($file_name,\%changes,$udom,$unum);
6468: return $outcome;
6469: }
6470: } else {
6471: return 'invalid';
6472: }
6473: }
6474:
1.745 raeburn 6475: #------------------------------------------------------Get Marked as Read Only
6476:
6477: sub get_marked_as_readonly {
6478: my ($domain,$user,$what,$group) = @_;
6479: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 6480: my @readonly_files;
1.629 banghart 6481: my $cmp1=$what;
6482: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 6483: while (my ($file_name,$value) = each(%{$current_permissions})) {
6484: if (defined($group)) {
6485: if ($file_name !~ m-^\Q$group\E/-) {
6486: next;
6487: }
6488: }
1.561 banghart 6489: if (ref($value) eq "ARRAY"){
6490: foreach my $stored_what (@{$value}) {
1.629 banghart 6491: my $cmp2=$stored_what;
1.759 albertel 6492: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 6493: $cmp2=join('',@{$stored_what});
1.745 raeburn 6494: }
1.629 banghart 6495: if ($cmp1 eq $cmp2) {
1.561 banghart 6496: push(@readonly_files, $file_name);
1.745 raeburn 6497: last;
1.563 banghart 6498: } elsif (!defined($what)) {
6499: push(@readonly_files, $file_name);
1.745 raeburn 6500: last;
1.561 banghart 6501: }
6502: }
1.745 raeburn 6503: }
1.561 banghart 6504: }
6505: return @readonly_files;
6506: }
1.577 banghart 6507: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 6508:
1.577 banghart 6509: sub get_marked_as_readonly_hash {
1.745 raeburn 6510: my ($current_permissions,$group,$what) = @_;
1.577 banghart 6511: my %readonly_files;
1.745 raeburn 6512: while (my ($file_name,$value) = each(%{$current_permissions})) {
6513: if (defined($group)) {
6514: if ($file_name !~ m-^\Q$group\E/-) {
6515: next;
6516: }
6517: }
1.577 banghart 6518: if (ref($value) eq "ARRAY"){
6519: foreach my $stored_what (@{$value}) {
1.745 raeburn 6520: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6521: foreach my $lock_descriptor(@{$stored_what}) {
6522: if ($lock_descriptor eq 'graded') {
6523: $readonly_files{$file_name} = 'graded';
6524: } elsif ($lock_descriptor eq 'handback') {
6525: $readonly_files{$file_name} = 'handback';
6526: } else {
6527: if (!exists($readonly_files{$file_name})) {
6528: $readonly_files{$file_name} = 'locked';
6529: }
6530: }
1.745 raeburn 6531: }
1.750 banghart 6532: }
1.577 banghart 6533: }
6534: }
6535: }
6536: return %readonly_files;
6537: }
1.559 banghart 6538: # ------------------------------------------------------------ Unmark as Read Only
6539:
6540: sub unmark_as_readonly {
1.629 banghart 6541: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6542: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6543: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6544: $file_name = &declutter_portfile($file_name);
1.634 albertel 6545: my $symb_crs = $what;
6546: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6547: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6548: my ($tmp)=keys(%current_permissions);
6549: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6550: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6551: foreach my $file (@readonly_files) {
1.759 albertel 6552: my $clean_file = &declutter_portfile($file);
6553: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6554: my $current_locks = $current_permissions{$file};
1.563 banghart 6555: my @new_locks;
6556: my @del_keys;
6557: if (ref($current_locks) eq "ARRAY"){
6558: foreach my $locker (@{$current_locks}) {
1.632 albertel 6559: my $compare=$locker;
1.749 raeburn 6560: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6561: $compare=join('',@{$locker});
1.746 raeburn 6562: if ($compare ne $symb_crs) {
6563: push(@new_locks, $locker);
6564: }
1.563 banghart 6565: }
6566: }
1.650 albertel 6567: if (scalar(@new_locks) > 0) {
1.563 banghart 6568: $current_permissions{$file} = \@new_locks;
6569: } else {
6570: push(@del_keys, $file);
1.613 albertel 6571: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6572: delete($current_permissions{$file});
1.563 banghart 6573: }
6574: }
1.561 banghart 6575: }
1.613 albertel 6576: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6577: return;
6578: }
1.512 banghart 6579:
1.17 www 6580: # ------------------------------------------------------------ Directory lister
6581:
6582: sub dirlist {
1.955 raeburn 6583: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 6584: $uri=~s/^\///;
6585: $uri=~s/\/$//;
1.253 stredwic 6586: my ($udom, $uname);
1.955 raeburn 6587: if ($getuserdir) {
1.253 stredwic 6588: $udom = $userdomain;
6589: $uname = $username;
1.955 raeburn 6590: } else {
6591: (undef,$udom,$uname)=split(/\//,$uri);
6592: if(defined($userdomain)) {
6593: $udom = $userdomain;
6594: }
6595: if(defined($username)) {
6596: $uname = $username;
6597: }
1.253 stredwic 6598: }
1.955 raeburn 6599: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 6600:
1.955 raeburn 6601: $dirRoot = $perlvar{'lonDocRoot'};
6602: if (defined($getpropath)) {
6603: $dirRoot = &propath($udom,$uname);
1.253 stredwic 6604: $dirRoot =~ s/\/$//;
1.955 raeburn 6605: } elsif (defined($getuserdir)) {
6606: my $subdir=$uname.'__';
6607: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6608: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
6609: ."/$udom/$subdir/$uname";
6610: } elsif (defined($alternateRoot)) {
6611: $dirRoot = $alternateRoot;
1.751 banghart 6612: }
1.253 stredwic 6613:
6614: if($udom) {
6615: if($uname) {
1.955 raeburn 6616: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 6617: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 6618: .':'.&escape($uname).':'.&escape($udom),
6619: &homeserver($uname,$udom));
6620: if ($listing eq 'unknown_cmd') {
6621: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6622: &homeserver($uname,$udom));
6623: } else {
6624: @listing_results = map { &unescape($_); } split(/:/,$listing);
6625: }
1.605 matthew 6626: if ($listing eq 'unknown_cmd') {
1.800 albertel 6627: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6628: &homeserver($uname,$udom));
1.605 matthew 6629: @listing_results = split(/:/,$listing);
6630: } else {
6631: @listing_results = map { &unescape($_); } split(/:/,$listing);
6632: }
6633: return @listing_results;
1.955 raeburn 6634: } elsif(!$alternateRoot) {
1.800 albertel 6635: my %allusers;
1.841 albertel 6636: my %servers = &get_servers($udom,'library');
1.955 raeburn 6637: foreach my $tryserver (keys(%servers)) {
6638: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
6639: &escape($udom),$tryserver);
6640: if ($listing eq 'unknown_cmd') {
6641: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6642: $udom, $tryserver);
6643: } else {
6644: @listing_results = map { &unescape($_); } split(/:/,$listing);
6645: }
1.841 albertel 6646: if ($listing eq 'unknown_cmd') {
6647: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6648: $udom, $tryserver);
6649: @listing_results = split(/:/,$listing);
6650: } else {
6651: @listing_results =
6652: map { &unescape($_); } split(/:/,$listing);
6653: }
6654: if ($listing_results[0] ne 'no_such_dir' &&
6655: $listing_results[0] ne 'empty' &&
6656: $listing_results[0] ne 'con_lost') {
6657: foreach my $line (@listing_results) {
6658: my ($entry) = split(/&/,$line,2);
6659: $allusers{$entry} = 1;
6660: }
6661: }
1.253 stredwic 6662: }
6663: my $alluserstr='';
1.800 albertel 6664: foreach my $user (sort(keys(%allusers))) {
6665: $alluserstr.=$user.'&user:';
1.253 stredwic 6666: }
6667: $alluserstr=~s/:$//;
6668: return split(/:/,$alluserstr);
6669: } else {
1.800 albertel 6670: return ('missing user name');
1.253 stredwic 6671: }
1.955 raeburn 6672: } elsif(!defined($getpropath)) {
1.841 albertel 6673: my @all_domains = sort(&all_domains());
1.955 raeburn 6674: foreach my $domain (@all_domains) {
6675: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6676: }
6677: return @all_domains;
6678: } else {
1.800 albertel 6679: return ('missing domain');
1.275 stredwic 6680: }
6681: }
6682:
6683: # --------------------------------------------- GetFileTimestamp
6684: # This function utilizes dirlist and returns the date stamp for
6685: # when it was last modified. It will also return an error of -1
6686: # if an error occurs
6687:
6688: sub GetFileTimestamp {
1.955 raeburn 6689: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 6690: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6691: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 6692: my ($fileStat) =
6693: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
6694: undef,$getuserdir);
1.275 stredwic 6695: my @stats = split('&', $fileStat);
6696: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6697: # @stats contains first the filename, then the stat output
6698: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6699: } else {
6700: return -1;
1.253 stredwic 6701: }
1.26 www 6702: }
6703:
1.712 albertel 6704: sub stat_file {
6705: my ($uri) = @_;
1.787 albertel 6706: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6707:
1.955 raeburn 6708: my ($udom,$uname,$file);
1.712 albertel 6709: if ($uri =~ m-^/(uploaded|editupload)/-) {
6710: ($udom,$uname,$file) =
1.811 albertel 6711: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6712: $file = 'userfiles/'.$file;
6713: }
6714: if ($uri =~ m-^/res/-) {
6715: ($udom,$uname) =
1.807 albertel 6716: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6717: $file = $uri;
6718: }
6719:
6720: if (!$udom || !$uname || !$file) {
6721: # unable to handle the uri
6722: return ();
6723: }
1.956 raeburn 6724: my $getpropath;
6725: if ($file =~ /^userfiles\//) {
6726: $getpropath = 1;
6727: }
1.955 raeburn 6728: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 6729: my @stats = split('&', $result);
1.721 banghart 6730:
1.712 albertel 6731: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6732: shift(@stats); #filename is first
6733: return @stats;
6734: }
6735: return ();
6736: }
6737:
1.26 www 6738: # -------------------------------------------------------- Value of a Condition
6739:
1.713 albertel 6740: # gets the value of a specific preevaluated condition
6741: # stored in the string $env{user.state.<cid>}
6742: # or looks up a condition reference in the bighash and if if hasn't
6743: # already been evaluated recurses into docondval to get the value of
6744: # the condition, then memoizing it to
6745: # $env{user.state.<cid>.<condition>}
1.40 www 6746: sub directcondval {
6747: my $number=shift;
1.620 albertel 6748: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 6749: &Apache::lonuserstate::evalstate();
6750: }
1.713 albertel 6751: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6752: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6753: } elsif ($number =~ /^_/) {
6754: my $sub_condition;
6755: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6756: &GDBM_READER(),0640)) {
6757: $sub_condition=$bighash{'conditions'.$number};
6758: untie(%bighash);
6759: }
6760: my $value = &docondval($sub_condition);
1.949 raeburn 6761: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 6762: return $value;
6763: }
1.620 albertel 6764: if ($env{'user.state.'.$env{'request.course.id'}}) {
6765: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 6766: } else {
6767: return 2;
6768: }
6769: }
6770:
1.713 albertel 6771: # get the collection of conditions for this resource
1.26 www 6772: sub condval {
6773: my $condidx=shift;
1.54 www 6774: my $allpathcond='';
1.713 albertel 6775: foreach my $cond (split(/\|/,$condidx)) {
6776: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6777: $allpathcond.=
6778: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6779: }
1.191 harris41 6780: }
1.54 www 6781: $allpathcond=~s/\|$//;
1.713 albertel 6782: return &docondval($allpathcond);
6783: }
6784:
6785: #evaluates an expression of conditions
6786: sub docondval {
6787: my ($allpathcond) = @_;
6788: my $result=0;
6789: if ($env{'request.course.id'}
6790: && defined($allpathcond)) {
6791: my $operand='|';
6792: my @stack;
6793: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6794: if ($chunk eq '(') {
6795: push @stack,($operand,$result);
6796: } elsif ($chunk eq ')') {
6797: my $before=pop @stack;
6798: if (pop @stack eq '&') {
6799: $result=$result>$before?$before:$result;
6800: } else {
6801: $result=$result>$before?$result:$before;
6802: }
6803: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6804: $operand=$chunk;
6805: } else {
6806: my $new=directcondval($chunk);
6807: if ($operand eq '&') {
6808: $result=$result>$new?$new:$result;
6809: } else {
6810: $result=$result>$new?$result:$new;
6811: }
6812: }
6813: }
1.26 www 6814: }
6815: return $result;
1.421 albertel 6816: }
6817:
6818: # ---------------------------------------------------- Devalidate courseresdata
6819:
6820: sub devalidatecourseresdata {
6821: my ($coursenum,$coursedomain)=@_;
6822: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6823: &devalidate_cache_new('courseres',$hashid);
1.28 www 6824: }
6825:
1.763 www 6826:
1.200 www 6827: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 6828: #
6829: # Parameters:
6830: # $coursenum - Number of the course.
6831: # $coursedomain - Domain at which the course was created.
6832: # Returns:
6833: # A hash of the course parameters along (I think) with timestamps
6834: # and version info.
1.877 foxr 6835:
1.624 albertel 6836: sub get_courseresdata {
6837: my ($coursenum,$coursedomain)=@_;
1.200 www 6838: my $coursehom=&homeserver($coursenum,$coursedomain);
6839: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6840: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 6841: my %dumpreply;
1.417 albertel 6842: unless (defined($cached)) {
1.624 albertel 6843: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 6844: $result=\%dumpreply;
1.251 albertel 6845: my ($tmp) = keys(%dumpreply);
6846: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 6847: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 6848: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
6849: return $tmp;
1.416 albertel 6850: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 6851: $result=undef;
1.599 albertel 6852: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 6853: }
6854: }
1.624 albertel 6855: return $result;
6856: }
6857:
1.633 albertel 6858: sub devalidateuserresdata {
6859: my ($uname,$udom)=@_;
6860: my $hashid="$udom:$uname";
6861: &devalidate_cache_new('userres',$hashid);
6862: }
6863:
1.624 albertel 6864: sub get_userresdata {
6865: my ($uname,$udom)=@_;
6866: #most student don\'t have any data set, check if there is some data
6867: if (&EXT_cache_status($udom,$uname)) { return undef; }
6868:
6869: my $hashid="$udom:$uname";
6870: my ($result,$cached)=&is_cached_new('userres',$hashid);
6871: if (!defined($cached)) {
6872: my %resourcedata=&dump('resourcedata',$udom,$uname);
6873: $result=\%resourcedata;
6874: &do_cache_new('userres',$hashid,$result,600);
6875: }
6876: my ($tmp)=keys(%$result);
6877: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
6878: return $result;
6879: }
6880: #error 2 occurs when the .db doesn't exist
6881: if ($tmp!~/error: 2 /) {
1.672 albertel 6882: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 6883: " Trying to get resource data for ".
6884: $uname." at ".$udom.": ".
6885: $tmp."</font>");
6886: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 6887: #&EXT_cache_set($udom,$uname);
6888: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 6889: undef($tmp); # not really an error so don't send it back
1.624 albertel 6890: }
6891: return $tmp;
6892: }
1.879 foxr 6893: #----------------------------------------------- resdata - return resource data
6894: # Purpose:
6895: # Return resource data for either users or for a course.
6896: # Parameters:
6897: # $name - Course/user name.
6898: # $domain - Name of the domain the user/course is registered on.
6899: # $type - Type of thing $name is (must be 'course' or 'user'
6900: # @which - Array of names of resources desired.
6901: # Returns:
6902: # The value of the first reasource in @which that is found in the
6903: # resource hash.
6904: # Exceptional Conditions:
6905: # If the $type passed in is not valid (not the string 'course' or
6906: # 'user', an undefined reference is returned.
6907: # If none of the resources are found, an undef is returned
1.624 albertel 6908: sub resdata {
6909: my ($name,$domain,$type,@which)=@_;
6910: my $result;
6911: if ($type eq 'course') {
6912: $result=&get_courseresdata($name,$domain);
6913: } elsif ($type eq 'user') {
6914: $result=&get_userresdata($name,$domain);
6915: }
6916: if (!ref($result)) { return $result; }
1.251 albertel 6917: foreach my $item (@which) {
1.927 albertel 6918: if (defined($result->{$item->[0]})) {
6919: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 6920: }
1.250 albertel 6921: }
1.291 albertel 6922: return undef;
1.200 www 6923: }
6924:
1.379 matthew 6925: #
6926: # EXT resource caching routines
6927: #
6928:
6929: sub clear_EXT_cache_status {
1.383 albertel 6930: &delenv('cache.EXT.');
1.379 matthew 6931: }
6932:
6933: sub EXT_cache_status {
6934: my ($target_domain,$target_user) = @_;
1.383 albertel 6935: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 6936: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 6937: # We know already the user has no data
6938: return 1;
6939: } else {
6940: return 0;
6941: }
6942: }
6943:
6944: sub EXT_cache_set {
6945: my ($target_domain,$target_user) = @_;
1.383 albertel 6946: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 6947: #&appenv({$cachename => time});
1.379 matthew 6948: }
6949:
1.28 www 6950: # --------------------------------------------------------- Value of a Variable
1.58 www 6951: sub EXT {
1.715 albertel 6952:
1.395 albertel 6953: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 6954: unless ($varname) { return ''; }
1.218 albertel 6955: #get real user name/domain, courseid and symb
6956: my $courseid;
1.359 albertel 6957: my $publicuser;
1.427 www 6958: if ($symbparm) {
6959: $symbparm=&get_symb_from_alias($symbparm);
6960: }
1.218 albertel 6961: if (!($uname && $udom)) {
1.790 albertel 6962: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6963: if (!$symbparm) { $symbparm=$cursymb; }
6964: } else {
1.620 albertel 6965: $courseid=$env{'request.course.id'};
1.218 albertel 6966: }
1.48 www 6967: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6968: my $rest;
1.320 albertel 6969: if (defined($therest[0])) {
1.48 www 6970: $rest=join('.',@therest);
6971: } else {
6972: $rest='';
6973: }
1.320 albertel 6974:
1.57 www 6975: my $qualifierrest=$qualifier;
6976: if ($rest) { $qualifierrest.='.'.$rest; }
6977: my $spacequalifierrest=$space;
6978: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6979: if ($realm eq 'user') {
1.48 www 6980: # --------------------------------------------------------------- user.resource
6981: if ($space eq 'resource') {
1.651 albertel 6982: if ( (defined($Apache::lonhomework::parsing_a_problem)
6983: || defined($Apache::lonhomework::parsing_a_task))
6984: &&
1.744 albertel 6985: ($symbparm eq &symbread()) ) {
6986: # if we are in the middle of processing the resource the
6987: # get the value we are planning on committing
6988: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6989: return $Apache::lonhomework::results{$qualifierrest};
6990: } else {
6991: return $Apache::lonhomework::history{$qualifierrest};
6992: }
1.335 albertel 6993: } else {
1.359 albertel 6994: my %restored;
1.620 albertel 6995: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6996: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6997: } else {
6998: %restored=&restore($symbparm,$courseid,$udom,$uname);
6999: }
1.335 albertel 7000: return $restored{$qualifierrest};
7001: }
1.48 www 7002: # ----------------------------------------------------------------- user.access
7003: } elsif ($space eq 'access') {
1.218 albertel 7004: # FIXME - not supporting calls for a specific user
1.48 www 7005: return &allowed($qualifier,$rest);
7006: # ------------------------------------------ user.preferences, user.environment
7007: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7008: if (($uname eq $env{'user.name'}) &&
7009: ($udom eq $env{'user.domain'})) {
7010: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7011: } else {
1.359 albertel 7012: my %returnhash;
7013: if (!$publicuser) {
7014: %returnhash=&userenvironment($udom,$uname,
7015: $qualifierrest);
7016: }
1.218 albertel 7017: return $returnhash{$qualifierrest};
7018: }
1.48 www 7019: # ----------------------------------------------------------------- user.course
7020: } elsif ($space eq 'course') {
1.218 albertel 7021: # FIXME - not supporting calls for a specific user
1.620 albertel 7022: return $env{join('.',('request.course',$qualifier))};
1.48 www 7023: # ------------------------------------------------------------------- user.role
7024: } elsif ($space eq 'role') {
1.218 albertel 7025: # FIXME - not supporting calls for a specific user
1.620 albertel 7026: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7027: if ($qualifier eq 'value') {
7028: return $role;
7029: } elsif ($qualifier eq 'extent') {
7030: return $where;
7031: }
7032: # ----------------------------------------------------------------- user.domain
7033: } elsif ($space eq 'domain') {
1.218 albertel 7034: return $udom;
1.48 www 7035: # ------------------------------------------------------------------- user.name
7036: } elsif ($space eq 'name') {
1.218 albertel 7037: return $uname;
1.48 www 7038: # ---------------------------------------------------- Any other user namespace
1.29 www 7039: } else {
1.359 albertel 7040: my %reply;
7041: if (!$publicuser) {
7042: %reply=&get($space,[$qualifierrest],$udom,$uname);
7043: }
7044: return $reply{$qualifierrest};
1.48 www 7045: }
1.236 www 7046: } elsif ($realm eq 'query') {
7047: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7048: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7049: [$spacequalifierrest]);
1.620 albertel 7050: return $env{'form.'.$spacequalifierrest};
1.236 www 7051: } elsif ($realm eq 'request') {
1.48 www 7052: # ------------------------------------------------------------- request.browser
7053: if ($space eq 'browser') {
1.430 www 7054: if ($qualifier eq 'textremote') {
1.676 albertel 7055: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7056: return 1;
7057: } else {
7058: return 0;
7059: }
7060: } else {
1.620 albertel 7061: return $env{'browser.'.$qualifier};
1.430 www 7062: }
1.57 www 7063: # ------------------------------------------------------------ request.filename
7064: } else {
1.620 albertel 7065: return $env{'request.'.$spacequalifierrest};
1.29 www 7066: }
1.28 www 7067: } elsif ($realm eq 'course') {
1.48 www 7068: # ---------------------------------------------------------- course.description
1.620 albertel 7069: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7070: } elsif ($realm eq 'resource') {
1.165 www 7071:
1.620 albertel 7072: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7073: if (!$symbparm) { $symbparm=&symbread(); }
7074: }
1.693 albertel 7075:
7076: if ($space eq 'title') {
7077: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7078: return &gettitle($symbparm);
7079: }
7080:
7081: if ($space eq 'map') {
7082: my ($map) = &decode_symb($symbparm);
7083: return &symbread($map);
7084: }
1.905 albertel 7085: if ($space eq 'filename') {
7086: if ($symbparm) {
7087: return &clutter((&decode_symb($symbparm))[2]);
7088: }
7089: return &hreflocation('',$env{'request.filename'});
7090: }
1.693 albertel 7091:
7092: my ($section, $group, @groups);
1.593 albertel 7093: my ($courselevelm,$courselevel);
1.539 albertel 7094: if ($symbparm && defined($courseid) &&
1.620 albertel 7095: $courseid eq $env{'request.course.id'}) {
1.165 www 7096:
1.218 albertel 7097: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7098:
1.60 www 7099: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7100: my $symbp=$symbparm;
1.735 albertel 7101: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7102:
7103: my $symbparm=$symbp.'.'.$spacequalifierrest;
7104: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7105:
1.620 albertel 7106: if (($env{'user.name'} eq $uname) &&
7107: ($env{'user.domain'} eq $udom)) {
7108: $section=$env{'request.course.sec'};
1.733 raeburn 7109: @groups = split(/:/,$env{'request.course.groups'});
7110: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7111: } else {
1.539 albertel 7112: if (! defined($usection)) {
1.551 albertel 7113: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7114: } else {
7115: $section = $usection;
7116: }
1.733 raeburn 7117: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7118: }
7119:
7120: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7121: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7122: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7123:
1.593 albertel 7124: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7125: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7126: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7127:
1.60 www 7128: # ----------------------------------------------------------- first, check user
1.624 albertel 7129:
7130: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7131: ([$courselevelr,'resource'],
7132: [$courselevelm,'map' ],
7133: [$courselevel, 'course' ]));
1.931 albertel 7134: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7135:
1.594 albertel 7136: # ------------------------------------------------ second, check some of course
1.684 raeburn 7137: my $coursereply;
1.691 raeburn 7138: if (@groups > 0) {
7139: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7140: $mapparm,$spacequalifierrest);
1.927 albertel 7141: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7142: }
1.96 www 7143:
1.684 raeburn 7144: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7145: $env{'course.'.$courseid.'.domain'},
7146: 'course',
7147: ([$seclevelr, 'resource'],
7148: [$seclevelm, 'map' ],
7149: [$seclevel, 'course' ],
7150: [$courselevelr,'resource']));
7151: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7152:
1.60 www 7153: # ------------------------------------------------------ third, check map parms
1.218 albertel 7154: my %parmhash=();
7155: my $thisparm='';
7156: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7157: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7158: &GDBM_READER(),0640)) {
1.218 albertel 7159: $thisparm=$parmhash{$symbparm};
7160: untie(%parmhash);
7161: }
1.927 albertel 7162: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7163: }
1.594 albertel 7164: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7165:
1.218 albertel 7166: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7167: my $filename;
7168: if (!$symbparm) { $symbparm=&symbread(); }
7169: if ($symbparm) {
1.409 www 7170: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7171: } else {
1.620 albertel 7172: $filename=$env{'request.filename'};
1.282 albertel 7173: }
7174: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7175: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7176: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7177: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7178:
1.927 albertel 7179: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7180: if ($symbparm && defined($courseid) &&
1.620 albertel 7181: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7182: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7183: $env{'course.'.$courseid.'.domain'},
7184: 'course',
1.927 albertel 7185: ([$courselevelm,'map' ],
7186: [$courselevel, 'course']));
7187: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7188: }
1.145 www 7189: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7190: unless ($space eq '0') {
1.336 albertel 7191: my @parts=split(/_/,$space);
7192: my $id=pop(@parts);
7193: my $part=join('_',@parts);
7194: if ($part eq '') { $part='0'; }
1.927 albertel 7195: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7196: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7197: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7198: }
1.395 albertel 7199: if ($recurse) { return undef; }
7200: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 7201: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 7202: # ---------------------------------------------------- Any other user namespace
7203: } elsif ($realm eq 'environment') {
7204: # ----------------------------------------------------------------- environment
1.620 albertel 7205: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7206: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 7207: } else {
1.770 albertel 7208: if ($uname eq 'anonymous' && $udom eq '') {
7209: return '';
7210: }
1.219 albertel 7211: my %returnhash=&userenvironment($udom,$uname,
7212: $spacequalifierrest);
7213: return $returnhash{$spacequalifierrest};
7214: }
1.28 www 7215: } elsif ($realm eq 'system') {
1.48 www 7216: # ----------------------------------------------------------------- system.time
7217: if ($space eq 'time') {
7218: return time;
7219: }
1.696 albertel 7220: } elsif ($realm eq 'server') {
7221: # ----------------------------------------------------------------- system.time
7222: if ($space eq 'name') {
7223: return $ENV{'SERVER_NAME'};
7224: }
1.28 www 7225: }
1.48 www 7226: return '';
1.61 www 7227: }
7228:
1.927 albertel 7229: sub get_reply {
7230: my ($reply_value) = @_;
1.940 raeburn 7231: if (ref($reply_value) eq 'ARRAY') {
7232: if (wantarray) {
7233: return @$reply_value;
7234: }
7235: return $reply_value->[0];
7236: } else {
7237: return $reply_value;
1.927 albertel 7238: }
7239: }
7240:
1.691 raeburn 7241: sub check_group_parms {
7242: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7243: my @groupitems = ();
7244: my $resultitem;
1.927 albertel 7245: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 7246: foreach my $group (@{$groups}) {
7247: foreach my $level (@levels) {
1.927 albertel 7248: my $item = $courseid.'.['.$group.'].'.$level->[0];
7249: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 7250: }
7251: }
7252: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7253: $env{'course.'.$courseid.'.domain'},
7254: 'course',@groupitems);
7255: return $coursereply;
7256: }
7257:
7258: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 7259: my ($courseid,@groups) = @_;
7260: @groups = sort(@groups);
1.691 raeburn 7261: return @groups;
7262: }
7263:
1.395 albertel 7264: sub packages_tab_default {
7265: my ($uri,$varname)=@_;
7266: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 7267:
7268: my (@extension,@specifics,$do_default);
7269: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 7270: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 7271: if ($pack_type eq 'default') {
7272: $do_default=1;
7273: } elsif ($pack_type eq 'extension') {
7274: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 7275: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 7276: # only look at packages defaults for packages that this id is
1.738 albertel 7277: push(@specifics,[$package,$pack_type,$pack_part]);
7278: }
7279: }
7280: # first look for a package that matches the requested part id
7281: foreach my $package (@specifics) {
7282: my (undef,$pack_type,$pack_part)=@{$package};
7283: next if ($pack_part ne $part);
7284: if (defined($packagetab{"$pack_type&$name&default"})) {
7285: return $packagetab{"$pack_type&$name&default"};
7286: }
7287: }
7288: # look for any possible matching non extension_ package
7289: foreach my $package (@specifics) {
7290: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 7291: if (defined($packagetab{"$pack_type&$name&default"})) {
7292: return $packagetab{"$pack_type&$name&default"};
7293: }
1.585 albertel 7294: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 7295: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7296: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 7297: }
7298: }
1.738 albertel 7299: # look for any posible extension_ match
7300: foreach my $package (@extension) {
7301: my ($package,$pack_type)=@{$package};
7302: if (defined($packagetab{"$pack_type&$name&default"})) {
7303: return $packagetab{"$pack_type&$name&default"};
7304: }
7305: if (defined($packagetab{$package."&$name&default"})) {
7306: return $packagetab{$package."&$name&default"};
7307: }
7308: }
7309: # look for a global default setting
7310: if ($do_default && defined($packagetab{"default&$name&default"})) {
7311: return $packagetab{"default&$name&default"};
7312: }
1.395 albertel 7313: return undef;
7314: }
7315:
1.334 albertel 7316: sub add_prefix_and_part {
7317: my ($prefix,$part)=@_;
7318: my $keyroot;
7319: if (defined($prefix) && $prefix !~ /^__/) {
7320: # prefix that has a part already
7321: $keyroot=$prefix;
7322: } elsif (defined($prefix)) {
7323: # prefix that is missing a part
7324: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7325: } else {
7326: # no prefix at all
7327: if (defined($part)) { $keyroot='_'.$part; }
7328: }
7329: return $keyroot;
7330: }
7331:
1.71 www 7332: # ---------------------------------------------------------------- Get metadata
7333:
1.599 albertel 7334: my %metaentry;
1.71 www 7335: sub metadata {
1.176 www 7336: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 7337: $uri=&declutter($uri);
1.288 albertel 7338: # if it is a non metadata possible uri return quickly
1.529 albertel 7339: if (($uri eq '') ||
7340: (($uri =~ m|^/*adm/|) &&
1.698 albertel 7341: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 7342: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7343: return undef;
7344: }
7345: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7346: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 7347: return undef;
1.288 albertel 7348: }
1.73 www 7349: my $filename=$uri;
7350: $uri=~s/\.meta$//;
1.172 www 7351: #
7352: # Is the metadata already cached?
1.177 www 7353: # Look at timestamp of caching
1.172 www 7354: # Everything is cached by the main uri, libraries are never directly cached
7355: #
1.428 albertel 7356: if (!defined($liburi)) {
1.599 albertel 7357: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 7358: if (defined($cached)) { return $result->{':'.$what}; }
7359: }
7360: {
1.172 www 7361: #
7362: # Is this a recursive call for a library?
7363: #
1.599 albertel 7364: # if (! exists($metacache{$uri})) {
7365: # $metacache{$uri}={};
7366: # }
1.924 albertel 7367: my $cachetime = 60*60;
1.171 www 7368: if ($liburi) {
7369: $liburi=&declutter($liburi);
7370: $filename=$liburi;
1.401 bowersj2 7371: } else {
1.599 albertel 7372: &devalidate_cache_new('meta',$uri);
7373: undef(%metaentry);
1.401 bowersj2 7374: }
1.140 www 7375: my %metathesekeys=();
1.73 www 7376: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 7377: my $metastring;
1.924 albertel 7378: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 7379: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 7380: $metastring =
1.929 albertel 7381: &Apache::lonnet::ssi_body($which,
1.924 albertel 7382: ('grade_target' => 'meta'));
7383: $cachetime = 1; # only want this cached in the child not long term
7384: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 7385: my $file=&filelocation('',&clutter($filename));
1.599 albertel 7386: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 7387: $metastring=&getfile($file);
1.489 albertel 7388: }
1.208 albertel 7389: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 7390: my $token;
1.140 www 7391: undef %metathesekeys;
1.71 www 7392: while ($token=$parser->get_token) {
1.339 albertel 7393: if ($token->[0] eq 'S') {
7394: if (defined($token->[2]->{'package'})) {
1.172 www 7395: #
7396: # This is a package - get package info
7397: #
1.339 albertel 7398: my $package=$token->[2]->{'package'};
7399: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7400: if (defined($token->[2]->{'id'})) {
7401: $keyroot.='_'.$token->[2]->{'id'};
7402: }
1.599 albertel 7403: if ($metaentry{':packages'}) {
7404: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 7405: } else {
1.599 albertel 7406: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 7407: }
1.736 albertel 7408: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 7409: my $part=$keyroot;
7410: $part=~s/^\_//;
1.736 albertel 7411: if ($pack_entry=~/^\Q$package\E\&/ ||
7412: $pack_entry=~/^\Q$package\E_0\&/) {
7413: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 7414: # ignore package.tab specified default values
7415: # here &package_tab_default() will fetch those
7416: if ($subp eq 'default') { next; }
1.736 albertel 7417: my $value=$packagetab{$pack_entry};
1.432 albertel 7418: my $unikey;
7419: if ($pack =~ /_0$/) {
7420: $unikey='parameter_0_'.$name;
7421: $part=0;
7422: } else {
7423: $unikey='parameter'.$keyroot.'_'.$name;
7424: }
1.339 albertel 7425: if ($subp eq 'display') {
7426: $value.=' [Part: '.$part.']';
7427: }
1.599 albertel 7428: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 7429: $metathesekeys{$unikey}=1;
1.599 albertel 7430: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7431: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 7432: }
1.599 albertel 7433: if (defined($metaentry{':'.$unikey.'.default'})) {
7434: $metaentry{':'.$unikey}=
7435: $metaentry{':'.$unikey.'.default'};
1.356 albertel 7436: }
1.339 albertel 7437: }
7438: }
7439: } else {
1.172 www 7440: #
7441: # This is not a package - some other kind of start tag
1.339 albertel 7442: #
7443: my $entry=$token->[1];
7444: my $unikey;
7445: if ($entry eq 'import') {
7446: $unikey='';
7447: } else {
7448: $unikey=$entry;
7449: }
7450: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7451:
7452: if (defined($token->[2]->{'id'})) {
7453: $unikey.='_'.$token->[2]->{'id'};
7454: }
1.175 www 7455:
1.339 albertel 7456: if ($entry eq 'import') {
1.175 www 7457: #
7458: # Importing a library here
1.339 albertel 7459: #
7460: if ($depthcount<20) {
7461: my $location=$parser->get_text('/import');
7462: my $dir=$filename;
7463: $dir=~s|[^/]*$||;
7464: $location=&filelocation($dir,$location);
1.736 albertel 7465: my $metadata =
7466: &metadata($uri,'keys', $location,$unikey,
7467: $depthcount+1);
7468: foreach my $meta (split(',',$metadata)) {
7469: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7470: $metathesekeys{$meta}=1;
1.339 albertel 7471: }
7472: }
7473: } else {
7474:
7475: if (defined($token->[2]->{'name'})) {
7476: $unikey.='_'.$token->[2]->{'name'};
7477: }
7478: $metathesekeys{$unikey}=1;
1.736 albertel 7479: foreach my $param (@{$token->[3]}) {
7480: $metaentry{':'.$unikey.'.'.$param} =
7481: $token->[2]->{$param};
1.339 albertel 7482: }
7483: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 7484: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 7485: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7486: # only ws inside the tag, and not in default, so use default
7487: # as value
1.599 albertel 7488: $metaentry{':'.$unikey}=$default;
1.908 albertel 7489: } elsif ( $internaltext =~ /\S/ ) {
7490: # something interesting inside the tag
7491: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 7492: } else {
1.908 albertel 7493: # no interesting values, don't set a default
1.339 albertel 7494: }
1.172 www 7495: # end of not-a-package not-a-library import
1.339 albertel 7496: }
1.172 www 7497: # end of not-a-package start tag
1.339 albertel 7498: }
1.172 www 7499: # the next is the end of "start tag"
1.339 albertel 7500: }
7501: }
1.483 albertel 7502: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 7503: $extension = lc($extension);
7504: if ($extension eq 'htm') { $extension='html'; }
7505:
1.737 albertel 7506: foreach my $key (keys(%packagetab)) {
1.483 albertel 7507: #no specific packages #how's our extension
7508: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 7509: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 7510: \%metathesekeys);
7511: }
1.883 albertel 7512:
7513: if (!exists($metaentry{':packages'})
7514: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 7515: foreach my $key (keys(%packagetab)) {
1.483 albertel 7516: #no specific packages well let's get default then
7517: if ($key!~/^default&/) { next; }
1.488 albertel 7518: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 7519: \%metathesekeys);
7520: }
7521: }
1.338 www 7522: # are there custom rights to evaluate
1.599 albertel 7523: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 7524:
1.338 www 7525: #
7526: # Importing a rights file here
1.339 albertel 7527: #
7528: unless ($depthcount) {
1.599 albertel 7529: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 7530: my $dir=$filename;
7531: $dir=~s|[^/]*$||;
7532: $location=&filelocation($dir,$location);
1.736 albertel 7533: my $rights_metadata =
7534: &metadata($uri,'keys',$location,'_rights',
7535: $depthcount+1);
7536: foreach my $rights (split(',',$rights_metadata)) {
7537: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7538: $metathesekeys{$rights}=1;
1.339 albertel 7539: }
7540: }
7541: }
1.737 albertel 7542: # uniqifiy package listing
7543: my %seen;
7544: my @uniq_packages =
7545: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7546: $metaentry{':packages'} = join(',',@uniq_packages);
7547:
7548: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 7549: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7550: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 7551: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 7552: # this is the end of "was not already recently cached
1.71 www 7553: }
1.599 albertel 7554: return $metaentry{':'.$what};
1.261 albertel 7555: }
7556:
1.488 albertel 7557: sub metadata_create_package_def {
1.483 albertel 7558: my ($uri,$key,$package,$metathesekeys)=@_;
7559: my ($pack,$name,$subp)=split(/\&/,$key);
7560: if ($subp eq 'default') { next; }
7561:
1.599 albertel 7562: if (defined($metaentry{':packages'})) {
7563: $metaentry{':packages'}.=','.$package;
1.483 albertel 7564: } else {
1.599 albertel 7565: $metaentry{':packages'}=$package;
1.483 albertel 7566: }
7567: my $value=$packagetab{$key};
7568: my $unikey;
7569: $unikey='parameter_0_'.$name;
1.599 albertel 7570: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 7571: $$metathesekeys{$unikey}=1;
1.599 albertel 7572: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7573: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 7574: }
1.599 albertel 7575: if (defined($metaentry{':'.$unikey.'.default'})) {
7576: $metaentry{':'.$unikey}=
7577: $metaentry{':'.$unikey.'.default'};
1.483 albertel 7578: }
7579: }
7580:
1.261 albertel 7581: sub metadata_generate_part0 {
7582: my ($metadata,$metacache,$uri) = @_;
7583: my %allnames;
1.737 albertel 7584: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7585: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7586: my $part=$$metacache{':'.$metakey.'.part'};
7587: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7588: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7589: $allnames{$name}=$part;
7590: }
7591: }
7592: }
7593: foreach my $name (keys(%allnames)) {
7594: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7595: my $key=":parameter_0_$name";
1.261 albertel 7596: $$metacache{"$key.part"}='0';
7597: $$metacache{"$key.name"}=$name;
1.428 albertel 7598: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7599: $allnames{$name}.'_'.$name.
7600: '.type'};
1.428 albertel 7601: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7602: '.display'};
1.644 www 7603: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7604: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7605: $$metacache{"$key.display"}=$olddis;
7606: }
1.71 www 7607: }
7608:
1.764 albertel 7609: # ------------------------------------------------------ Devalidate title cache
7610:
7611: sub devalidate_title_cache {
7612: my ($url)=@_;
7613: if (!$env{'request.course.id'}) { return; }
7614: my $symb=&symbread($url);
7615: if (!$symb) { return; }
7616: my $key=$env{'request.course.id'}."\0".$symb;
7617: &devalidate_cache_new('title',$key);
7618: }
7619:
1.301 www 7620: # ------------------------------------------------- Get the title of a resource
7621:
7622: sub gettitle {
7623: my $urlsymb=shift;
7624: my $symb=&symbread($urlsymb);
1.534 albertel 7625: if ($symb) {
1.620 albertel 7626: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7627: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7628: if (defined($cached)) {
7629: return $result;
7630: }
1.534 albertel 7631: my ($map,$resid,$url)=&decode_symb($symb);
7632: my $title='';
1.907 albertel 7633: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7634: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7635: } else {
7636: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7637: &GDBM_READER(),0640)) {
7638: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7639: $title=$bighash{'title_'.$mapid.'.'.$resid};
7640: untie(%bighash);
7641: }
1.534 albertel 7642: }
7643: $title=~s/\&colon\;/\:/gs;
7644: if ($title) {
1.599 albertel 7645: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7646: }
7647: $urlsymb=$url;
7648: }
7649: my $title=&metadata($urlsymb,'title');
7650: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7651: return $title;
1.301 www 7652: }
1.613 albertel 7653:
1.614 albertel 7654: sub get_slot {
7655: my ($which,$cnum,$cdom)=@_;
7656: if (!$cnum || !$cdom) {
1.790 albertel 7657: (undef,my $courseid)=&whichuser();
1.620 albertel 7658: $cdom=$env{'course.'.$courseid.'.domain'};
7659: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7660: }
1.703 albertel 7661: my $key=join("\0",'slots',$cdom,$cnum,$which);
7662: my %slotinfo;
7663: if (exists($remembered{$key})) {
7664: $slotinfo{$which} = $remembered{$key};
7665: } else {
7666: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7667: &Apache::lonhomework::showhash(%slotinfo);
7668: my ($tmp)=keys(%slotinfo);
7669: if ($tmp=~/^error:/) { return (); }
7670: $remembered{$key} = $slotinfo{$which};
7671: }
1.616 albertel 7672: if (ref($slotinfo{$which}) eq 'HASH') {
7673: return %{$slotinfo{$which}};
7674: }
7675: return $slotinfo{$which};
1.614 albertel 7676: }
1.31 www 7677: # ------------------------------------------------- Update symbolic store links
7678:
7679: sub symblist {
7680: my ($mapname,%newhash)=@_;
1.438 www 7681: $mapname=&deversion(&declutter($mapname));
1.31 www 7682: my %hash;
1.620 albertel 7683: if (($env{'request.course.fn'}) && (%newhash)) {
7684: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7685: &GDBM_WRCREAT(),0640)) {
1.711 albertel 7686: foreach my $url (keys %newhash) {
7687: next if ($url eq 'last_known'
7688: && $env{'form.no_update_last_known'});
7689: $hash{declutter($url)}=&encode_symb($mapname,
7690: $newhash{$url}->[1],
7691: $newhash{$url}->[0]);
1.191 harris41 7692: }
1.31 www 7693: if (untie(%hash)) {
7694: return 'ok';
7695: }
7696: }
7697: }
7698: return 'error';
1.212 www 7699: }
7700:
7701: # --------------------------------------------------------------- Verify a symb
7702:
7703: sub symbverify {
1.510 www 7704: my ($symb,$thisurl)=@_;
7705: my $thisfn=$thisurl;
1.439 www 7706: $thisfn=&declutter($thisfn);
1.215 www 7707: # direct jump to resource in page or to a sequence - will construct own symbs
7708: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7709: # check URL part
1.409 www 7710: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7711:
1.431 www 7712: unless ($url eq $thisfn) { return 0; }
1.213 www 7713:
1.216 www 7714: $symb=&symbclean($symb);
1.510 www 7715: $thisurl=&deversion($thisurl);
1.439 www 7716: $thisfn=&deversion($thisfn);
1.213 www 7717:
7718: my %bighash;
7719: my $okay=0;
1.431 www 7720:
1.620 albertel 7721: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7722: &GDBM_READER(),0640)) {
1.510 www 7723: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7724: unless ($ids) {
1.510 www 7725: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7726: }
7727: if ($ids) {
7728: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 7729: foreach my $id (split(/\,/,$ids)) {
7730: my ($mapid,$resid)=split(/\./,$id);
1.216 www 7731: if (
7732: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7733: eq $symb) {
1.620 albertel 7734: if (($env{'request.role.adv'}) ||
1.800 albertel 7735: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 7736: $okay=1;
7737: }
7738: }
1.216 www 7739: }
7740: }
1.213 www 7741: untie(%bighash);
7742: }
7743: return $okay;
1.31 www 7744: }
7745:
1.210 www 7746: # --------------------------------------------------------------- Clean-up symb
7747:
7748: sub symbclean {
7749: my $symb=shift;
1.568 albertel 7750: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 7751: # remove version from map
7752: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 7753:
1.210 www 7754: # remove version from URL
7755: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 7756:
1.507 www 7757: # remove wrapper
7758:
1.510 www 7759: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 7760: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 7761: return $symb;
1.409 www 7762: }
7763:
7764: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 7765:
7766: sub encode_symb {
7767: my ($map,$resid,$url)=@_;
7768: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7769: }
1.409 www 7770:
7771: sub decode_symb {
1.568 albertel 7772: my $symb=shift;
7773: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7774: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 7775: return (&fixversion($map),$resid,&fixversion($url));
7776: }
7777:
7778: sub fixversion {
7779: my $fn=shift;
1.609 banghart 7780: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 7781: my %bighash;
7782: my $uri=&clutter($fn);
1.620 albertel 7783: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 7784: # is this cached?
1.599 albertel 7785: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 7786: if (defined($cached)) { return $result; }
7787: # unfortunately not cached, or expired
1.620 albertel 7788: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 7789: &GDBM_READER(),0640)) {
7790: if ($bighash{'version_'.$uri}) {
7791: my $version=$bighash{'version_'.$uri};
1.444 www 7792: unless (($version eq 'mostrecent') ||
7793: ($version==&getversion($uri))) {
1.440 www 7794: $uri=~s/\.(\w+)$/\.$version\.$1/;
7795: }
7796: }
7797: untie %bighash;
1.413 www 7798: }
1.599 albertel 7799: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 7800: }
7801:
7802: sub deversion {
7803: my $url=shift;
7804: $url=~s/\.\d+\.(\w+)$/\.$1/;
7805: return $url;
1.210 www 7806: }
7807:
1.31 www 7808: # ------------------------------------------------------ Return symb list entry
7809:
7810: sub symbread {
1.249 www 7811: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 7812: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 7813: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 7814: # no filename provided? try from environment
1.44 www 7815: unless ($thisfn) {
1.620 albertel 7816: if ($env{'request.symb'}) {
7817: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 7818: }
1.620 albertel 7819: $thisfn=$env{'request.filename'};
1.44 www 7820: }
1.569 albertel 7821: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 7822: # is that filename actually a symb? Verify, clean, and return
7823: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 7824: if (&symbverify($thisfn,$1)) {
1.620 albertel 7825: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 7826: }
1.242 www 7827: }
1.44 www 7828: $thisfn=declutter($thisfn);
1.31 www 7829: my %hash;
1.37 www 7830: my %bighash;
7831: my $syval='';
1.620 albertel 7832: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 7833: my $targetfn = $thisfn;
1.609 banghart 7834: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 7835: $targetfn = 'adm/wrapper/'.$thisfn;
7836: }
1.687 albertel 7837: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7838: $targetfn=$1;
7839: }
1.620 albertel 7840: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7841: &GDBM_READER(),0640)) {
1.481 raeburn 7842: $syval=$hash{$targetfn};
1.37 www 7843: untie(%hash);
7844: }
7845: # ---------------------------------------------------------- There was an entry
7846: if ($syval) {
1.601 albertel 7847: #unless ($syval=~/\_\d+$/) {
1.620 albertel 7848: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 7849: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7850: #return $env{$cache_str}='';
1.601 albertel 7851: #}
7852: #$syval.=$1;
7853: #}
1.37 www 7854: } else {
7855: # ------------------------------------------------------- Was not in symb table
1.620 albertel 7856: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7857: &GDBM_READER(),0640)) {
1.37 www 7858: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 7859: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 7860: unless ($ids) {
7861: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 7862: }
7863: unless ($ids) {
7864: # alias?
7865: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 7866: }
1.37 www 7867: if ($ids) {
7868: # ------------------------------------------------------------------- Has ID(s)
7869: my @possibilities=split(/\,/,$ids);
1.39 www 7870: if ($#possibilities==0) {
7871: # ----------------------------------------------- There is only one possibility
1.37 www 7872: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 7873: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7874: $resid,$thisfn);
1.249 www 7875: } elsif (!$donotrecurse) {
1.39 www 7876: # ------------------------------------------ There is more than one possibility
7877: my $realpossible=0;
1.800 albertel 7878: foreach my $id (@possibilities) {
7879: my $file=$bighash{'src_'.$id};
1.39 www 7880: if (&allowed('bre',$file)) {
1.800 albertel 7881: my ($mapid,$resid)=split(/\./,$id);
1.39 www 7882: if ($bighash{'map_type_'.$mapid} ne 'page') {
7883: $realpossible++;
1.626 albertel 7884: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7885: $resid,$thisfn);
1.39 www 7886: }
7887: }
1.191 harris41 7888: }
1.39 www 7889: if ($realpossible!=1) { $syval=''; }
1.249 www 7890: } else {
7891: $syval='';
1.37 www 7892: }
7893: }
7894: untie(%bighash)
1.481 raeburn 7895: }
1.31 www 7896: }
1.62 www 7897: if ($syval) {
1.620 albertel 7898: return $env{$cache_str}=$syval;
1.62 www 7899: }
1.31 www 7900: }
1.949 raeburn 7901: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7902: return $env{$cache_str}='';
1.31 www 7903: }
7904:
7905: # ---------------------------------------------------------- Return random seed
7906:
1.32 www 7907: sub numval {
7908: my $txt=shift;
7909: $txt=~tr/A-J/0-9/;
7910: $txt=~tr/a-j/0-9/;
7911: $txt=~tr/K-T/0-9/;
7912: $txt=~tr/k-t/0-9/;
7913: $txt=~tr/U-Z/0-5/;
7914: $txt=~tr/u-z/0-5/;
7915: $txt=~s/\D//g;
1.564 albertel 7916: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 7917: return int($txt);
1.368 albertel 7918: }
7919:
1.484 albertel 7920: sub numval2 {
7921: my $txt=shift;
7922: $txt=~tr/A-J/0-9/;
7923: $txt=~tr/a-j/0-9/;
7924: $txt=~tr/K-T/0-9/;
7925: $txt=~tr/k-t/0-9/;
7926: $txt=~tr/U-Z/0-5/;
7927: $txt=~tr/u-z/0-5/;
7928: $txt=~s/\D//g;
7929: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7930: my $total;
7931: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 7932: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 7933: return int($total);
7934: }
7935:
1.575 albertel 7936: sub numval3 {
7937: use integer;
7938: my $txt=shift;
7939: $txt=~tr/A-J/0-9/;
7940: $txt=~tr/a-j/0-9/;
7941: $txt=~tr/K-T/0-9/;
7942: $txt=~tr/k-t/0-9/;
7943: $txt=~tr/U-Z/0-5/;
7944: $txt=~tr/u-z/0-5/;
7945: $txt=~s/\D//g;
7946: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7947: my $total;
7948: foreach my $val (@txts) { $total+=$val; }
7949: if ($_64bit) { $total=(($total<<32)>>32); }
7950: return $total;
7951: }
7952:
1.675 albertel 7953: sub digest {
7954: my ($data)=@_;
7955: my $digest=&Digest::MD5::md5($data);
7956: my ($a,$b,$c,$d)=unpack("iiii",$digest);
7957: my ($e,$f);
7958: {
7959: use integer;
7960: $e=($a+$b);
7961: $f=($c+$d);
7962: if ($_64bit) {
7963: $e=(($e<<32)>>32);
7964: $f=(($f<<32)>>32);
7965: }
7966: }
7967: if (wantarray) {
7968: return ($e,$f);
7969: } else {
7970: my $g;
7971: {
7972: use integer;
7973: $g=($e+$f);
7974: if ($_64bit) {
7975: $g=(($g<<32)>>32);
7976: }
7977: }
7978: return $g;
7979: }
7980: }
7981:
1.368 albertel 7982: sub latest_rnd_algorithm_id {
1.675 albertel 7983: return '64bit5';
1.366 albertel 7984: }
1.32 www 7985:
1.503 albertel 7986: sub get_rand_alg {
7987: my ($courseid)=@_;
1.790 albertel 7988: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 7989: if ($courseid) {
1.620 albertel 7990: return $env{"course.$courseid.rndseed"};
1.503 albertel 7991: }
7992: return &latest_rnd_algorithm_id();
7993: }
7994:
1.562 albertel 7995: sub validCODE {
7996: my ($CODE)=@_;
7997: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7998: return 0;
7999: }
8000:
1.491 albertel 8001: sub getCODE {
1.620 albertel 8002: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 8003: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8004: defined($Apache::lonhomework::parsing_a_task) ) &&
8005: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 8006: return $Apache::lonhomework::history{'resource.CODE'};
8007: }
8008: return undef;
8009: }
8010:
1.31 www 8011: sub rndseed {
1.155 albertel 8012: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8013: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8014: if (!defined($symb)) {
1.366 albertel 8015: unless ($symb=$wsymb) { return time; }
8016: }
8017: if (!$courseid) { $courseid=$wcourseid; }
8018: if (!$domain) { $domain=$wdomain; }
8019: if (!$username) { $username=$wusername }
1.503 albertel 8020: my $which=&get_rand_alg();
1.803 albertel 8021:
1.491 albertel 8022: if (defined(&getCODE())) {
1.675 albertel 8023: if ($which eq '64bit5') {
8024: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8025: } elsif ($which eq '64bit4') {
1.575 albertel 8026: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8027: } else {
8028: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8029: }
1.675 albertel 8030: } elsif ($which eq '64bit5') {
8031: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8032: } elsif ($which eq '64bit4') {
8033: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8034: } elsif ($which eq '64bit3') {
8035: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8036: } elsif ($which eq '64bit2') {
8037: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8038: } elsif ($which eq '64bit') {
8039: return &rndseed_64bit($symb,$courseid,$domain,$username);
8040: }
8041: return &rndseed_32bit($symb,$courseid,$domain,$username);
8042: }
8043:
8044: sub rndseed_32bit {
8045: my ($symb,$courseid,$domain,$username)=@_;
8046: {
8047: use integer;
8048: my $symbchck=unpack("%32C*",$symb) << 27;
8049: my $symbseed=numval($symb) << 22;
8050: my $namechck=unpack("%32C*",$username) << 17;
8051: my $nameseed=numval($username) << 12;
8052: my $domainseed=unpack("%32C*",$domain) << 7;
8053: my $courseseed=unpack("%32C*",$courseid);
8054: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8055: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8056: #&logthis("rndseed :$num:$symb");
1.564 albertel 8057: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8058: return $num;
8059: }
8060: }
8061:
8062: sub rndseed_64bit {
8063: my ($symb,$courseid,$domain,$username)=@_;
8064: {
8065: use integer;
8066: my $symbchck=unpack("%32S*",$symb) << 21;
8067: my $symbseed=numval($symb) << 10;
8068: my $namechck=unpack("%32S*",$username);
8069:
8070: my $nameseed=numval($username) << 21;
8071: my $domainseed=unpack("%32S*",$domain) << 10;
8072: my $courseseed=unpack("%32S*",$courseid);
8073:
8074: my $num1=$symbchck+$symbseed+$namechck;
8075: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8076: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8077: #&logthis("rndseed :$num:$symb");
1.564 albertel 8078: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8079: return "$num1,$num2";
1.155 albertel 8080: }
1.366 albertel 8081: }
8082:
1.443 albertel 8083: sub rndseed_64bit2 {
8084: my ($symb,$courseid,$domain,$username)=@_;
8085: {
8086: use integer;
8087: # strings need to be an even # of cahracters long, it it is odd the
8088: # last characters gets thrown away
8089: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8090: my $symbseed=numval($symb) << 10;
8091: my $namechck=unpack("%32S*",$username.' ');
8092:
8093: my $nameseed=numval($username) << 21;
1.501 albertel 8094: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8095: my $courseseed=unpack("%32S*",$courseid.' ');
8096:
8097: my $num1=$symbchck+$symbseed+$namechck;
8098: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8099: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8100: #&logthis("rndseed :$num:$symb");
1.803 albertel 8101: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8102: return "$num1,$num2";
8103: }
8104: }
8105:
8106: sub rndseed_64bit3 {
8107: my ($symb,$courseid,$domain,$username)=@_;
8108: {
8109: use integer;
8110: # strings need to be an even # of cahracters long, it it is odd the
8111: # last characters gets thrown away
8112: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8113: my $symbseed=numval2($symb) << 10;
8114: my $namechck=unpack("%32S*",$username.' ');
8115:
8116: my $nameseed=numval2($username) << 21;
1.443 albertel 8117: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8118: my $courseseed=unpack("%32S*",$courseid.' ');
8119:
8120: my $num1=$symbchck+$symbseed+$namechck;
8121: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8122: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8123: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8124: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8125:
1.503 albertel 8126: return "$num1:$num2";
1.443 albertel 8127: }
8128: }
8129:
1.575 albertel 8130: sub rndseed_64bit4 {
8131: my ($symb,$courseid,$domain,$username)=@_;
8132: {
8133: use integer;
8134: # strings need to be an even # of cahracters long, it it is odd the
8135: # last characters gets thrown away
8136: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8137: my $symbseed=numval3($symb) << 10;
8138: my $namechck=unpack("%32S*",$username.' ');
8139:
8140: my $nameseed=numval3($username) << 21;
8141: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8142: my $courseseed=unpack("%32S*",$courseid.' ');
8143:
8144: my $num1=$symbchck+$symbseed+$namechck;
8145: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8146: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8147: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 8148: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8149:
8150: return "$num1:$num2";
8151: }
8152: }
8153:
1.675 albertel 8154: sub rndseed_64bit5 {
8155: my ($symb,$courseid,$domain,$username)=@_;
8156: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8157: return "$num1:$num2";
8158: }
8159:
1.366 albertel 8160: sub rndseed_CODE_64bit {
8161: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 8162: {
1.366 albertel 8163: use integer;
1.443 albertel 8164: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 8165: my $symbseed=numval2($symb);
1.491 albertel 8166: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8167: my $CODEseed=numval(&getCODE());
1.443 albertel 8168: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 8169: my $num1=$symbseed+$CODEchck;
8170: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8171: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8172: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 8173: if ($_64bit) { $num1=(($num1<<32)>>32); }
8174: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 8175: return "$num1:$num2";
1.366 albertel 8176: }
8177: }
8178:
1.575 albertel 8179: sub rndseed_CODE_64bit4 {
8180: my ($symb,$courseid,$domain,$username)=@_;
8181: {
8182: use integer;
8183: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8184: my $symbseed=numval3($symb);
8185: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8186: my $CODEseed=numval3(&getCODE());
8187: my $courseseed=unpack("%32S*",$courseid.' ');
8188: my $num1=$symbseed+$CODEchck;
8189: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8190: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8191: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 8192: if ($_64bit) { $num1=(($num1<<32)>>32); }
8193: if ($_64bit) { $num2=(($num2<<32)>>32); }
8194: return "$num1:$num2";
8195: }
8196: }
8197:
1.675 albertel 8198: sub rndseed_CODE_64bit5 {
8199: my ($symb,$courseid,$domain,$username)=@_;
8200: my $code = &getCODE();
8201: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8202: return "$num1:$num2";
8203: }
8204:
1.366 albertel 8205: sub setup_random_from_rndseed {
8206: my ($rndseed)=@_;
1.503 albertel 8207: if ($rndseed =~/([,:])/) {
8208: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 8209: &Math::Random::random_set_seed(abs($num1),abs($num2));
8210: } else {
8211: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 8212: }
1.36 albertel 8213: }
8214:
1.474 albertel 8215: sub latest_receipt_algorithm_id {
1.835 albertel 8216: return 'receipt3';
1.474 albertel 8217: }
8218:
1.480 www 8219: sub recunique {
8220: my $fucourseid=shift;
8221: my $unique;
1.835 albertel 8222: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8223: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8224: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 8225: } else {
8226: $unique=$perlvar{'lonReceipt'};
8227: }
8228: return unpack("%32C*",$unique);
8229: }
8230:
8231: sub recprefix {
8232: my $fucourseid=shift;
8233: my $prefix;
1.835 albertel 8234: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8235: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8236: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 8237: } else {
8238: $prefix=$perlvar{'lonHostID'};
8239: }
8240: return unpack("%32C*",$prefix);
8241: }
8242:
1.76 www 8243: sub ireceipt {
1.474 albertel 8244: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 8245:
8246: my $return =&recprefix($fucourseid).'-';
8247:
8248: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8249: $env{'request.state'} eq 'construct') {
8250: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8251: return $return;
8252: }
8253:
1.76 www 8254: my $cuname=unpack("%32C*",$funame);
8255: my $cudom=unpack("%32C*",$fudom);
8256: my $cucourseid=unpack("%32C*",$fucourseid);
8257: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 8258: my $cunique=&recunique($fucourseid);
1.474 albertel 8259: my $cpart=unpack("%32S*",$part);
1.835 albertel 8260: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8261:
1.790 albertel 8262: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 8263:
8264: $return.= ($cunique%$cuname+
8265: $cunique%$cudom+
8266: $cusymb%$cuname+
8267: $cusymb%$cudom+
8268: $cucourseid%$cuname+
8269: $cucourseid%$cudom+
8270: $cpart%$cuname+
8271: $cpart%$cudom);
8272: } else {
8273: $return.= ($cunique%$cuname+
8274: $cunique%$cudom+
8275: $cusymb%$cuname+
8276: $cusymb%$cudom+
8277: $cucourseid%$cuname+
8278: $cucourseid%$cudom);
8279: }
8280: return $return;
1.76 www 8281: }
8282:
8283: sub receipt {
1.474 albertel 8284: my ($part)=@_;
1.790 albertel 8285: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 8286: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 8287: }
1.260 ng 8288:
1.790 albertel 8289: sub whichuser {
8290: my ($passedsymb)=@_;
8291: my ($symb,$courseid,$domain,$name,$publicuser);
8292: if (defined($env{'form.grade_symb'})) {
8293: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8294: my $allowed=&allowed('vgr',$tmp_courseid);
8295: if (!$allowed &&
8296: exists($env{'request.course.sec'}) &&
8297: $env{'request.course.sec'} !~ /^\s*$/) {
8298: $allowed=&allowed('vgr',$tmp_courseid.
8299: '/'.$env{'request.course.sec'});
8300: }
8301: if ($allowed) {
8302: ($symb)=&get_env_multiple('form.grade_symb');
8303: $courseid=$tmp_courseid;
8304: ($domain)=&get_env_multiple('form.grade_domain');
8305: ($name)=&get_env_multiple('form.grade_username');
8306: return ($symb,$courseid,$domain,$name,$publicuser);
8307: }
8308: }
8309: if (!$passedsymb) {
8310: $symb=&symbread();
8311: } else {
8312: $symb=$passedsymb;
8313: }
8314: $courseid=$env{'request.course.id'};
8315: $domain=$env{'user.domain'};
8316: $name=$env{'user.name'};
8317: if ($name eq 'public' && $domain eq 'public') {
8318: if (!defined($env{'form.username'})) {
8319: $env{'form.username'}.=time.rand(10000000);
8320: }
8321: $name.=$env{'form.username'};
8322: }
8323: return ($symb,$courseid,$domain,$name,$publicuser);
8324:
8325: }
8326:
1.36 albertel 8327: # ------------------------------------------------------------ Serves up a file
1.472 albertel 8328: # returns either the contents of the file or
8329: # -1 if the file doesn't exist
1.481 raeburn 8330: #
8331: # if the target is a file that was uploaded via DOCS,
8332: # a check will be made to see if a current copy exists on the local server,
8333: # if it does this will be served, otherwise a copy will be retrieved from
8334: # the home server for the course and stored in /home/httpd/html/userfiles on
8335: # the local server.
1.472 albertel 8336:
1.36 albertel 8337: sub getfile {
1.538 albertel 8338: my ($file) = @_;
1.609 banghart 8339: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 8340: &repcopy($file);
8341: return &readfile($file);
8342: }
8343:
8344: sub repcopy_userfile {
8345: my ($file)=@_;
1.609 banghart 8346: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 8347: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 8348: my ($cdom,$cnum,$filename) =
1.811 albertel 8349: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 8350: my $uri="/uploaded/$cdom/$cnum/$filename";
8351: if (-e "$file") {
1.828 www 8352: # we already have a local copy, check it out
1.538 albertel 8353: my @fileinfo = stat($file);
1.828 www 8354: my $rtncode;
8355: my $info;
1.538 albertel 8356: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 8357: if ($lwpresp ne 'ok') {
1.828 www 8358: # there is no such file anymore, even though we had a local copy
1.482 albertel 8359: if ($rtncode eq '404') {
1.538 albertel 8360: unlink($file);
1.482 albertel 8361: }
8362: return -1;
8363: }
8364: if ($info < $fileinfo[9]) {
1.828 www 8365: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 8366: return 'ok';
1.828 www 8367: } else {
8368: # the file is outdated, get rid of it
8369: unlink($file);
1.482 albertel 8370: }
1.828 www 8371: }
8372: # one way or the other, at this point, we don't have the file
8373: # construct the correct path for the file
8374: my @parts = ($cdom,$cnum);
8375: if ($filename =~ m|^(.+)/[^/]+$|) {
8376: push @parts, split(/\//,$1);
8377: }
8378: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8379: foreach my $part (@parts) {
8380: $path .= '/'.$part;
8381: if (!-e $path) {
8382: mkdir($path,0770);
1.482 albertel 8383: }
8384: }
1.828 www 8385: # now the path exists for sure
8386: # get a user agent
8387: my $ua=new LWP::UserAgent;
8388: my $transferfile=$file.'.in.transfer';
8389: # FIXME: this should flock
8390: if (-e $transferfile) { return 'ok'; }
8391: my $request;
8392: $uri=~s/^\///;
1.980 raeburn 8393: my $homeserver = &homeserver($cnum,$cdom);
8394: my $protocol = $protocol{$homeserver};
8395: $protocol = 'http' if ($protocol ne 'https');
8396: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 8397: my $response=$ua->request($request,$transferfile);
8398: # did it work?
8399: if ($response->is_error()) {
8400: unlink($transferfile);
8401: &logthis("Userfile repcopy failed for $uri");
8402: return -1;
8403: }
8404: # worked, rename the transfer file
8405: rename($transferfile,$file);
1.607 raeburn 8406: return 'ok';
1.481 raeburn 8407: }
8408:
1.517 albertel 8409: sub tokenwrapper {
8410: my $uri=shift;
1.980 raeburn 8411: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 8412: $uri=~s|^/||;
1.620 albertel 8413: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 8414: my $token=$1;
1.552 albertel 8415: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8416: if ($udom && $uname && $file) {
8417: $file=~s|(\?\.*)*$||;
1.949 raeburn 8418: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 8419: my $homeserver = &homeserver($uname,$udom);
8420: my $protocol = $protocol{$homeserver};
8421: $protocol = 'http' if ($protocol ne 'https');
8422: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 8423: (($uri=~/\?/)?'&':'?').'token='.$token.
8424: '&tokenissued='.$perlvar{'lonHostID'};
8425: } else {
8426: return '/adm/notfound.html';
8427: }
8428: }
8429:
1.828 www 8430: # call with reqtype HEAD: get last modification time
8431: # call with reqtype GET: get the file contents
8432: # Do not call this with reqtype GET for large files! It loads everything into memory
8433: #
1.481 raeburn 8434: sub getuploaded {
8435: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8436: $uri=~s/^\///;
1.980 raeburn 8437: my $homeserver = &homeserver($cnum,$cdom);
8438: my $protocol = $protocol{$homeserver};
8439: $protocol = 'http' if ($protocol ne 'https');
8440: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 8441: my $ua=new LWP::UserAgent;
8442: my $request=new HTTP::Request($reqtype,$uri);
8443: my $response=$ua->request($request);
8444: $$rtncode = $response->code;
1.482 albertel 8445: if (! $response->is_success()) {
8446: return 'failed';
8447: }
8448: if ($reqtype eq 'HEAD') {
1.486 www 8449: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 8450: } elsif ($reqtype eq 'GET') {
8451: $$info = $response->content;
1.472 albertel 8452: }
1.482 albertel 8453: return 'ok';
1.36 albertel 8454: }
8455:
1.481 raeburn 8456: sub readfile {
8457: my $file = shift;
8458: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8459: my $fh;
8460: open($fh,"<$file");
8461: my $a='';
1.800 albertel 8462: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 8463: return $a;
8464: }
8465:
1.36 albertel 8466: sub filelocation {
1.590 banghart 8467: my ($dir,$file) = @_;
8468: my $location;
8469: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 8470:
8471: if ($file =~ m-^/adm/-) {
8472: $file=~s-^/adm/wrapper/-/-;
8473: $file=~s-^/adm/coursedocs/showdoc/-/-;
8474: }
1.882 albertel 8475:
1.590 banghart 8476: if ($file=~m:^/~:) { # is a contruction space reference
8477: $location = $file;
8478: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 8479: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 8480: # is a correct contruction space reference
8481: $location = $file;
1.956 raeburn 8482: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8483: $location = $file;
1.609 banghart 8484: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 8485: my ($udom,$uname,$filename)=
1.811 albertel 8486: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 8487: my $home=&homeserver($uname,$udom);
8488: my $is_me=0;
8489: my @ids=¤t_machine_ids();
8490: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8491: if ($is_me) {
1.955 raeburn 8492: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 8493: } else {
8494: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8495: $udom.'/'.$uname.'/'.$filename;
8496: }
1.882 albertel 8497: } elsif ($file =~ m-^/adm/-) {
8498: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 8499: } else {
8500: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8501: $file=~s:^/res/:/:;
8502: if ( !( $file =~ m:^/:) ) {
8503: $location = $dir. '/'.$file;
8504: } else {
8505: $location = '/home/httpd/html/res'.$file;
8506: }
1.59 albertel 8507: }
1.590 banghart 8508: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 8509: while ($location=~m{/\.\./}) {
8510: if ($location =~ m{/[^/]+/\.\./}) {
8511: $location=~ s{/[^/]+/\.\./}{/}g;
8512: } else {
8513: $location=~ s{/\.\./}{/}g;
8514: }
8515: } #remove dir/..
1.590 banghart 8516: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
8517: return $location;
1.46 www 8518: }
1.36 albertel 8519:
1.46 www 8520: sub hreflocation {
8521: my ($dir,$file)=@_;
1.980 raeburn 8522: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 8523: $file=filelocation($dir,$file);
1.700 albertel 8524: } elsif ($file=~m-^/adm/-) {
8525: $file=~s-^/adm/wrapper/-/-;
8526: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 8527: }
8528: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8529: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 8530: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8531: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 8532: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 8533: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 8534: -/uploaded/$1/$2/-x;
1.46 www 8535: }
1.913 albertel 8536: if ($file=~ m{^/userfiles/}) {
8537: $file =~ s{^/userfiles/}{/uploaded/};
8538: }
1.462 albertel 8539: return $file;
1.465 albertel 8540: }
8541:
8542: sub current_machine_domains {
1.853 albertel 8543: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8544: }
8545:
8546: sub machine_domains {
8547: my ($hostname) = @_;
1.465 albertel 8548: my @domains;
1.838 albertel 8549: my %hostname = &all_hostnames();
1.465 albertel 8550: while( my($id, $name) = each(%hostname)) {
1.467 matthew 8551: # &logthis("-$id-$name-$hostname-");
1.465 albertel 8552: if ($hostname eq $name) {
1.844 albertel 8553: push(@domains,&host_domain($id));
1.465 albertel 8554: }
8555: }
8556: return @domains;
8557: }
8558:
8559: sub current_machine_ids {
1.853 albertel 8560: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8561: }
8562:
8563: sub machine_ids {
8564: my ($hostname) = @_;
8565: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 8566: my @ids;
1.888 albertel 8567: my %name_to_host = &all_names();
1.889 albertel 8568: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
8569: return @{ $name_to_host{$hostname} };
8570: }
8571: return;
1.31 www 8572: }
8573:
1.824 raeburn 8574: sub additional_machine_domains {
8575: my @domains;
8576: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
8577: while( my $line = <$fh>) {
8578: $line =~ s/\s//g;
8579: push(@domains,$line);
8580: }
8581: return @domains;
8582: }
8583:
8584: sub default_login_domain {
8585: my $domain = $perlvar{'lonDefDomain'};
8586: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8587: foreach my $posdom (¤t_machine_domains(),
8588: &additional_machine_domains()) {
8589: if (lc($posdom) eq lc($testdomain)) {
8590: $domain=$posdom;
8591: last;
8592: }
8593: }
8594: return $domain;
8595: }
8596:
1.31 www 8597: # ------------------------------------------------------------- Declutters URLs
8598:
8599: sub declutter {
8600: my $thisfn=shift;
1.569 albertel 8601: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8602: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8603: $thisfn=~s/^\///;
1.697 albertel 8604: $thisfn=~s|^adm/wrapper/||;
8605: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8606: $thisfn=~s/^res\///;
1.235 www 8607: $thisfn=~s/\?.+$//;
1.268 www 8608: return $thisfn;
8609: }
8610:
8611: # ------------------------------------------------------------- Clutter up URLs
8612:
8613: sub clutter {
8614: my $thisfn='/'.&declutter(shift);
1.887 albertel 8615: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8616: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8617: $thisfn='/res'.$thisfn;
8618: }
1.694 albertel 8619: if ($thisfn !~m|/adm|) {
1.695 albertel 8620: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8621: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8622: } else {
8623: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8624: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8625: if ($embstyle eq 'ssi'
8626: || ($embstyle eq 'hdn')
8627: || ($embstyle eq 'rat')
8628: || ($embstyle eq 'prv')
8629: || ($embstyle eq 'ign')) {
8630: #do nothing with these
8631: } elsif (($embstyle eq 'img')
1.695 albertel 8632: || ($embstyle eq 'emb')
8633: || ($embstyle eq 'wrp')) {
8634: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8635: } elsif ($embstyle eq 'unk'
8636: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8637: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8638: } else {
1.718 www 8639: # &logthis("Got a blank emb style");
1.695 albertel 8640: }
1.694 albertel 8641: }
8642: }
1.31 www 8643: return $thisfn;
1.12 www 8644: }
8645:
1.787 albertel 8646: sub clutter_with_no_wrapper {
8647: my $uri = &clutter(shift);
8648: if ($uri =~ m-^/adm/-) {
8649: $uri =~ s-^/adm/wrapper/-/-;
8650: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8651: }
8652: return $uri;
8653: }
8654:
1.557 albertel 8655: sub freeze_escape {
8656: my ($value)=@_;
8657: if (ref($value)) {
8658: $value=&nfreeze($value);
8659: return '__FROZEN__'.&escape($value);
8660: }
8661: return &escape($value);
8662: }
8663:
1.11 www 8664:
1.557 albertel 8665: sub thaw_unescape {
8666: my ($value)=@_;
8667: if ($value =~ /^__FROZEN__/) {
8668: substr($value,0,10,undef);
8669: $value=&unescape($value);
8670: return &thaw($value);
8671: }
8672: return &unescape($value);
8673: }
8674:
1.436 albertel 8675: sub correct_line_ends {
8676: my ($result)=@_;
8677: $$result =~s/\r\n/\n/mg;
8678: $$result =~s/\r/\n/mg;
1.415 albertel 8679: }
1.1 albertel 8680: # ================================================================ Main Program
8681:
1.184 www 8682: sub goodbye {
1.204 albertel 8683: &logthis("Starting Shut down");
1.443 albertel 8684: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8685: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8686: #converted
1.599 albertel 8687: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8688: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8689: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8690: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8691: #1.1 only
1.870 albertel 8692: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8693: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8694: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8695: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8696: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8697: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8698: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8699: &flushcourselogs();
8700: &logthis("Shutting down");
8701: }
8702:
1.852 albertel 8703: sub get_dns {
1.869 albertel 8704: my ($url,$func,$ignore_cache) = @_;
8705: if (!$ignore_cache) {
8706: my ($content,$cached)=
8707: &Apache::lonnet::is_cached_new('dns',$url);
8708: if ($cached) {
8709: &$func($content);
8710: return;
8711: }
8712: }
8713:
8714: my %alldns;
1.852 albertel 8715: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8716: foreach my $dns (<$config>) {
8717: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 8718: my $line = $1;
8719: my ($host,$protocol) = split(/:/,$line);
8720: if ($protocol ne 'https') {
8721: $protocol = 'http';
8722: }
8723: $alldns{$host} = $protocol;
1.869 albertel 8724: }
8725: while (%alldns) {
8726: my ($dns) = keys(%alldns);
1.852 albertel 8727: my $ua=new LWP::UserAgent;
1.979 raeburn 8728: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 8729: my $response=$ua->request($request);
1.979 raeburn 8730: delete($alldns{$dns});
1.852 albertel 8731: next if ($response->is_error());
8732: my @content = split("\n",$response->content);
1.869 albertel 8733: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 8734: &$func(\@content);
1.869 albertel 8735: return;
1.852 albertel 8736: }
8737: close($config);
1.871 albertel 8738: my $which = (split('/',$url))[3];
8739: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8740: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 8741: my @content = <$config>;
8742: &$func(\@content);
8743: return;
1.852 albertel 8744: }
1.327 albertel 8745: # ------------------------------------------------------------ Read domain file
8746: {
1.852 albertel 8747: my $loaded;
1.846 albertel 8748: my %domain;
8749:
1.852 albertel 8750: sub parse_domain_tab {
8751: my ($lines) = @_;
8752: foreach my $line (@$lines) {
8753: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 8754:
1.846 albertel 8755: chomp($line);
1.852 albertel 8756: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 8757: my %this_domain;
8758: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8759: 'lang_def', 'city', 'longi', 'lati',
8760: 'primary') {
8761: $this_domain{$field} = shift(@elements);
8762: }
8763: $domain{$name} = \%this_domain;
1.852 albertel 8764: }
8765: }
1.864 albertel 8766:
8767: sub reset_domain_info {
8768: undef($loaded);
8769: undef(%domain);
8770: }
8771:
1.852 albertel 8772: sub load_domain_tab {
1.869 albertel 8773: my ($ignore_cache) = @_;
8774: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 8775: my $fh;
8776: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8777: my @lines = <$fh>;
8778: &parse_domain_tab(\@lines);
1.448 albertel 8779: }
1.852 albertel 8780: close($fh);
8781: $loaded = 1;
1.327 albertel 8782: }
1.846 albertel 8783:
8784: sub domain {
1.852 albertel 8785: &load_domain_tab() if (!$loaded);
8786:
1.846 albertel 8787: my ($name,$what) = @_;
8788: return if ( !exists($domain{$name}) );
8789:
8790: if (!$what) {
8791: return $domain{$name}{'description'};
8792: }
8793: return $domain{$name}{$what};
8794: }
1.974 raeburn 8795:
8796: sub domain_info {
8797: &load_domain_tab() if (!$loaded);
8798: return %domain;
8799: }
8800:
1.327 albertel 8801: }
8802:
8803:
1.1 albertel 8804: # ------------------------------------------------------------- Read hosts file
8805: {
1.838 albertel 8806: my %hostname;
1.844 albertel 8807: my %hostdom;
1.845 albertel 8808: my %libserv;
1.852 albertel 8809: my $loaded;
1.888 albertel 8810: my %name_to_host;
1.852 albertel 8811:
8812: sub parse_hosts_tab {
8813: my ($file) = @_;
8814: foreach my $configline (@$file) {
8815: next if ($configline =~ /^(\#|\s*$ )/x);
8816: next if ($configline =~ /^\^/);
8817: chomp($configline);
1.968 raeburn 8818: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 8819: $name=~s/\s//g;
8820: if ($id && $domain && $role && $name) {
8821: $hostname{$id}=$name;
1.888 albertel 8822: push(@{$name_to_host{$name}}, $id);
1.852 albertel 8823: $hostdom{$id}=$domain;
8824: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 8825: if (defined($protocol)) {
8826: if ($protocol eq 'https') {
8827: $protocol{$id} = $protocol;
8828: } else {
8829: $protocol{$id} = 'http';
8830: }
1.968 raeburn 8831: } else {
1.969 raeburn 8832: $protocol{$id} = 'http';
1.968 raeburn 8833: }
1.852 albertel 8834: }
8835: }
8836: }
1.864 albertel 8837:
8838: sub reset_hosts_info {
1.897 albertel 8839: &purge_remembered();
1.864 albertel 8840: &reset_domain_info();
8841: &reset_hosts_ip_info();
1.892 albertel 8842: undef(%name_to_host);
1.864 albertel 8843: undef(%hostname);
8844: undef(%hostdom);
8845: undef(%libserv);
8846: undef($loaded);
8847: }
1.1 albertel 8848:
1.852 albertel 8849: sub load_hosts_tab {
1.869 albertel 8850: my ($ignore_cache) = @_;
8851: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 8852: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8853: my @config = <$config>;
8854: &parse_hosts_tab(\@config);
8855: close($config);
8856: $loaded=1;
1.1 albertel 8857: }
1.852 albertel 8858:
1.838 albertel 8859: sub hostname {
1.852 albertel 8860: &load_hosts_tab() if (!$loaded);
8861:
1.838 albertel 8862: my ($lonid) = @_;
8863: return $hostname{$lonid};
8864: }
1.845 albertel 8865:
1.838 albertel 8866: sub all_hostnames {
1.852 albertel 8867: &load_hosts_tab() if (!$loaded);
8868:
1.838 albertel 8869: return %hostname;
8870: }
1.845 albertel 8871:
1.888 albertel 8872: sub all_names {
8873: &load_hosts_tab() if (!$loaded);
8874:
8875: return %name_to_host;
8876: }
8877:
1.974 raeburn 8878: sub all_host_domain {
8879: &load_hosts_tab() if (!$loaded);
8880: return %hostdom;
8881: }
8882:
1.845 albertel 8883: sub is_library {
1.852 albertel 8884: &load_hosts_tab() if (!$loaded);
8885:
1.845 albertel 8886: return exists($libserv{$_[0]});
8887: }
8888:
8889: sub all_library {
1.852 albertel 8890: &load_hosts_tab() if (!$loaded);
8891:
1.845 albertel 8892: return %libserv;
8893: }
8894:
1.841 albertel 8895: sub get_servers {
1.852 albertel 8896: &load_hosts_tab() if (!$loaded);
8897:
1.841 albertel 8898: my ($domain,$type) = @_;
8899: my %possible_hosts = ($type eq 'library') ? %libserv
8900: : %hostname;
8901: my %result;
1.842 albertel 8902: if (ref($domain) eq 'ARRAY') {
8903: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 8904: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 8905: $result{$host} = $hostname;
8906: }
8907: }
8908: } else {
8909: while ( my ($host,$hostname) = each(%possible_hosts)) {
8910: if ($hostdom{$host} eq $domain) {
8911: $result{$host} = $hostname;
8912: }
1.841 albertel 8913: }
8914: }
8915: return %result;
8916: }
1.845 albertel 8917:
1.844 albertel 8918: sub host_domain {
1.852 albertel 8919: &load_hosts_tab() if (!$loaded);
8920:
1.844 albertel 8921: my ($lonid) = @_;
8922: return $hostdom{$lonid};
8923: }
8924:
1.841 albertel 8925: sub all_domains {
1.852 albertel 8926: &load_hosts_tab() if (!$loaded);
8927:
1.841 albertel 8928: my %seen;
8929: my @uniq = grep(!$seen{$_}++, values(%hostdom));
8930: return @uniq;
8931: }
1.1 albertel 8932: }
8933:
1.847 albertel 8934: {
8935: my %iphost;
1.856 albertel 8936: my %name_to_ip;
8937: my %lonid_to_ip;
1.869 albertel 8938:
1.847 albertel 8939: sub get_hosts_from_ip {
8940: my ($ip) = @_;
8941: my %iphosts = &get_iphost();
8942: if (ref($iphosts{$ip})) {
8943: return @{$iphosts{$ip}};
8944: }
8945: return;
1.839 albertel 8946: }
1.864 albertel 8947:
8948: sub reset_hosts_ip_info {
8949: undef(%iphost);
8950: undef(%name_to_ip);
8951: undef(%lonid_to_ip);
8952: }
1.856 albertel 8953:
8954: sub get_host_ip {
8955: my ($lonid) = @_;
8956: if (exists($lonid_to_ip{$lonid})) {
8957: return $lonid_to_ip{$lonid};
8958: }
8959: my $name=&hostname($lonid);
8960: my $ip = gethostbyname($name);
8961: return if (!$ip || length($ip) ne 4);
8962: $ip=inet_ntoa($ip);
8963: $name_to_ip{$name} = $ip;
8964: $lonid_to_ip{$lonid} = $ip;
8965: return $ip;
8966: }
1.847 albertel 8967:
8968: sub get_iphost {
1.869 albertel 8969: my ($ignore_cache) = @_;
1.894 albertel 8970:
1.869 albertel 8971: if (!$ignore_cache) {
8972: if (%iphost) {
8973: return %iphost;
8974: }
8975: my ($ip_info,$cached)=
8976: &Apache::lonnet::is_cached_new('iphost','iphost');
8977: if ($cached) {
8978: %iphost = %{$ip_info->[0]};
8979: %name_to_ip = %{$ip_info->[1]};
8980: %lonid_to_ip = %{$ip_info->[2]};
8981: return %iphost;
8982: }
8983: }
1.894 albertel 8984:
8985: # get yesterday's info for fallback
8986: my %old_name_to_ip;
8987: my ($ip_info,$cached)=
8988: &Apache::lonnet::is_cached_new('iphost','iphost');
8989: if ($cached) {
8990: %old_name_to_ip = %{$ip_info->[1]};
8991: }
8992:
1.888 albertel 8993: my %name_to_host = &all_names();
8994: foreach my $name (keys(%name_to_host)) {
1.847 albertel 8995: my $ip;
8996: if (!exists($name_to_ip{$name})) {
8997: $ip = gethostbyname($name);
8998: if (!$ip || length($ip) ne 4) {
1.894 albertel 8999: if (defined($old_name_to_ip{$name})) {
9000: $ip = $old_name_to_ip{$name};
9001: &logthis("Can't find $name defaulting to old $ip");
9002: } else {
9003: &logthis("Name $name no IP found");
9004: next;
9005: }
9006: } else {
9007: $ip=inet_ntoa($ip);
1.847 albertel 9008: }
9009: $name_to_ip{$name} = $ip;
9010: } else {
9011: $ip = $name_to_ip{$name};
1.653 albertel 9012: }
1.888 albertel 9013: foreach my $id (@{ $name_to_host{$name} }) {
9014: $lonid_to_ip{$id} = $ip;
9015: }
9016: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9017: }
1.869 albertel 9018: &Apache::lonnet::do_cache_new('iphost','iphost',
9019: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9020: 48*60*60);
1.869 albertel 9021:
1.847 albertel 9022: return %iphost;
1.598 albertel 9023: }
9024: }
9025:
1.986 foxr 9026: #
9027: # Given a DNS returns the loncapa host name for that DNS
9028: #
9029: sub host_from_dns {
9030: my ($dns) = @_;
9031: my @hosts;
9032: my $ip;
9033:
9034: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9035: if (length($ip) == 4) {
9036: $ip = &IO::Socket::inet_ntoa($ip);
9037: @hosts = get_hosts_from_ip($ip);
9038: return $hosts[0];
9039: }
9040: return undef;
9041: }
9042:
1.862 albertel 9043: BEGIN {
9044:
9045: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9046: unless ($readit) {
9047: {
9048: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9049: %perlvar = (%perlvar,%{$configvars});
9050: }
9051:
9052:
1.1 albertel 9053: # ------------------------------------------------------ Read spare server file
9054: {
1.448 albertel 9055: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9056:
9057: while (my $configline=<$config>) {
9058: chomp($configline);
1.284 matthew 9059: if ($configline) {
1.784 albertel 9060: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9061: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9062: push(@{ $spareid{$type} }, $host);
1.1 albertel 9063: }
9064: }
1.448 albertel 9065: close($config);
1.1 albertel 9066: }
1.11 www 9067: # ------------------------------------------------------------ Read permissions
9068: {
1.448 albertel 9069: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9070:
9071: while (my $configline=<$config>) {
1.448 albertel 9072: chomp($configline);
9073: if ($configline) {
9074: my ($role,$perm)=split(/ /,$configline);
9075: if ($perm ne '') { $pr{$role}=$perm; }
9076: }
1.11 www 9077: }
1.448 albertel 9078: close($config);
1.11 www 9079: }
9080:
9081: # -------------------------------------------- Read plain texts for permissions
9082: {
1.448 albertel 9083: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9084:
9085: while (my $configline=<$config>) {
1.448 albertel 9086: chomp($configline);
9087: if ($configline) {
1.742 raeburn 9088: my ($short,@plain)=split(/:/,$configline);
9089: %{$prp{$short}} = ();
9090: if (@plain > 0) {
9091: $prp{$short}{'std'} = $plain[0];
9092: for (my $i=1; $i<@plain; $i++) {
9093: $prp{$short}{'alt'.$i} = $plain[$i];
9094: }
9095: }
1.448 albertel 9096: }
1.135 www 9097: }
1.448 albertel 9098: close($config);
1.135 www 9099: }
9100:
9101: # ---------------------------------------------------------- Read package table
9102: {
1.448 albertel 9103: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9104:
9105: while (my $configline=<$config>) {
1.483 albertel 9106: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9107: chomp($configline);
9108: my ($short,$plain)=split(/:/,$configline);
9109: my ($pack,$name)=split(/\&/,$short);
9110: if ($plain ne '') {
9111: $packagetab{$pack.'&'.$name.'&name'}=$name;
9112: $packagetab{$short}=$plain;
9113: }
1.11 www 9114: }
1.448 albertel 9115: close($config);
1.329 matthew 9116: }
9117:
9118: # ------------- set up temporary directory
9119: {
9120: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9121:
1.11 www 9122: }
9123:
1.794 albertel 9124: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9125: 'compress_threshold'=> 20_000,
9126: });
1.185 www 9127:
1.281 www 9128: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 9129: $dumpcount=0;
1.958 www 9130: $locknum=0;
1.22 www 9131:
1.163 harris41 9132: &logtouch();
1.672 albertel 9133: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 9134: $readit=1;
1.564 albertel 9135: {
9136: use integer;
9137: my $test=(2**32)+1;
1.568 albertel 9138: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 9139: &logthis(" Detected 64bit platform ($_64bit)");
9140: }
1.195 www 9141: }
1.1 albertel 9142: }
1.179 www 9143:
1.1 albertel 9144: 1;
1.191 harris41 9145: __END__
9146:
1.243 albertel 9147: =pod
9148:
1.191 harris41 9149: =head1 NAME
9150:
1.243 albertel 9151: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 9152:
9153: =head1 SYNOPSIS
9154:
1.243 albertel 9155: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 9156:
9157: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9158:
1.243 albertel 9159: Common parameters:
9160:
9161: =over 4
9162:
9163: =item *
9164:
9165: $uname : an internal username (if $cname expecting a course Id specifically)
9166:
9167: =item *
9168:
9169: $udom : a domain (if $cdom expecting a course's domain specifically)
9170:
9171: =item *
9172:
9173: $symb : a resource instance identifier
9174:
9175: =item *
9176:
9177: $namespace : the name of a .db file that contains the data needed or
9178: being set.
9179:
9180: =back
9181:
1.394 bowersj2 9182: =head1 OVERVIEW
1.191 harris41 9183:
1.394 bowersj2 9184: lonnet provides subroutines which interact with the
9185: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9186: about classes, users, and resources.
1.243 albertel 9187:
9188: For many of these objects you can also use this to store data about
9189: them or modify them in various ways.
1.191 harris41 9190:
1.394 bowersj2 9191: =head2 Symbs
1.191 harris41 9192:
1.394 bowersj2 9193: To identify a specific instance of a resource, LON-CAPA uses symbols
9194: or "symbs"X<symb>. These identifiers are built from the URL of the
9195: map, the resource number of the resource in the map, and the URL of
9196: the resource itself. The latter is somewhat redundant, but might help
9197: if maps change.
9198:
9199: An example is
9200:
9201: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9202:
9203: The respective map entry is
9204:
9205: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9206: title="Problem 2">
9207: </resource>
9208:
9209: Symbs are used by the random number generator, as well as to store and
9210: restore data specific to a certain instance of for example a problem.
9211:
9212: =head2 Storing And Retrieving Data
9213:
9214: X<store()>X<cstore()>X<restore()>Three of the most important functions
9215: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9216: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9217: is is the non-critical message twin of cstore. These functions are for
9218: handlers to store a perl hash to a user's permanent data space in an
9219: easy manner, and to retrieve it again on another call. It is expected
9220: that a handler would use this once at the beginning to retrieve data,
9221: and then again once at the end to send only the new data back.
9222:
9223: The data is stored in the user's data directory on the user's
9224: homeserver under the ID of the course.
9225:
9226: The hash that is returned by restore will have all of the previous
9227: value for all of the elements of the hash.
9228:
9229: Example:
9230:
9231: #creating a hash
9232: my %hash;
9233: $hash{'foo'}='bar';
9234:
9235: #storing it
9236: &Apache::lonnet::cstore(\%hash);
9237:
9238: #changing a value
9239: $hash{'foo'}='notbar';
9240:
9241: #adding a new value
9242: $hash{'bar'}='foo';
9243: &Apache::lonnet::cstore(\%hash);
9244:
9245: #retrieving the hash
9246: my %history=&Apache::lonnet::restore();
9247:
9248: #print the hash
9249: foreach my $key (sort(keys(%history))) {
9250: print("\%history{$key} = $history{$key}");
9251: }
9252:
9253: Will print out:
1.191 harris41 9254:
1.394 bowersj2 9255: %history{1:foo} = bar
9256: %history{1:keys} = foo:timestamp
9257: %history{1:timestamp} = 990455579
9258: %history{2:bar} = foo
9259: %history{2:foo} = notbar
9260: %history{2:keys} = foo:bar:timestamp
9261: %history{2:timestamp} = 990455580
9262: %history{bar} = foo
9263: %history{foo} = notbar
9264: %history{timestamp} = 990455580
9265: %history{version} = 2
9266:
9267: Note that the special hash entries C<keys>, C<version> and
9268: C<timestamp> were added to the hash. C<version> will be equal to the
9269: total number of versions of the data that have been stored. The
9270: C<timestamp> attribute will be the UNIX time the hash was
9271: stored. C<keys> is available in every historical section to list which
9272: keys were added or changed at a specific historical revision of a
9273: hash.
9274:
9275: B<Warning>: do not store the hash that restore returns directly. This
9276: will cause a mess since it will restore the historical keys as if the
9277: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 9278:
1.394 bowersj2 9279: Calling convention:
1.191 harris41 9280:
1.394 bowersj2 9281: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9282: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 9283:
1.394 bowersj2 9284: For more detailed information, see lonnet specific documentation.
1.191 harris41 9285:
1.394 bowersj2 9286: =head1 RETURN MESSAGES
1.191 harris41 9287:
1.394 bowersj2 9288: =over 4
1.191 harris41 9289:
1.394 bowersj2 9290: =item * B<con_lost>: unable to contact remote host
1.191 harris41 9291:
1.394 bowersj2 9292: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9293: when the connection is brought back up
1.191 harris41 9294:
1.394 bowersj2 9295: =item * B<con_failed>: unable to contact remote host and unable to save message
9296: for later delivery
1.191 harris41 9297:
1.967 bisitz 9298: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 9299:
1.394 bowersj2 9300: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 9301: that was requested
1.191 harris41 9302:
1.243 albertel 9303: =back
1.191 harris41 9304:
1.243 albertel 9305: =head1 PUBLIC SUBROUTINES
1.191 harris41 9306:
1.243 albertel 9307: =head2 Session Environment Functions
1.191 harris41 9308:
1.243 albertel 9309: =over 4
1.191 harris41 9310:
1.394 bowersj2 9311: =item *
9312: X<appenv()>
1.949 raeburn 9313: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 9314: the user envirnoment file, and will be restored for each access this
1.620 albertel 9315: user makes during this session, also modifies the %env for the current
1.949 raeburn 9316: process. Optional rolesarrayref - if defined contains a reference to an array
9317: of roles which are exempt from the restriction on modifying user.role entries
9318: in the user's environment.db and in %env.
1.191 harris41 9319:
9320: =item *
1.394 bowersj2 9321: X<delenv()>
1.987 raeburn 9322: B<delenv($delthis,$regexp)>: removes all items from the session
9323: environment file that begin with $delthis. If the
9324: optional second arg - $regexp - is true, $delthis is treated as a
9325: regular expression, otherwise \Q$delthis\E is used.
9326: The values are also deleted from the current processes %env.
1.191 harris41 9327:
1.795 albertel 9328: =item * get_env_multiple($name)
9329:
9330: gets $name from the %env hash, it seemlessly handles the cases where multiple
9331: values may be defined and end up as an array ref.
9332:
9333: returns an array of values
9334:
1.243 albertel 9335: =back
9336:
9337: =head2 User Information
1.191 harris41 9338:
1.243 albertel 9339: =over 4
1.191 harris41 9340:
9341: =item *
1.394 bowersj2 9342: X<queryauthenticate()>
9343: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 9344: authentication scheme
9345:
9346: =item *
1.394 bowersj2 9347: X<authenticate()>
9348: B<authenticate($uname,$upass,$udom)>: try to
9349: authenticate user from domain's lib servers (first use the current
9350: one). C<$upass> should be the users password.
1.191 harris41 9351:
9352: =item *
1.394 bowersj2 9353: X<homeserver()>
9354: B<homeserver($uname,$udom)>: find the server which has
9355: the user's directory and files (there must be only one), this caches
9356: the answer, and also caches if there is a borken connection.
1.191 harris41 9357:
9358: =item *
1.394 bowersj2 9359: X<idget()>
9360: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9361: (IDs are a unique resource in a domain, there must be only 1 ID per
9362: username, and only 1 username per ID in a specific domain) (returns
9363: hash: id=>name,id=>name)
1.191 harris41 9364:
9365: =item *
1.394 bowersj2 9366: X<idrget()>
9367: B<idrget($udom,@unames)>: find the IDs behind a list of
9368: usernames (returns hash: name=>id,name=>id)
1.191 harris41 9369:
9370: =item *
1.394 bowersj2 9371: X<idput()>
9372: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 9373:
9374: =item *
1.394 bowersj2 9375: X<rolesinit()>
9376: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 9377:
9378: =item *
1.551 albertel 9379: X<getsection()>
9380: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 9381: course $cname, return section name/number or '' for "not in course"
9382: and '-1' for "no section"
9383:
9384: =item *
1.394 bowersj2 9385: X<userenvironment()>
9386: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 9387: passed in @what from the requested user's environment, returns a hash
9388:
1.858 raeburn 9389: =item *
9390: X<userlog_query()>
1.859 albertel 9391: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9392: activity.log file. %filters defines filters applied when parsing the
9393: log file. These can be start or end timestamps, or the type of action
9394: - log to look for Login or Logout events, check for Checkin or
9395: Checkout, role for role selection. The response is in the form
9396: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9397: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 9398:
1.243 albertel 9399: =back
9400:
9401: =head2 User Roles
9402:
9403: =over 4
9404:
9405: =item *
9406:
1.810 raeburn 9407: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 9408: F: full access
9409: U,I,K: authentication modes (cxx only)
9410: '': forbidden
9411: 1: user needs to choose course
9412: 2: browse allowed
1.766 albertel 9413: A: passphrase authentication needed
1.243 albertel 9414:
9415: =item *
9416:
9417: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9418: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9419: and course level
9420:
9421: =item *
9422:
1.988 ! raeburn 9423: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
! 9424: (rolesplain.tab); plain text explanation of a user role term.
! 9425: $type is Course (default) or Group.
! 9426: If $forcedefault evaluates to true, text returned will be default
! 9427: text for $type. Otherwise, if this is a course, the text returned
! 9428: will be a custom name for the role (if defined in the course's
! 9429: environment). If no custom name is defined the default is returned.
! 9430:
1.832 raeburn 9431: =item *
9432:
1.935 raeburn 9433: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 9434: All arguments are optional. Returns a hash of a roles, either for
9435: co-author/assistant author roles for a user's Construction Space
1.906 albertel 9436: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 9437: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9438: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9439: For each key, value is set to colon-separated start and end times for
9440: the role. If no username and domain are specified, will default to
1.934 raeburn 9441: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 9442: of role statuses (active, future or previous), roles
9443: (e.g., cc,in, st etc.) and domains of the roles which can be used
9444: to restrict the list of roles reported. If no array ref is
9445: provided for types, will default to return only active roles.
1.834 albertel 9446:
1.243 albertel 9447: =back
9448:
9449: =head2 User Modification
9450:
9451: =over 4
9452:
9453: =item *
9454:
1.957 raeburn 9455: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 9456: user for the level given by URL. Optional start and end dates (leave empty
9457: string or zero for "no date")
1.191 harris41 9458:
9459: =item *
9460:
1.243 albertel 9461: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9462: change a users, password, possible return values are: ok,
9463: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9464: refused
1.191 harris41 9465:
9466: =item *
9467:
1.243 albertel 9468: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 9469:
9470: =item *
9471:
1.963 raeburn 9472: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9473: $forceid,$desiredhome,$email,$inststatus) :
1.243 albertel 9474: modify user
1.191 harris41 9475:
9476: =item *
9477:
1.286 matthew 9478: modifystudent
9479:
1.957 raeburn 9480: modify a student's enrollment and identification information.
1.286 matthew 9481: The course id is resolved based on the current users environment.
9482: This means the envoking user must be a course coordinator or otherwise
9483: associated with a course.
9484:
1.297 matthew 9485: This call is essentially a wrapper for lonnet::modifyuser and
9486: lonnet::modify_student_enrollment
1.286 matthew 9487:
9488: Inputs:
9489:
9490: =over 4
9491:
1.957 raeburn 9492: =item B<$udom> Student's loncapa domain
1.286 matthew 9493:
1.957 raeburn 9494: =item B<$uname> Student's loncapa login name
1.286 matthew 9495:
1.964 bisitz 9496: =item B<$uid> Student/Employee ID
1.286 matthew 9497:
1.957 raeburn 9498: =item B<$umode> Student's authentication mode
1.286 matthew 9499:
1.957 raeburn 9500: =item B<$upass> Student's password
1.286 matthew 9501:
1.957 raeburn 9502: =item B<$first> Student's first name
1.286 matthew 9503:
1.957 raeburn 9504: =item B<$middle> Student's middle name
1.286 matthew 9505:
1.957 raeburn 9506: =item B<$last> Student's last name
1.286 matthew 9507:
1.957 raeburn 9508: =item B<$gene> Student's generation
1.286 matthew 9509:
1.957 raeburn 9510: =item B<$usec> Student's section in course
1.286 matthew 9511:
9512: =item B<$end> Unix time of the roles expiration
9513:
9514: =item B<$start> Unix time of the roles start date
9515:
9516: =item B<$forceid> If defined, allow $uid to be changed
9517:
9518: =item B<$desiredhome> server to use as home server for student
9519:
1.957 raeburn 9520: =item B<$email> Student's permanent e-mail address
9521:
9522: =item B<$type> Type of enrollment (auto or manual)
9523:
1.963 raeburn 9524: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
9525:
9526: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 9527:
1.963 raeburn 9528: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 9529:
1.963 raeburn 9530: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 9531:
1.963 raeburn 9532: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 9533:
1.286 matthew 9534: =back
1.297 matthew 9535:
9536: =item *
9537:
9538: modify_student_enrollment
9539:
9540: Change a students enrollment status in a class. The environment variable
9541: 'role.request.course' must be defined for this function to proceed.
9542:
9543: Inputs:
9544:
9545: =over 4
9546:
9547: =item $udom, students domain
9548:
9549: =item $uname, students name
9550:
9551: =item $uid, students user id
9552:
9553: =item $first, students first name
9554:
9555: =item $middle
9556:
9557: =item $last
9558:
9559: =item $gene
9560:
9561: =item $usec
9562:
9563: =item $end
9564:
9565: =item $start
9566:
1.957 raeburn 9567: =item $type
9568:
9569: =item $locktype
9570:
9571: =item $cid
9572:
9573: =item $selfenroll
9574:
9575: =item $context
9576:
1.297 matthew 9577: =back
9578:
1.191 harris41 9579:
9580: =item *
9581:
1.243 albertel 9582: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
9583: custom role; give a custom role to a user for the level given by URL. Specify
9584: name and domain of role author, and role name
1.191 harris41 9585:
9586: =item *
9587:
1.243 albertel 9588: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 9589:
9590: =item *
9591:
1.243 albertel 9592: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
9593:
9594: =back
9595:
9596: =head2 Course Infomation
9597:
9598: =over 4
1.191 harris41 9599:
9600: =item *
9601:
1.631 albertel 9602: coursedescription($courseid) : returns a hash of information about the
9603: specified course id, including all environment settings for the
9604: course, the description of the course will be in the hash under the
9605: key 'description'
1.191 harris41 9606:
9607: =item *
9608:
1.624 albertel 9609: resdata($name,$domain,$type,@which) : request for current parameter
9610: setting for a specific $type, where $type is either 'course' or 'user',
9611: @what should be a list of parameters to ask about. This routine caches
9612: answers for 5 minutes.
1.243 albertel 9613:
1.877 foxr 9614: =item *
9615:
9616: get_courseresdata($courseid, $domain) : dump the entire course resource
9617: data base, returning a hash that is keyed by the resource name and has
9618: values that are the resource value. I believe that the timestamps and
9619: versions are also returned.
9620:
9621:
1.243 albertel 9622: =back
9623:
9624: =head2 Course Modification
9625:
9626: =over 4
1.191 harris41 9627:
9628: =item *
9629:
1.243 albertel 9630: writecoursepref($courseid,%prefs) : write preferences (environment
9631: database) for a course
1.191 harris41 9632:
9633: =item *
9634:
1.243 albertel 9635: createcourse($udom,$description,$url) : make/modify course
9636:
9637: =back
9638:
9639: =head2 Resource Subroutines
9640:
9641: =over 4
1.191 harris41 9642:
9643: =item *
9644:
1.243 albertel 9645: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 9646:
9647: =item *
9648:
1.243 albertel 9649: repcopy($filename) : subscribes to the requested file, and attempts to
9650: replicate from the owning library server, Might return
1.607 raeburn 9651: 'unavailable', 'not_found', 'forbidden', 'ok', or
9652: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 9653: resource. Expects the local filesystem pathname
9654: (/home/httpd/html/res/....)
9655:
9656: =back
9657:
9658: =head2 Resource Information
9659:
9660: =over 4
1.191 harris41 9661:
9662: =item *
9663:
1.243 albertel 9664: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9665: a vairety of different possible values, $varname should be a request
9666: string, and the other parameters can be used to specify who and what
9667: one is asking about.
9668:
9669: Possible values for $varname are environment.lastname (or other item
9670: from the envirnment hash), user.name (or someother aspect about the
9671: user), resource.0.maxtries (or some other part and parameter of a
9672: resource)
1.204 albertel 9673:
9674: =item *
9675:
1.243 albertel 9676: directcondval($number) : get current value of a condition; reads from a state
9677: string
1.204 albertel 9678:
9679: =item *
9680:
1.243 albertel 9681: condval($condidx) : value of condition index based on state
1.204 albertel 9682:
9683: =item *
9684:
1.243 albertel 9685: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9686: resource's metadata, $what should be either a specific key, or either
9687: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9688: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9689:
9690: this function automatically caches all requests
1.191 harris41 9691:
9692: =item *
9693:
1.243 albertel 9694: metadata_query($query,$custom,$customshow) : make a metadata query against the
9695: network of library servers; returns file handle of where SQL and regex results
9696: will be stored for query
1.191 harris41 9697:
9698: =item *
9699:
1.243 albertel 9700: symbread($filename) : return symbolic list entry (filename argument optional);
9701: returns the data handle
1.191 harris41 9702:
9703: =item *
9704:
1.243 albertel 9705: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9706: a possible symb for the URL in $thisfn, and if is an encryypted
9707: resource that the user accessed using /enc/ returns a 1 on success, 0
9708: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9709: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9710:
1.191 harris41 9711:
9712: =item *
9713:
1.243 albertel 9714: symbclean($symb) : removes versions numbers from a symb, returns the
9715: cleaned symb
1.191 harris41 9716:
9717: =item *
9718:
1.243 albertel 9719: is_on_map($uri) : checks if the $uri is somewhere on the current
9720: course map, user must be in a course for it to work.
1.191 harris41 9721:
9722: =item *
9723:
1.243 albertel 9724: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 9725:
9726: =item *
9727:
1.243 albertel 9728: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9729: a random seed, all arguments are optional, if they aren't sent it uses the
9730: environment to derive them. Note: if symb isn't sent and it can't get one
9731: from &symbread it will use the current time as its return value
1.191 harris41 9732:
9733: =item *
9734:
1.243 albertel 9735: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9736: unfakeable, receipt
1.191 harris41 9737:
9738: =item *
9739:
1.620 albertel 9740: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 9741:
9742: =item *
9743:
1.243 albertel 9744: countacc($url) : count the number of accesses to a given URL
1.191 harris41 9745:
9746: =item *
9747:
1.243 albertel 9748: 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 9749:
9750: =item *
9751:
1.243 albertel 9752: 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 9753:
9754: =item *
9755:
1.243 albertel 9756: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 9757:
9758: =item *
9759:
1.243 albertel 9760: devalidate($symb) : devalidate temporary spreadsheet calculations,
9761: forcing spreadsheet to reevaluate the resource scores next time.
9762:
9763: =back
9764:
9765: =head2 Storing/Retreiving Data
9766:
9767: =over 4
1.191 harris41 9768:
9769: =item *
9770:
1.243 albertel 9771: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9772: for this url; hashref needs to be given and should be a \%hashname; the
9773: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 9774: be derived from the env
1.191 harris41 9775:
9776: =item *
9777:
1.243 albertel 9778: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9779: uses critical subroutine
1.191 harris41 9780:
9781: =item *
9782:
1.243 albertel 9783: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9784: all args are optional
1.191 harris41 9785:
9786: =item *
9787:
1.717 albertel 9788: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9789: dumps the complete (or key matching regexp) namespace into a hash
9790: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9791: normally &store()ed into
9792:
9793: $range should be either an integer '100' (give me the first 100
9794: matching records)
9795: or be two integers sperated by a - with no spaces
9796: '30-50' (give me the 30th through the 50th matching
9797: records)
9798:
9799:
9800: =item *
9801:
9802: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9803: replaces a &store() version of data with a replacement set of data
9804: for a particular resource in a namespace passed in the $storehash hash
9805: reference
9806:
9807: =item *
9808:
1.243 albertel 9809: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9810: works very similar to store/cstore, but all data is stored in a
9811: temporary location and can be reset using tmpreset, $storehash should
9812: be a hash reference, returns nothing on success
1.191 harris41 9813:
9814: =item *
9815:
1.243 albertel 9816: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9817: similar to restore, but all data is stored in a temporary location and
9818: can be reset using tmpreset. Returns a hash of values on success,
9819: error string otherwise.
1.191 harris41 9820:
9821: =item *
9822:
1.243 albertel 9823: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9824: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 9825:
9826: =item *
9827:
1.243 albertel 9828: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9829: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 9830:
9831: =item *
9832:
1.243 albertel 9833: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9834: namesp ($udom and $uname are optional)
1.191 harris41 9835:
9836: =item *
9837:
1.702 albertel 9838: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 9839: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 9840: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 9841:
1.702 albertel 9842: $range should be either an integer '100' (give me the first 100
9843: matching records)
9844: or be two integers sperated by a - with no spaces
9845: '30-50' (give me the 30th through the 50th matching
9846: records)
1.449 matthew 9847: =item *
9848:
9849: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
9850: $store can be a scalar, an array reference, or if the amount to be
9851: incremented is > 1, a hash reference.
9852:
9853: ($udom and $uname are optional)
1.191 harris41 9854:
9855: =item *
9856:
1.243 albertel 9857: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
9858: ($udom and $uname are optional)
1.191 harris41 9859:
9860: =item *
9861:
1.243 albertel 9862: cput($namespace,$storehash,$udom,$uname) : critical put
9863: ($udom and $uname are optional)
1.191 harris41 9864:
9865: =item *
9866:
1.748 albertel 9867: newput($namespace,$storehash,$udom,$uname) :
9868:
9869: Attempts to store the items in the $storehash, but only if they don't
9870: currently exist, if this succeeds you can be certain that you have
9871: successfully created a new key value pair in the $namespace db.
9872:
9873:
9874: Args:
9875: $namespace: name of database to store values to
9876: $storehash: hashref to store to the db
9877: $udom: (optional) domain of user containing the db
9878: $uname: (optional) name of user caontaining the db
9879:
9880: Returns:
9881: 'ok' -> succeeded in storing all keys of $storehash
9882: 'key_exists: <key>' -> failed to anything out of $storehash, as at
9883: least <key> already existed in the db (other
9884: requested keys may also already exist)
1.967 bisitz 9885: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 9886: 'con_lost' -> unable to contact request server
9887: 'refused' -> action was not allowed by remote machine
9888:
9889:
9890: =item *
9891:
1.243 albertel 9892: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9893: reference filled in from namesp (encrypts the return communication)
9894: ($udom and $uname are optional)
1.191 harris41 9895:
9896: =item *
9897:
1.243 albertel 9898: log($udom,$name,$home,$message) : write to permanent log for user; use
9899: critical subroutine
9900:
1.806 raeburn 9901: =item *
9902:
1.860 raeburn 9903: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
9904: array reference filled in from namespace found in domain level on either
9905: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 9906:
9907: =item *
9908:
1.860 raeburn 9909: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
9910: domain level either on specified domain server ($uhome) or primary domain
9911: server ($udom and $uhome are optional)
1.806 raeburn 9912:
1.943 raeburn 9913: =item *
9914:
9915: get_domain_defaults($target_domain) : returns hash with defaults for
9916: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
9917: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
9918: or localauth), initial password or a kerberos realm, language (e.g., en-us).
9919: Values are retrieved from cache (if current), or from domain's configuration.db
9920: (if available), or lastly from values in lonTabs/dns_domain,tab,
9921: or lonTabs/domain.tab.
9922:
9923: %domdefaults = &get_auth_defaults($target_domain);
9924:
1.243 albertel 9925: =back
9926:
9927: =head2 Network Status Functions
9928:
9929: =over 4
1.191 harris41 9930:
9931: =item *
9932:
9933: dirlist($uri) : return directory list based on URI
9934:
9935: =item *
9936:
1.243 albertel 9937: spareserver() : find server with least workload from spare.tab
9938:
1.986 foxr 9939:
9940: =item *
9941:
9942: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
9943: if there is no corresponding loncapa host.
9944:
1.243 albertel 9945: =back
9946:
1.986 foxr 9947:
1.243 albertel 9948: =head2 Apache Request
9949:
9950: =over 4
1.191 harris41 9951:
9952: =item *
9953:
1.243 albertel 9954: ssi($url,%hash) : server side include, does a complete request cycle on url to
9955: localhost, posts hash
9956:
9957: =back
9958:
9959: =head2 Data to String to Data
9960:
9961: =over 4
1.191 harris41 9962:
9963: =item *
9964:
1.243 albertel 9965: hash2str(%hash) : convert a hash into a string complete with escaping and '='
9966: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 9967:
9968: =item *
9969:
1.243 albertel 9970: hashref2str($hashref) : convert a hashref into a string complete with
9971: escaping and '=' and '&' separators, supports elements that are
9972: arrayrefs and hashrefs
1.191 harris41 9973:
9974: =item *
9975:
1.243 albertel 9976: arrayref2str($arrayref) : convert an arrayref into a string complete
9977: with escaping and '&' separators, supports elements that are arrayrefs
9978: and hashrefs
1.191 harris41 9979:
9980: =item *
9981:
1.243 albertel 9982: str2hash($string) : convert string to hash using unescaping and
9983: splitting on '=' and '&', supports elements that are arrayrefs and
9984: hashrefs
1.191 harris41 9985:
9986: =item *
9987:
1.243 albertel 9988: str2array($string) : convert string to hash using unescaping and
9989: splitting on '&', supports elements that are arrayrefs and hashrefs
9990:
9991: =back
9992:
9993: =head2 Logging Routines
9994:
9995: =over 4
9996:
9997: These routines allow one to make log messages in the lonnet.log and
9998: lonnet.perm logfiles.
1.191 harris41 9999:
10000: =item *
10001:
1.243 albertel 10002: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 10003:
10004: =item *
10005:
1.243 albertel 10006: logthis() : append message to the normal lonnet.log file, it gets
10007: preiodically rolled over and deleted.
1.191 harris41 10008:
10009: =item *
10010:
1.243 albertel 10011: logperm() : append a permanent message to lonnet.perm.log, this log
10012: file never gets deleted by any automated portion of the system, only
10013: messages of critical importance should go in here.
10014:
10015: =back
10016:
10017: =head2 General File Helper Routines
10018:
10019: =over 4
1.191 harris41 10020:
10021: =item *
10022:
1.481 raeburn 10023: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10024: (a) files in /uploaded
10025: (i) If a local copy of the file exists -
10026: compares modification date of local copy with last-modified date for
10027: definitive version stored on home server for course. If local copy is
10028: stale, requests a new version from the home server and stores it.
10029: If the original has been removed from the home server, then local copy
10030: is unlinked.
10031: (ii) If local copy does not exist -
10032: requests the file from the home server and stores it.
10033:
10034: If $caller is 'uploadrep':
10035: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10036: for request for files originally uploaded via DOCS.
10037: - returns 'ok' if fresh local copy now available, -1 otherwise.
10038:
10039: Otherwise:
10040: This indicates a call from the content generation phase of the request.
10041: - returns the entire contents of the file or -1.
10042:
10043: (b) files in /res
10044: - returns the entire contents of a file or -1;
10045: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 10046:
1.712 albertel 10047:
10048: =item *
10049:
10050: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10051: reference
10052:
10053: returns either a stat() list of data about the file or an empty list
10054: if the file doesn't exist or couldn't find out about it (connection
10055: problems or user unknown)
10056:
1.191 harris41 10057: =item *
10058:
1.243 albertel 10059: filelocation($dir,$file) : returns file system location of a file
10060: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10061: directory that relative $file lookups are to looked in ($dir of /a/dir
10062: and a file of ../bob will become /a/bob)
1.191 harris41 10063:
10064: =item *
10065:
10066: hreflocation($dir,$file) : returns file system location or a URL; same as
10067: filelocation except for hrefs
10068:
10069: =item *
10070:
10071: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10072:
1.243 albertel 10073: =back
10074:
1.608 albertel 10075: =head2 Usererfile file routines (/uploaded*)
10076:
10077: =over 4
10078:
10079: =item *
10080:
10081: userfileupload(): main rotine for putting a file in a user or course's
10082: filespace, arguments are,
10083:
1.620 albertel 10084: formname - required - this is the name of the element in $env where the
1.608 albertel 10085: filename, and the contents of the file to create/modifed exist
1.620 albertel 10086: the filename is in $env{'form.'.$formname.'.filename'} and the
10087: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10088: coursedoc - if true, store the file in the course of the active role
10089: of the current user
10090: subdir - required - subdirectory to put the file in under ../userfiles/
10091: if undefined, it will be placed in "unknown"
10092:
10093: (This routine calls clean_filename() to remove any dangerous
10094: characters from the filename, and then calls finuserfileupload() to
10095: complete the transaction)
10096:
10097: returns either the url of the uploaded file (/uploaded/....) if successful
10098: and /adm/notfound.html if unsuccessful
10099:
10100: =item *
10101:
10102: clean_filename(): routine for cleaing a filename up for storage in
10103: userfile space, argument is:
10104:
10105: filename - proposed filename
10106:
10107: returns: the new clean filename
10108:
10109: =item *
10110:
10111: finishuserfileupload(): routine that creaes and sends the file to
10112: userspace, probably shouldn't be called directly
10113:
10114: docuname: username or courseid of destination for the file
10115: docudom: domain of user/course of destination for the file
10116: formname: same as for userfileupload()
10117: fname: filename (inculding subdirectories) for the file
10118:
10119: returns either the url of the uploaded file (/uploaded/....) if successful
10120: and /adm/notfound.html if unsuccessful
10121:
10122: =item *
10123:
10124: renameuserfile(): renames an existing userfile to a new name
10125:
10126: Args:
10127: docuname: username or courseid of destination for the file
10128: docudom: domain of user/course of destination for the file
10129: old: current file name (including any subdirs under userfiles)
10130: new: desired file name (including any subdirs under userfiles)
10131:
10132: =item *
10133:
10134: mkdiruserfile(): creates a directory is a userfiles dir
10135:
10136: Args:
10137: docuname: username or courseid of destination for the file
10138: docudom: domain of user/course of destination for the file
10139: dir: dir to create (including any subdirs under userfiles)
10140:
10141: =item *
10142:
10143: removeuserfile(): removes a file that exists in userfiles
10144:
10145: Args:
10146: docuname: username or courseid of destination for the file
10147: docudom: domain of user/course of destination for the file
10148: fname: filname to delete (including any subdirs under userfiles)
10149:
10150: =item *
10151:
10152: removeuploadedurl(): convience function for removeuserfile()
10153:
10154: Args:
10155: url: a full /uploaded/... url to delete
10156:
1.747 albertel 10157: =item *
10158:
10159: get_portfile_permissions():
10160: Args:
10161: domain: domain of user or course contain the portfolio files
10162: user: name of user or num of course contain the portfolio files
10163: Returns:
10164: hashref of a dump of the proper file_permissions.db
10165:
10166:
10167: =item *
10168:
10169: get_access_controls():
10170:
10171: Args:
10172: current_permissions: the hash ref returned from get_portfile_permissions()
10173: group: (optional) the group you want the files associated with
10174: file: (optional) the file you want access info on
10175:
10176: Returns:
1.749 raeburn 10177: a hash (keys are file names) of hashes containing
10178: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10179: values are XML containing access control settings (see below)
1.747 albertel 10180:
10181: Internal notes:
10182:
1.749 raeburn 10183: access controls are stored in file_permissions.db as key=value pairs.
10184: key -> path to file/file_name\0uniqueID:scope_end_start
10185: where scope -> public,guest,course,group,domains or users.
10186: end -> UNIX time for end of access (0 -> no end date)
10187: start -> UNIX time for start of access
10188:
10189: value -> XML description of access control
10190: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10191: <start></start>
10192: <end></end>
10193:
10194: <password></password> for scope type = guest
10195:
10196: <domain></domain> for scope type = course or group
10197: <number></number>
10198: <roles id="">
10199: <role></role>
10200: <access></access>
10201: <section></section>
10202: <group></group>
10203: </roles>
10204:
10205: <dom></dom> for scope type = domains
10206:
10207: <users> for scope type = users
10208: <user>
10209: <uname></uname>
10210: <udom></udom>
10211: </user>
10212: </users>
10213: </scope>
10214:
10215: Access data is also aggregated for each file in an additional key=value pair:
10216: key -> path to file/file_name\0accesscontrol
10217: value -> reference to hash
10218: hash contains key = value pairs
10219: where key = uniqueID:scope_end_start
10220: value = UNIX time record was last updated
10221:
10222: Used to improve speed of look-ups of access controls for each file.
10223:
10224: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10225:
10226: modify_access_controls():
10227:
10228: Modifies access controls for a portfolio file
10229: Args
10230: 1. file name
10231: 2. reference to hash of required changes,
10232: 3. domain
10233: 4. username
10234: where domain,username are the domain of the portfolio owner
10235: (either a user or a course)
10236:
10237: Returns:
10238: 1. result of additions or updates ('ok' or 'error', with error message).
10239: 2. result of deletions ('ok' or 'error', with error message).
10240: 3. reference to hash of any new or updated access controls.
10241: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10242: key = integer (inbound ID)
10243: value = uniqueID
1.747 albertel 10244:
1.608 albertel 10245: =back
10246:
1.243 albertel 10247: =head2 HTTP Helper Routines
10248:
10249: =over 4
10250:
1.191 harris41 10251: =item *
10252:
10253: escape() : unpack non-word characters into CGI-compatible hex codes
10254:
10255: =item *
10256:
10257: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10258:
1.243 albertel 10259: =back
10260:
10261: =head1 PRIVATE SUBROUTINES
10262:
10263: =head2 Underlying communication routines (Shouldn't call)
10264:
10265: =over 4
10266:
10267: =item *
10268:
10269: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10270:
10271: =item *
10272:
10273: reply() : uses subreply to send a message to remote machine, logs all failures
10274:
10275: =item *
10276:
10277: critical() : passes a critical message to another server; if cannot
10278: get through then place message in connection buffer directory and
10279: returns con_delayed, if incapable of saving message, returns
10280: con_failed
10281:
10282: =item *
10283:
10284: reconlonc() : tries to reconnect lonc client processes.
10285:
10286: =back
10287:
10288: =head2 Resource Access Logging
10289:
10290: =over 4
10291:
10292: =item *
10293:
10294: flushcourselogs() : flush (save) buffer logs and access logs
10295:
10296: =item *
10297:
10298: courselog($what) : save message for course in hash
10299:
10300: =item *
10301:
10302: courseacclog($what) : save message for course using &courselog(). Perform
10303: special processing for specific resource types (problems, exams, quizzes, etc).
10304:
1.191 harris41 10305: =item *
10306:
10307: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10308: as a PerlChildExitHandler
1.243 albertel 10309:
10310: =back
10311:
10312: =head2 Other
10313:
10314: =over 4
10315:
10316: =item *
10317:
10318: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 10319:
10320: =back
10321:
10322: =cut
1.877 foxr 10323:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>