Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1071
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1071 ! raeburn 4: # $Id: lonnet.pm,v 1.1070 2010/06/04 00:14:15 www Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968 raeburn 79: $_64bit %env %protocol);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.676 albertel 98:
1.195 www 99: my $readit;
1.550 foxr 100: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 101:
1.619 albertel 102: require Exporter;
103:
104: our @ISA = qw (Exporter);
105: our @EXPORT = qw(%env);
106:
1.449 matthew 107:
1.1 albertel 108: # --------------------------------------------------------------------- Logging
1.729 www 109: {
110: my $logid;
111: sub instructor_log {
1.957 raeburn 112: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
113: if (($cnum eq '') || ($cdom eq '')) {
114: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
115: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
116: }
1.729 www 117: $logid++;
1.957 raeburn 118: my $now = time();
119: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 120: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 121: { $id => {
122: 'exe_uname' => $env{'user.name'},
123: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 124: 'exe_time' => $now,
1.730 www 125: 'exe_ip' => $ENV{'REMOTE_ADDR'},
126: 'delflag' => $delflag,
127: 'logentry' => $storehash,
128: 'uname' => $uname,
129: 'udom' => $udom,
130: }
1.957 raeburn 131: },$cdom,$cnum);
1.729 www 132: }
133: }
1.1 albertel 134:
1.163 harris41 135: sub logtouch {
136: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 137: unless (-e "$execdir/logs/lonnet.log") {
138: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 139: close $fh;
140: }
141: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
142: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
143: }
144:
1.1 albertel 145: sub logthis {
146: my $message=shift;
147: my $execdir=$perlvar{'lonDaemons'};
148: my $now=time;
149: my $local=localtime($now);
1.448 albertel 150: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 151: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
152: print $fh $logstring;
1.448 albertel 153: close($fh);
154: }
1.1 albertel 155: return 1;
156: }
157:
158: sub logperm {
159: my $message=shift;
160: my $execdir=$perlvar{'lonDaemons'};
161: my $now=time;
162: my $local=localtime($now);
1.448 albertel 163: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
164: print $fh "$now:$message:$local\n";
165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
1.850 albertel 170: sub create_connection {
1.853 albertel 171: my ($hostname,$lonid) = @_;
1.851 albertel 172: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 173: Type => SOCK_STREAM,
174: Timeout => 10);
175: return 0 if (!$client);
1.890 albertel 176: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 177: my $result = <$client>;
178: chomp($result);
179: return 1 if ($result eq 'done');
180: return 0;
181: }
182:
1.983 raeburn 183: sub get_server_timezone {
184: my ($cnum,$cdom) = @_;
185: my $home=&homeserver($cnum,$cdom);
186: if ($home ne 'no_host') {
187: my $cachetime = 24*3600;
188: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
189: if (defined($cached)) {
190: return $timezone;
191: } else {
192: my $timezone = &reply('servertimezone',$home);
193: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
194: }
195: }
196: }
1.850 albertel 197:
1.993 raeburn 198: sub get_server_loncaparev {
199: my ($dom,$lonhost) = @_;
200: if (defined($lonhost)) {
201: if (!defined(&hostname($lonhost))) {
202: undef($lonhost);
203: }
204: }
205: if (!defined($lonhost)) {
206: if (defined(&domain($dom,'primary'))) {
207: $lonhost=&domain($dom,'primary');
208: if ($lonhost eq 'no_host') {
209: undef($lonhost);
210: }
211: }
212: }
213: if (defined($lonhost)) {
214: my $cachetime = 24*3600;
215: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
216: if (defined($cached)) {
217: return $loncaparev;
218: } else {
219: my $loncaparev = &reply('serverloncaparev',$lonhost);
220: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
221: }
222: }
223: }
224:
1.1 albertel 225: # -------------------------------------------------- Non-critical communication
226: sub subreply {
227: my ($cmd,$server)=@_;
1.838 albertel 228: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 229: #
230: # With loncnew process trimming, there's a timing hole between lonc server
231: # process exit and the master server picking up the listen on the AF_UNIX
232: # socket. In that time interval, a lock file will exist:
233:
234: my $lockfile=$peerfile.".lock";
235: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
236: sleep(1);
237: }
238: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 239: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 240: #
1.550 foxr 241: # We'll give the connection a few tries before abandoning it. If
242: # connection is not possible, we'll con_lost back to the client.
243: #
244: my $client;
245: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
246: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
247: Type => SOCK_STREAM,
248: Timeout => 10);
1.869 albertel 249: if ($client) {
1.550 foxr 250: last; # Connected!
1.850 albertel 251: } else {
1.853 albertel 252: &create_connection(&hostname($server),$server);
1.550 foxr 253: }
1.850 albertel 254: sleep(1); # Try again later if failed connection.
1.550 foxr 255: }
256: my $answer;
257: if ($client) {
1.704 albertel 258: print $client "sethost:$server:$cmd\n";
1.550 foxr 259: $answer=<$client>;
260: if (!$answer) { $answer="con_lost"; }
261: chomp($answer);
262: } else {
263: $answer = 'con_lost'; # Failed connection.
264: }
1.1 albertel 265: return $answer;
266: }
267:
268: sub reply {
269: my ($cmd,$server)=@_;
1.838 albertel 270: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 271: my $answer=subreply($cmd,$server);
1.65 www 272: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 273: &logthis("<font color=\"blue\">WARNING:".
1.12 www 274: " $cmd to $server returned $answer</font>");
275: }
1.1 albertel 276: return $answer;
277: }
278:
279: # ----------------------------------------------------------- Send USR1 to lonc
280:
281: sub reconlonc {
1.891 albertel 282: my ($lonid) = @_;
283: my $hostname = &hostname($lonid);
284: if ($lonid) {
285: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
286: if ($hostname && -e $peerfile) {
287: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
288: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
289: Type => SOCK_STREAM,
290: Timeout => 10);
291: if ($client) {
292: print $client ("reset_retries\n");
293: my $answer=<$client>;
294: #reset just this one.
295: }
296: }
297: return;
298: }
299:
1.836 www 300: &logthis("Trying to reconnect lonc");
1.1 albertel 301: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 302: if (open(my $fh,"<$loncfile")) {
1.1 albertel 303: my $loncpid=<$fh>;
304: chomp($loncpid);
305: if (kill 0 => $loncpid) {
306: &logthis("lonc at pid $loncpid responding, sending USR1");
307: kill USR1 => $loncpid;
308: sleep 1;
1.836 www 309: } else {
1.12 www 310: &logthis(
1.672 albertel 311: "<font color=\"blue\">WARNING:".
1.12 www 312: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 313: }
314: } else {
1.836 www 315: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 316: }
317: }
318:
319: # ------------------------------------------------------ Critical communication
1.12 www 320:
1.1 albertel 321: sub critical {
322: my ($cmd,$server)=@_;
1.838 albertel 323: unless (&hostname($server)) {
1.672 albertel 324: &logthis("<font color=\"blue\">WARNING:".
1.89 www 325: " Critical message to unknown server ($server)</font>");
326: return 'no_such_host';
327: }
1.1 albertel 328: my $answer=reply($cmd,$server);
329: if ($answer eq 'con_lost') {
330: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 331: my $answer=reply($cmd,$server);
1.1 albertel 332: if ($answer eq 'con_lost') {
333: my $now=time;
334: my $middlename=$cmd;
1.5 www 335: $middlename=substr($middlename,0,16);
1.1 albertel 336: $middlename=~s/\W//g;
337: my $dfilename=
1.305 www 338: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
339: $dumpcount++;
1.1 albertel 340: {
1.448 albertel 341: my $dfh;
342: if (open($dfh,">$dfilename")) {
343: print $dfh "$cmd\n";
344: close($dfh);
345: }
1.1 albertel 346: }
347: sleep 2;
348: my $wcmd='';
349: {
1.448 albertel 350: my $dfh;
351: if (open($dfh,"<$dfilename")) {
352: $wcmd=<$dfh>;
353: close($dfh);
354: }
1.1 albertel 355: }
356: chomp($wcmd);
1.7 www 357: if ($wcmd eq $cmd) {
1.672 albertel 358: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 359: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 360: &logperm("D:$server:$cmd");
361: return 'con_delayed';
362: } else {
1.672 albertel 363: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 364: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 365: &logperm("F:$server:$cmd");
366: return 'con_failed';
367: }
368: }
369: }
370: return $answer;
1.405 albertel 371: }
372:
1.755 albertel 373: # ------------------------------------------- check if return value is an error
374:
375: sub error {
376: my ($result) = @_;
1.756 albertel 377: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 378: if ($2 == 2) { return undef; }
379: return $1;
380: }
381: return undef;
382: }
383:
1.783 albertel 384: sub convert_and_load_session_env {
385: my ($lonidsdir,$handle)=@_;
386: my @profile;
387: {
1.917 albertel 388: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
389: if (!$opened) {
1.915 albertel 390: return 0;
391: }
1.783 albertel 392: flock($idf,LOCK_SH);
393: @profile=<$idf>;
394: close($idf);
395: }
396: my %temp_env;
397: foreach my $line (@profile) {
1.786 albertel 398: if ($line !~ m/=/) {
399: return 0;
400: }
1.783 albertel 401: chomp($line);
402: my ($envname,$envvalue)=split(/=/,$line,2);
403: $temp_env{&unescape($envname)} = &unescape($envvalue);
404: }
405: unlink("$lonidsdir/$handle.id");
406: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
407: 0640)) {
408: %disk_env = %temp_env;
409: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
410: untie(%disk_env);
411: }
1.786 albertel 412: return 1;
1.783 albertel 413: }
414:
1.374 www 415: # ------------------------------------------- Transfer profile into environment
1.780 albertel 416: my $env_loaded;
417: sub transfer_profile_to_env {
1.788 albertel 418: my ($lonidsdir,$handle,$force_transfer) = @_;
419: if (!$force_transfer && $env_loaded) { return; }
1.374 www 420:
1.720 albertel 421: if (!defined($lonidsdir)) {
422: $lonidsdir = $perlvar{'lonIDsDir'};
423: }
424: if (!defined($handle)) {
425: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
426: }
427:
1.786 albertel 428: my $convert;
429: {
1.917 albertel 430: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
431: if (!$opened) {
1.915 albertel 432: return;
433: }
1.786 albertel 434: flock($idf,LOCK_SH);
435: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
436: &GDBM_READER(),0640)) {
437: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
438: untie(%disk_env);
439: } else {
440: $convert = 1;
441: }
442: }
443: if ($convert) {
444: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
445: &logthis("Failed to load session, or convert session.");
446: }
1.374 www 447: }
1.783 albertel 448:
1.786 albertel 449: my %remove;
1.783 albertel 450: while ( my $envname = each(%env) ) {
1.433 matthew 451: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
452: if ($time < time-300) {
1.783 albertel 453: $remove{$key}++;
1.433 matthew 454: }
455: }
456: }
1.783 albertel 457:
1.619 albertel 458: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 459: $env_loaded=1;
1.783 albertel 460: foreach my $expired_key (keys(%remove)) {
1.433 matthew 461: &delenv($expired_key);
1.374 www 462: }
1.1 albertel 463: }
464:
1.916 albertel 465: # ---------------------------------------------------- Check for valid session
466: sub check_for_valid_session {
467: my ($r) = @_;
468: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
469: my $lonid=$cookies{'lonID'};
470: return undef if (!$lonid);
471:
472: my $handle=&LONCAPA::clean_handle($lonid->value);
473: my $lonidsdir=$r->dir_config('lonIDsDir');
474: return undef if (!-e "$lonidsdir/$handle.id");
475:
1.917 albertel 476: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
477: return undef if (!$opened);
1.916 albertel 478:
479: flock($idf,LOCK_SH);
480: my %disk_env;
481: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
482: &GDBM_READER(),0640)) {
483: return undef;
484: }
485:
486: if (!defined($disk_env{'user.name'})
487: || !defined($disk_env{'user.domain'})) {
488: return undef;
489: }
490: return $handle;
491: }
492:
1.830 albertel 493: sub timed_flock {
494: my ($file,$lock_type) = @_;
495: my $failed=0;
496: eval {
497: local $SIG{__DIE__}='DEFAULT';
498: local $SIG{ALRM}=sub {
499: $failed=1;
500: die("failed lock");
501: };
502: alarm(13);
503: flock($file,$lock_type);
504: alarm(0);
505: };
506: if ($failed) {
507: return undef;
508: } else {
509: return 1;
510: }
511: }
512:
1.5 www 513: # ---------------------------------------------------------- Append Environment
514:
515: sub appenv {
1.949 raeburn 516: my ($newenv,$roles) = @_;
517: if (ref($newenv) eq 'HASH') {
518: foreach my $key (keys(%{$newenv})) {
519: my $refused = 0;
520: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
521: $refused = 1;
522: if (ref($roles) eq 'ARRAY') {
523: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
524: if (grep(/^\Q$role\E$/,@{$roles})) {
525: $refused = 0;
526: }
527: }
528: }
529: if ($refused) {
530: &logthis("<font color=\"blue\">WARNING: ".
531: "Attempt to modify environment ".$key." to ".$newenv->{$key}
532: .'</font>');
533: delete($newenv->{$key});
534: } else {
535: $env{$key}=$newenv->{$key};
536: }
537: }
538: my $opened = open(my $env_file,'+<',$env{'user.environment'});
539: if ($opened
540: && &timed_flock($env_file,LOCK_EX)
541: &&
542: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
543: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
544: while (my ($key,$value) = each(%{$newenv})) {
545: $disk_env{$key} = $value;
546: }
547: untie(%disk_env);
1.35 www 548: }
1.191 harris41 549: }
1.56 www 550: return 'ok';
551: }
552: # ----------------------------------------------------- Delete from Environment
553:
554: sub delenv {
1.987 raeburn 555: my ($delthis,$regexp) = @_;
1.56 www 556: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 557: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 558: "Attempt to delete from environment ".$delthis);
559: return 'error';
560: }
1.917 albertel 561: my $opened = open(my $env_file,'+<',$env{'user.environment'});
562: if ($opened
1.915 albertel 563: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 564: &&
565: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
566: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 567: foreach my $key (keys(%disk_env)) {
1.987 raeburn 568: if ($regexp) {
569: if ($key=~/^$delthis/) {
570: delete($env{$key});
571: delete($disk_env{$key});
572: }
573: } else {
574: if ($key=~/^\Q$delthis\E/) {
575: delete($env{$key});
576: delete($disk_env{$key});
577: }
578: }
1.448 albertel 579: }
1.783 albertel 580: untie(%disk_env);
1.5 www 581: }
582: return 'ok';
1.369 albertel 583: }
584:
1.790 albertel 585: sub get_env_multiple {
586: my ($name) = @_;
587: my @values;
588: if (defined($env{$name})) {
589: # exists is it an array
590: if (ref($env{$name})) {
591: @values=@{ $env{$name} };
592: } else {
593: $values[0]=$env{$name};
594: }
595: }
596: return(@values);
597: }
598:
1.958 www 599: # ------------------------------------------------------------------- Locking
600:
601: sub set_lock {
602: my ($text)=@_;
603: $locknum++;
604: my $id=$$.'-'.$locknum;
605: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
606: 'session.lock.'.$id => $text});
607: return $id;
608: }
609:
610: sub get_locks {
611: my $num=0;
612: my %texts=();
613: foreach my $lock (split(/\,/,$env{'session.locks'})) {
614: if ($lock=~/\w/) {
615: $num++;
616: $texts{$lock}=$env{'session.lock.'.$lock};
617: }
618: }
619: return ($num,%texts);
620: }
621:
622: sub remove_lock {
623: my ($id)=@_;
624: my $newlocks='';
625: foreach my $lock (split(/\,/,$env{'session.locks'})) {
626: if (($lock=~/\w/) && ($lock ne $id)) {
627: $newlocks.=','.$lock;
628: }
629: }
630: &appenv({'session.locks' => $newlocks});
631: &delenv('session.lock.'.$id);
632: }
633:
634: sub remove_all_locks {
635: my $activelocks=$env{'session.locks'};
636: foreach my $lock (split(/\,/,$env{'session.locks'})) {
637: if ($lock=~/\w/) {
638: &remove_lock($lock);
639: }
640: }
641: }
642:
643:
1.369 albertel 644: # ------------------------------------------ Find out current server userload
645: sub userload {
646: my $numusers=0;
647: {
648: opendir(LONIDS,$perlvar{'lonIDsDir'});
649: my $filename;
650: my $curtime=time;
651: while ($filename=readdir(LONIDS)) {
1.925 albertel 652: next if ($filename eq '.' || $filename eq '..');
653: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 654: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 655: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 656: }
657: closedir(LONIDS);
658: }
659: my $userloadpercent=0;
660: my $maxuserload=$perlvar{'lonUserLoadLim'};
661: if ($maxuserload) {
1.371 albertel 662: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 663: }
1.372 albertel 664: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 665: return $userloadpercent;
1.283 www 666: }
667:
1.1 albertel 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: }
1.1001 raeburn 696: if (defined($spare_server)) {
697: my $hostname = &hostname($spare_server);
698: if (defined($hostname)) {
699: $spare_server = $protocol.'://'.$hostname;
700: }
701: }
1.784 albertel 702: }
703: return $spare_server;
704: }
705:
706: sub compare_server_load {
707: my ($try_server, $spare_server, $lowest_load) = @_;
708:
709: my $loadans = &reply('load', $try_server);
710: my $userloadans = &reply('userload',$try_server);
711:
712: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
713: next; #didn't get a number from the server
714: }
715:
716: my $load;
717: if ($loadans =~ /\d/) {
718: if ($userloadans =~ /\d/) {
719: #both are numbers, pick the bigger one
720: $load = ($loadans > $userloadans) ? $loadans
721: : $userloadans;
1.411 albertel 722: } else {
1.784 albertel 723: $load = $loadans;
1.411 albertel 724: }
1.784 albertel 725: } else {
726: $load = $userloadans;
727: }
728:
729: if (($load =~ /\d/) && ($load < $lowest_load)) {
730: $spare_server = $try_server;
731: $lowest_load = $load;
1.370 albertel 732: }
1.784 albertel 733: return ($spare_server,$lowest_load);
1.202 matthew 734: }
1.914 albertel 735:
736: # --------------------------- ask offload servers if user already has a session
737: sub find_existing_session {
738: my ($udom,$uname) = @_;
739: foreach my $try_server (@{ $spareid{'primary'} },
740: @{ $spareid{'default'} }) {
741: return $try_server if (&has_user_session($try_server, $udom, $uname));
742: }
743: return;
744: }
745:
746: # -------------------------------- ask if server already has a session for user
747: sub has_user_session {
748: my ($lonid,$udom,$uname) = @_;
749: my $result = &reply(join(':','userhassession',
750: map {&escape($_)} ($udom,$uname)),$lonid);
751: return 1 if ($result eq 'ok');
752:
753: return 0;
754: }
755:
1.202 matthew 756: # --------------------------------------------- Try to change a user's password
757:
758: sub changepass {
1.799 raeburn 759: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 760: $currentpass = &escape($currentpass);
761: $newpass = &escape($newpass);
1.1030 raeburn 762: my $lonhost = $perlvar{'lonHostID'};
763: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 764: $server);
765: if (! $answer) {
766: &logthis("No reply on password change request to $server ".
767: "by $uname in domain $udom.");
768: } elsif ($answer =~ "^ok") {
769: &logthis("$uname in $udom successfully changed their password ".
770: "on $server.");
771: } elsif ($answer =~ "^pwchange_failure") {
772: &logthis("$uname in $udom was unable to change their password ".
773: "on $server. The action was blocked by either lcpasswd ".
774: "or pwchange");
775: } elsif ($answer =~ "^non_authorized") {
776: &logthis("$uname in $udom did not get their password correct when ".
777: "attempting to change it on $server.");
778: } elsif ($answer =~ "^auth_mode_error") {
779: &logthis("$uname in $udom attempted to change their password despite ".
780: "not being locally or internally authenticated on $server.");
781: } elsif ($answer =~ "^unknown_user") {
782: &logthis("$uname in $udom attempted to change their password ".
783: "on $server but were unable to because $server is not ".
784: "their home server.");
785: } elsif ($answer =~ "^refused") {
786: &logthis("$server refused to change $uname in $udom password because ".
787: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 788: } elsif ($answer =~ "invalid_client") {
789: &logthis("$server refused to change $uname in $udom password because ".
790: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 791: }
792: return $answer;
1.1 albertel 793: }
794:
1.169 harris41 795: # ----------------------- Try to determine user's current authentication scheme
796:
797: sub queryauthenticate {
798: my ($uname,$udom)=@_;
1.456 albertel 799: my $uhome=&homeserver($uname,$udom);
800: if (!$uhome) {
801: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
802: return 'no_host';
803: }
804: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
805: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
806: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 807: }
1.456 albertel 808: return $answer;
1.169 harris41 809: }
810:
1.1 albertel 811: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 812:
1.1 albertel 813: sub authenticate {
1.952 raeburn 814: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 815: $upass=&escape($upass);
816: $uname= &LONCAPA::clean_username($uname);
1.836 www 817: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 818: my $newhome;
1.836 www 819: if ((!$uhome) || ($uhome eq 'no_host')) {
820: # Maybe the machine was offline and only re-appeared again recently?
821: &reconlonc();
822: # One more
1.952 raeburn 823: $uhome=&homeserver($uname,$udom,1);
824: if (($uhome eq 'no_host') && $checkdefauth) {
825: if (defined(&domain($udom,'primary'))) {
826: $newhome=&domain($udom,'primary');
827: }
828: if ($newhome ne '') {
829: $uhome = $newhome;
830: }
831: }
1.836 www 832: if ((!$uhome) || ($uhome eq 'no_host')) {
833: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 834: return 'no_host';
835: }
1.1 albertel 836: }
1.952 raeburn 837: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 838: if ($answer eq 'authorized') {
1.952 raeburn 839: if ($newhome) {
840: &logthis("User $uname at $udom authorized by $uhome, but needs account");
841: return 'no_account_on_host';
842: } else {
843: &logthis("User $uname at $udom authorized by $uhome");
844: return $uhome;
845: }
1.471 albertel 846: }
847: if ($answer eq 'non_authorized') {
848: &logthis("User $uname at $udom rejected by $uhome");
849: return 'no_host';
1.9 www 850: }
1.471 albertel 851: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 852: return 'no_host';
853: }
854:
855: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 856:
1.599 albertel 857: my %homecache;
1.1 albertel 858: sub homeserver {
1.230 stredwic 859: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 860: my $index="$uname:$udom";
1.426 albertel 861:
1.599 albertel 862: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 863:
864: my %servers = &get_servers($udom,'library');
865: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 866: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 867: exists($badServerCache{$tryserver}));
1.841 albertel 868:
869: my $answer=reply("home:$udom:$uname",$tryserver);
870: if ($answer eq 'found') {
871: delete($badServerCache{$tryserver});
872: return $homecache{$index}=$tryserver;
873: } elsif ($answer eq 'no_host') {
874: $badServerCache{$tryserver}=1;
875: }
1.1 albertel 876: }
877: return 'no_host';
1.70 www 878: }
879:
880: # ------------------------------------- Find the usernames behind a list of IDs
881:
882: sub idget {
883: my ($udom,@ids)=@_;
884: my %returnhash=();
885:
1.841 albertel 886: my %servers = &get_servers($udom,'library');
887: foreach my $tryserver (keys(%servers)) {
888: my $idlist=join('&',@ids);
889: $idlist=~tr/A-Z/a-z/;
890: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
891: my @answer=();
892: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
893: @answer=split(/\&/,$reply);
894: } ;
895: my $i;
896: for ($i=0;$i<=$#ids;$i++) {
897: if ($answer[$i]) {
898: $returnhash{$ids[$i]}=$answer[$i];
899: }
900: }
901: }
1.70 www 902: return %returnhash;
903: }
904:
905: # ------------------------------------- Find the IDs behind a list of usernames
906:
907: sub idrget {
908: my ($udom,@unames)=@_;
909: my %returnhash=();
1.800 albertel 910: foreach my $uname (@unames) {
911: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 912: }
1.70 www 913: return %returnhash;
914: }
915:
916: # ------------------------------- Store away a list of names and associated IDs
917:
918: sub idput {
919: my ($udom,%ids)=@_;
920: my %servers=();
1.800 albertel 921: foreach my $uname (keys(%ids)) {
922: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
923: my $uhom=&homeserver($uname,$udom);
1.70 www 924: if ($uhom ne 'no_host') {
1.800 albertel 925: my $id=&escape($ids{$uname});
1.70 www 926: $id=~tr/A-Z/a-z/;
1.800 albertel 927: my $esc_unam=&escape($uname);
1.70 www 928: if ($servers{$uhom}) {
1.800 albertel 929: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 930: } else {
1.800 albertel 931: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 932: }
933: }
1.191 harris41 934: }
1.800 albertel 935: foreach my $server (keys(%servers)) {
936: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 937: }
1.344 www 938: }
939:
1.1023 raeburn 940: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 941: sub dump_dom {
1.1023 raeburn 942: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 943: if (!$udom) {
944: $udom=$env{'user.domain'};
945: }
946: my %returnhash;
1.1023 raeburn 947: if ($udom) {
948: my $uname = &get_domainconfiguser($udom);
949: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 950: }
951: return %returnhash;
952: }
953:
1.1023 raeburn 954: # ------------------------------------------ get items from domain db files
1.806 raeburn 955:
956: sub get_dom {
1.860 raeburn 957: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 958: my $items='';
959: foreach my $item (@$storearr) {
960: $items.=&escape($item).'&';
961: }
962: $items=~s/\&$//;
1.860 raeburn 963: if (!$udom) {
964: $udom=$env{'user.domain'};
965: if (defined(&domain($udom,'primary'))) {
966: $uhome=&domain($udom,'primary');
967: } else {
1.874 albertel 968: undef($uhome);
1.860 raeburn 969: }
970: } else {
971: if (!$uhome) {
972: if (defined(&domain($udom,'primary'))) {
973: $uhome=&domain($udom,'primary');
974: }
975: }
976: }
977: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 978: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 979: my %returnhash;
1.875 albertel 980: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 981: return %returnhash;
982: }
1.806 raeburn 983: my @pairs=split(/\&/,$rep);
984: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
985: return @pairs;
986: }
987: my $i=0;
988: foreach my $item (@$storearr) {
989: $returnhash{$item}=&thaw_unescape($pairs[$i]);
990: $i++;
991: }
992: return %returnhash;
993: } else {
1.880 banghart 994: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 995: }
996: }
997:
998: # -------------------------------------------- put items in domain db files
999:
1000: sub put_dom {
1.860 raeburn 1001: my ($namespace,$storehash,$udom,$uhome)=@_;
1002: if (!$udom) {
1003: $udom=$env{'user.domain'};
1004: if (defined(&domain($udom,'primary'))) {
1005: $uhome=&domain($udom,'primary');
1006: } else {
1.874 albertel 1007: undef($uhome);
1.860 raeburn 1008: }
1009: } else {
1010: if (!$uhome) {
1011: if (defined(&domain($udom,'primary'))) {
1012: $uhome=&domain($udom,'primary');
1013: }
1014: }
1015: }
1016: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1017: my $items='';
1018: foreach my $item (keys(%$storehash)) {
1019: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1020: }
1021: $items=~s/\&$//;
1022: return &reply("putdom:$udom:$namespace:$items",$uhome);
1023: } else {
1.860 raeburn 1024: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1025: }
1026: }
1027:
1.1023 raeburn 1028: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1029: sub newput_dom {
1.1023 raeburn 1030: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1031: my $result;
1032: if (!$udom) {
1033: $udom=$env{'user.domain'};
1034: }
1.1023 raeburn 1035: if ($udom) {
1036: my $uname = &get_domainconfiguser($udom);
1037: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1038: }
1039: return $result;
1040: }
1041:
1.1023 raeburn 1042: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1043: sub del_dom {
1.1023 raeburn 1044: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1045: if (ref($storearr) eq 'ARRAY') {
1046: if (!$udom) {
1047: $udom=$env{'user.domain'};
1048: }
1.1023 raeburn 1049: if ($udom) {
1050: my $uname = &get_domainconfiguser($udom);
1051: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1052: }
1053: }
1054: }
1055:
1.1023 raeburn 1056: # ----------------------------------construct domainconfig user for a domain
1057: sub get_domainconfiguser {
1058: my ($udom) = @_;
1059: return $udom.'-domainconfig';
1060: }
1061:
1.837 raeburn 1062: sub retrieve_inst_usertypes {
1063: my ($udom) = @_;
1064: my (%returnhash,@order);
1.989 raeburn 1065: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1066: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1067: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1068: %returnhash = %{$domdefs{'inststatustypes'}};
1069: @order = @{$domdefs{'inststatusorder'}};
1070: } else {
1071: if (defined(&domain($udom,'primary'))) {
1072: my $uhome=&domain($udom,'primary');
1073: my $rep=&reply("inst_usertypes:$udom",$uhome);
1074: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1075: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1076: return (\%returnhash,\@order);
1077: }
1078: my ($hashitems,$orderitems) = split(/:/,$rep);
1079: my @pairs=split(/\&/,$hashitems);
1080: foreach my $item (@pairs) {
1081: my ($key,$value)=split(/=/,$item,2);
1082: $key = &unescape($key);
1083: next if ($key =~ /^error: 2 /);
1084: $returnhash{$key}=&thaw_unescape($value);
1085: }
1086: my @esc_order = split(/\&/,$orderitems);
1087: foreach my $item (@esc_order) {
1088: push(@order,&unescape($item));
1089: }
1090: } else {
1091: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1092: }
1093: }
1094: return (\%returnhash,\@order);
1095: }
1096:
1.868 raeburn 1097: sub is_domainimage {
1098: my ($url) = @_;
1099: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1100: if (&domain($1) ne '') {
1101: return '1';
1102: }
1103: }
1104: return;
1105: }
1106:
1.899 raeburn 1107: sub inst_directory_query {
1108: my ($srch) = @_;
1109: my $udom = $srch->{'srchdomain'};
1110: my %results;
1111: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1112: my $outcome;
1.899 raeburn 1113: if ($homeserver ne '') {
1.904 albertel 1114: my $queryid=&reply("querysend:instdirsearch:".
1115: &escape($srch->{'srchby'}).':'.
1116: &escape($srch->{'srchterm'}).':'.
1117: &escape($srch->{'srchtype'}),$homeserver);
1118: my $host=&hostname($homeserver);
1119: if ($queryid !~/^\Q$host\E\_/) {
1120: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1121: return;
1122: }
1123: my $response = &get_query_reply($queryid);
1124: my $maxtries = 5;
1125: my $tries = 1;
1126: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1127: $response = &get_query_reply($queryid);
1128: $tries ++;
1129: }
1130:
1131: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1132: if ($response eq 'unavailable') {
1133: $outcome = $response;
1134: } else {
1135: $outcome = 'ok';
1136: my @matches = split(/\n/,$response);
1137: foreach my $match (@matches) {
1138: my ($key,$value) = split(/=/,$match);
1139: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1140: }
1.899 raeburn 1141: }
1142: }
1143: }
1.909 raeburn 1144: return ($outcome,%results);
1.899 raeburn 1145: }
1146:
1147: sub usersearch {
1148: my ($srch) = @_;
1149: my $dom = $srch->{'srchdomain'};
1150: my %results;
1151: my %libserv = &all_library();
1152: my $query = 'usersearch';
1153: foreach my $tryserver (keys(%libserv)) {
1154: if (&host_domain($tryserver) eq $dom) {
1155: my $host=&hostname($tryserver);
1156: my $queryid=
1.911 raeburn 1157: &reply("querysend:".&escape($query).':'.
1158: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1159: &escape($srch->{'srchtype'}).':'.
1160: &escape($srch->{'srchterm'}),$tryserver);
1161: if ($queryid !~/^\Q$host\E\_/) {
1162: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1163: next;
1.899 raeburn 1164: }
1165: my $reply = &get_query_reply($queryid);
1166: my $maxtries = 1;
1167: my $tries = 1;
1168: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1169: $reply = &get_query_reply($queryid);
1170: $tries ++;
1171: }
1172: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1173: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1174: } else {
1.911 raeburn 1175: my @matches;
1176: if ($reply =~ /\n/) {
1177: @matches = split(/\n/,$reply);
1178: } else {
1179: @matches = split(/\&/,$reply);
1180: }
1.899 raeburn 1181: foreach my $match (@matches) {
1182: my ($uname,$udom,%userhash);
1.911 raeburn 1183: foreach my $entry (split(/:/,$match)) {
1184: my ($key,$value) =
1185: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1186: $userhash{$key} = $value;
1187: if ($key eq 'username') {
1188: $uname = $value;
1189: } elsif ($key eq 'domain') {
1190: $udom = $value;
1.911 raeburn 1191: }
1.899 raeburn 1192: }
1193: $results{$uname.':'.$udom} = \%userhash;
1194: }
1195: }
1196: }
1197: }
1198: return %results;
1199: }
1200:
1.912 raeburn 1201: sub get_instuser {
1202: my ($udom,$uname,$id) = @_;
1203: my $homeserver = &domain($udom,'primary');
1204: my ($outcome,%results);
1205: if ($homeserver ne '') {
1206: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1207: &escape($id).':'.&escape($udom),$homeserver);
1208: my $host=&hostname($homeserver);
1209: if ($queryid !~/^\Q$host\E\_/) {
1210: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1211: return;
1212: }
1213: my $response = &get_query_reply($queryid);
1214: my $maxtries = 5;
1215: my $tries = 1;
1216: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1217: $response = &get_query_reply($queryid);
1218: $tries ++;
1219: }
1220: if (!&error($response) && $response ne 'refused') {
1221: if ($response eq 'unavailable') {
1222: $outcome = $response;
1223: } else {
1224: $outcome = 'ok';
1225: my @matches = split(/\n/,$response);
1226: foreach my $match (@matches) {
1227: my ($key,$value) = split(/=/,$match);
1228: $results{&unescape($key)} = &thaw_unescape($value);
1229: }
1230: }
1231: }
1232: }
1233: my %userinfo;
1234: if (ref($results{$uname}) eq 'HASH') {
1235: %userinfo = %{$results{$uname}};
1236: }
1237: return ($outcome,%userinfo);
1238: }
1239:
1240: sub inst_rulecheck {
1.923 raeburn 1241: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1242: my %returnhash;
1243: if ($udom ne '') {
1244: if (ref($rules) eq 'ARRAY') {
1245: @{$rules} = map {&escape($_);} (@{$rules});
1246: my $rulestr = join(':',@{$rules});
1247: my $homeserver=&domain($udom,'primary');
1248: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1249: my $response;
1250: if ($item eq 'username') {
1251: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1252: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1253: $homeserver));
1.923 raeburn 1254: } elsif ($item eq 'id') {
1255: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1256: ':'.&escape($id).':'.$rulestr,
1257: $homeserver));
1.945 raeburn 1258: } elsif ($item eq 'selfcreate') {
1259: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1260: &escape($udom).':'.&escape($uname).
1261: ':'.$rulestr,$homeserver));
1.923 raeburn 1262: }
1.912 raeburn 1263: if ($response ne 'refused') {
1264: my @pairs=split(/\&/,$response);
1265: foreach my $item (@pairs) {
1266: my ($key,$value)=split(/=/,$item,2);
1267: $key = &unescape($key);
1268: next if ($key =~ /^error: 2 /);
1269: $returnhash{$key}=&thaw_unescape($value);
1270: }
1271: }
1272: }
1273: }
1274: }
1275: return %returnhash;
1276: }
1277:
1278: sub inst_userrules {
1.923 raeburn 1279: my ($udom,$check) = @_;
1.912 raeburn 1280: my (%ruleshash,@ruleorder);
1281: if ($udom ne '') {
1282: my $homeserver=&domain($udom,'primary');
1283: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1284: my $response;
1285: if ($check eq 'id') {
1286: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1287: $homeserver);
1.943 raeburn 1288: } elsif ($check eq 'email') {
1289: $response=&reply('instemailrules:'.&escape($udom),
1290: $homeserver);
1.923 raeburn 1291: } else {
1292: $response=&reply('instuserrules:'.&escape($udom),
1293: $homeserver);
1294: }
1.912 raeburn 1295: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1296: ($response ne 'unknown_cmd') &&
1.912 raeburn 1297: ($response ne 'no_such_host')) {
1298: my ($hashitems,$orderitems) = split(/:/,$response);
1299: my @pairs=split(/\&/,$hashitems);
1300: foreach my $item (@pairs) {
1301: my ($key,$value)=split(/=/,$item,2);
1302: $key = &unescape($key);
1303: next if ($key =~ /^error: 2 /);
1304: $ruleshash{$key}=&thaw_unescape($value);
1305: }
1306: my @esc_order = split(/\&/,$orderitems);
1307: foreach my $item (@esc_order) {
1308: push(@ruleorder,&unescape($item));
1309: }
1310: }
1311: }
1312: }
1313: return (\%ruleshash,\@ruleorder);
1314: }
1315:
1.976 raeburn 1316: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1317:
1318: sub get_domain_defaults {
1319: my ($domain) = @_;
1320: my $cachetime = 60*60*24;
1321: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1322: if (defined($cached)) {
1323: if (ref($result) eq 'HASH') {
1324: return %{$result};
1325: }
1326: }
1327: my %domdefaults;
1328: my %domconfig =
1.989 raeburn 1329: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1330: 'requestcourses','inststatus',
1331: 'coursedefaults'],$domain);
1.943 raeburn 1332: if (ref($domconfig{'defaults'}) eq 'HASH') {
1333: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1334: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1335: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1336: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1337: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1338: } else {
1339: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1340: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1341: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1342: }
1.976 raeburn 1343: if (ref($domconfig{'quotas'}) eq 'HASH') {
1344: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1345: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1346: } else {
1347: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1348: }
1349: my @usertools = ('aboutme','blog','portfolio');
1350: foreach my $item (@usertools) {
1351: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1352: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1353: }
1354: }
1355: }
1.985 raeburn 1356: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1357: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1358: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1359: }
1360: }
1.989 raeburn 1361: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1362: foreach my $item ('inststatustypes','inststatusorder') {
1363: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1364: }
1365: }
1.1047 raeburn 1366: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1367: foreach my $item ('canuse_pdfforms') {
1368: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1369: }
1370: }
1.943 raeburn 1371: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1372: $cachetime);
1373: return %domdefaults;
1374: }
1375:
1.344 www 1376: # --------------------------------------------------- Assign a key to a student
1377:
1378: sub assign_access_key {
1.364 www 1379: #
1380: # a valid key looks like uname:udom#comments
1381: # comments are being appended
1382: #
1.498 www 1383: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1384: $kdom=
1.620 albertel 1385: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1386: $knum=
1.620 albertel 1387: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1388: $cdom=
1.620 albertel 1389: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1390: $cnum=
1.620 albertel 1391: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1392: $udom=$env{'user.name'} unless (defined($udom));
1393: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1394: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1395: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1396: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1397: # assigned to this person
1398: # - this should not happen,
1.345 www 1399: # unless something went wrong
1400: # the first time around
1401: # ready to assign
1.364 www 1402: $logentry=$1.'; '.$logentry;
1.496 www 1403: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1404: $kdom,$knum) eq 'ok') {
1.345 www 1405: # key now belongs to user
1.346 www 1406: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1407: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1408: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1409: return 'ok';
1410: } else {
1411: return
1412: 'error: Count not permanently assign key, will need to be re-entered later.';
1413: }
1414: } else {
1415: return 'error: Could not assign key, try again later.';
1416: }
1.364 www 1417: } elsif (!$existing{$ckey}) {
1.345 www 1418: # the key does not exist
1419: return 'error: The key does not exist';
1420: } else {
1421: # the key is somebody else's
1422: return 'error: The key is already in use';
1423: }
1.344 www 1424: }
1425:
1.364 www 1426: # ------------------------------------------ put an additional comment on a key
1427:
1428: sub comment_access_key {
1429: #
1430: # a valid key looks like uname:udom#comments
1431: # comments are being appended
1432: #
1433: my ($ckey,$cdom,$cnum,$logentry)=@_;
1434: $cdom=
1.620 albertel 1435: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1436: $cnum=
1.620 albertel 1437: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1438: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1439: if ($existing{$ckey}) {
1440: $existing{$ckey}.='; '.$logentry;
1441: # ready to assign
1.367 www 1442: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1443: $cdom,$cnum) eq 'ok') {
1444: return 'ok';
1445: } else {
1446: return 'error: Count not store comment.';
1447: }
1448: } else {
1449: # the key does not exist
1450: return 'error: The key does not exist';
1451: }
1452: }
1453:
1.344 www 1454: # ------------------------------------------------------ Generate a set of keys
1455:
1456: sub generate_access_keys {
1.364 www 1457: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1458: $cdom=
1.620 albertel 1459: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1460: $cnum=
1.620 albertel 1461: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1462: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1463: unless (($cdom) && ($cnum)) { return 0; }
1464: if ($number>10000) { return 0; }
1465: sleep(2); # make sure don't get same seed twice
1466: srand(time()^($$+($$<<15))); # from "Programming Perl"
1467: my $total=0;
1468: for (my $i=1;$i<=$number;$i++) {
1469: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1470: sprintf("%lx",int(100000*rand)).'-'.
1471: sprintf("%lx",int(100000*rand));
1472: $newkey=~s/1/g/g; # folks mix up 1 and l
1473: $newkey=~s/0/h/g; # and also 0 and O
1474: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1475: if ($existing{$newkey}) {
1476: $i--;
1477: } else {
1.364 www 1478: if (&put('accesskeys',
1479: { $newkey => '# generated '.localtime().
1.620 albertel 1480: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1481: '; '.$logentry },
1482: $cdom,$cnum) eq 'ok') {
1.344 www 1483: $total++;
1484: }
1485: }
1486: }
1.620 albertel 1487: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1488: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1489: return $total;
1490: }
1491:
1492: # ------------------------------------------------------- Validate an accesskey
1493:
1494: sub validate_access_key {
1495: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1496: $cdom=
1.620 albertel 1497: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1498: $cnum=
1.620 albertel 1499: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1500: $udom=$env{'user.domain'} unless (defined($udom));
1501: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1502: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1503: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1504: }
1505:
1506: # ------------------------------------- Find the section of student in a course
1.652 albertel 1507: sub devalidate_getsection_cache {
1508: my ($udom,$unam,$courseid)=@_;
1509: my $hashid="$udom:$unam:$courseid";
1510: &devalidate_cache_new('getsection',$hashid);
1511: }
1.298 matthew 1512:
1.815 albertel 1513: sub courseid_to_courseurl {
1514: my ($courseid) = @_;
1515: #already url style courseid
1516: return $courseid if ($courseid =~ m{^/});
1517:
1518: if (exists($env{'course.'.$courseid.'.num'})) {
1519: my $cnum = $env{'course.'.$courseid.'.num'};
1520: my $cdom = $env{'course.'.$courseid.'.domain'};
1521: return "/$cdom/$cnum";
1522: }
1523:
1524: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1525: if (exists($courseinfo{'num'})) {
1526: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1527: }
1528:
1529: return undef;
1530: }
1531:
1.298 matthew 1532: sub getsection {
1533: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1534: my $cachetime=1800;
1.551 albertel 1535:
1536: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1537: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1538: if (defined($cached)) { return $result; }
1539:
1.298 matthew 1540: my %Pending;
1541: my %Expired;
1542: #
1543: # Each role can either have not started yet (pending), be active,
1544: # or have expired.
1545: #
1546: # If there is an active role, we are done.
1547: #
1548: # If there is more than one role which has not started yet,
1549: # choose the one which will start sooner
1550: # If there is one role which has not started yet, return it.
1551: #
1552: # If there is more than one expired role, choose the one which ended last.
1553: # If there is a role which has expired, return it.
1554: #
1.815 albertel 1555: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1556: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1557: foreach my $key (keys(%roleshash)) {
1.479 albertel 1558: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1559: my $section=$1;
1560: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1561: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1562: my $now=time;
1.548 albertel 1563: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1564: $Expired{$end}=$section;
1565: next;
1566: }
1.548 albertel 1567: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1568: $Pending{$start}=$section;
1569: next;
1570: }
1.599 albertel 1571: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1572: }
1573: #
1574: # Presumedly there will be few matching roles from the above
1575: # loop and the sorting time will be negligible.
1576: if (scalar(keys(%Pending))) {
1577: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1578: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1579: }
1580: if (scalar(keys(%Expired))) {
1581: my @sorted = sort {$a <=> $b} keys(%Expired);
1582: my $time = pop(@sorted);
1.599 albertel 1583: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1584: }
1.599 albertel 1585: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1586: }
1.70 www 1587:
1.599 albertel 1588: sub save_cache {
1589: &purge_remembered();
1.722 albertel 1590: #&Apache::loncommon::validate_page();
1.620 albertel 1591: undef(%env);
1.780 albertel 1592: undef($env_loaded);
1.599 albertel 1593: }
1.452 albertel 1594:
1.599 albertel 1595: my $to_remember=-1;
1596: my %remembered;
1597: my %accessed;
1598: my $kicks=0;
1599: my $hits=0;
1.849 albertel 1600: sub make_key {
1601: my ($name,$id) = @_;
1.872 albertel 1602: if (length($id) > 65
1603: && length(&escape($id)) > 200) {
1604: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1605: }
1.849 albertel 1606: return &escape($name.':'.$id);
1607: }
1608:
1.599 albertel 1609: sub devalidate_cache_new {
1610: my ($name,$id,$debug) = @_;
1611: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1612: $id=&make_key($name,$id);
1.599 albertel 1613: $memcache->delete($id);
1614: delete($remembered{$id});
1615: delete($accessed{$id});
1616: }
1617:
1618: sub is_cached_new {
1619: my ($name,$id,$debug) = @_;
1.849 albertel 1620: $id=&make_key($name,$id);
1.599 albertel 1621: if (exists($remembered{$id})) {
1622: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1623: $accessed{$id}=[&gettimeofday()];
1624: $hits++;
1625: return ($remembered{$id},1);
1626: }
1627: my $value = $memcache->get($id);
1628: if (!(defined($value))) {
1629: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1630: return (undef,undef);
1.416 albertel 1631: }
1.599 albertel 1632: if ($value eq '__undef__') {
1633: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1634: $value=undef;
1635: }
1636: &make_room($id,$value,$debug);
1637: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1638: return ($value,1);
1639: }
1640:
1641: sub do_cache_new {
1642: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1643: $id=&make_key($name,$id);
1.599 albertel 1644: my $setvalue=$value;
1645: if (!defined($setvalue)) {
1646: $setvalue='__undef__';
1647: }
1.623 albertel 1648: if (!defined($time) ) {
1649: $time=600;
1650: }
1.599 albertel 1651: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1652: my $result = $memcache->set($id,$setvalue,$time);
1653: if (! $result) {
1.872 albertel 1654: &logthis("caching of id -> $id failed");
1.910 albertel 1655: $memcache->disconnect_all();
1.872 albertel 1656: }
1.600 albertel 1657: # need to make a copy of $value
1.919 albertel 1658: &make_room($id,$value,$debug);
1.599 albertel 1659: return $value;
1660: }
1661:
1662: sub make_room {
1663: my ($id,$value,$debug)=@_;
1.919 albertel 1664:
1665: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1666: : $value;
1.599 albertel 1667: if ($to_remember<0) { return; }
1668: $accessed{$id}=[&gettimeofday()];
1669: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1670: my $to_kick;
1671: my $max_time=0;
1672: foreach my $other (keys(%accessed)) {
1673: if (&tv_interval($accessed{$other}) > $max_time) {
1674: $to_kick=$other;
1675: $max_time=&tv_interval($accessed{$other});
1676: }
1677: }
1678: delete($remembered{$to_kick});
1679: delete($accessed{$to_kick});
1680: $kicks++;
1681: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1682: return;
1683: }
1684:
1.599 albertel 1685: sub purge_remembered {
1.604 albertel 1686: #&logthis("Tossing ".scalar(keys(%remembered)));
1687: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1688: undef(%remembered);
1689: undef(%accessed);
1.428 albertel 1690: }
1.70 www 1691: # ------------------------------------- Read an entry from a user's environment
1692:
1693: sub userenvironment {
1694: my ($udom,$unam,@what)=@_;
1.976 raeburn 1695: my $items;
1696: foreach my $item (@what) {
1697: $items.=&escape($item).'&';
1698: }
1699: $items=~s/\&$//;
1.70 www 1700: my %returnhash=();
1.1009 raeburn 1701: my $uhome = &homeserver($unam,$udom);
1702: unless ($uhome eq 'no_host') {
1703: my @answer=split(/\&/,
1704: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1705: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1706: return %returnhash;
1707: }
1.1009 raeburn 1708: my $i;
1709: for ($i=0;$i<=$#what;$i++) {
1710: $returnhash{$what[$i]}=&unescape($answer[$i]);
1711: }
1.70 www 1712: }
1713: return %returnhash;
1.1 albertel 1714: }
1715:
1.617 albertel 1716: # ---------------------------------------------------------- Get a studentphoto
1717: sub studentphoto {
1718: my ($udom,$unam,$ext) = @_;
1719: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1720: if (defined($env{'request.course.id'})) {
1.708 raeburn 1721: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1722: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1723: return(&retrievestudentphoto($udom,$unam,$ext));
1724: } else {
1725: my ($result,$perm_reqd)=
1.707 albertel 1726: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1727: if ($result eq 'ok') {
1728: if (!($perm_reqd eq 'yes')) {
1729: return(&retrievestudentphoto($udom,$unam,$ext));
1730: }
1731: }
1732: }
1733: }
1734: } else {
1735: my ($result,$perm_reqd) =
1.707 albertel 1736: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1737: if ($result eq 'ok') {
1738: if (!($perm_reqd eq 'yes')) {
1739: return(&retrievestudentphoto($udom,$unam,$ext));
1740: }
1741: }
1742: }
1743: return '/adm/lonKaputt/lonlogo_broken.gif';
1744: }
1745:
1746: sub retrievestudentphoto {
1747: my ($udom,$unam,$ext,$type) = @_;
1748: my $home=&Apache::lonnet::homeserver($unam,$udom);
1749: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1750: if ($ret eq 'ok') {
1751: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1752: if ($type eq 'thumbnail') {
1753: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1754: }
1755: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1756: return $tokenurl;
1757: } else {
1758: if ($type eq 'thumbnail') {
1759: return '/adm/lonKaputt/genericstudent_tn.gif';
1760: } else {
1761: return '/adm/lonKaputt/lonlogo_broken.gif';
1762: }
1.617 albertel 1763: }
1764: }
1765:
1.263 www 1766: # -------------------------------------------------------------------- New chat
1767:
1768: sub chatsend {
1.724 raeburn 1769: my ($newentry,$anon,$group)=@_;
1.620 albertel 1770: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1771: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1772: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1773: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1774: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1775: &escape($newentry)).':'.$group,$chome);
1.292 www 1776: }
1777:
1778: # ------------------------------------------ Find current version of a resource
1779:
1780: sub getversion {
1781: my $fname=&clutter(shift);
1782: unless ($fname=~/^\/res\//) { return -1; }
1783: return ¤tversion(&filelocation('',$fname));
1784: }
1785:
1786: sub currentversion {
1787: my $fname=shift;
1.599 albertel 1788: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1789: if (defined($cached)) { return $result; }
1.292 www 1790: my $author=$fname;
1791: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1792: my ($udom,$uname)=split(/\//,$author);
1793: my $home=homeserver($uname,$udom);
1794: if ($home eq 'no_host') {
1795: return -1;
1796: }
1797: my $answer=reply("currentversion:$fname",$home);
1798: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1799: return -1;
1800: }
1.599 albertel 1801: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1802: }
1803:
1.1 albertel 1804: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1805:
1.1 albertel 1806: sub subscribe {
1807: my $fname=shift;
1.761 raeburn 1808: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1809: $fname=~s/[\n\r]//g;
1.1 albertel 1810: my $author=$fname;
1811: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1812: my ($udom,$uname)=split(/\//,$author);
1813: my $home=homeserver($uname,$udom);
1.335 albertel 1814: if ($home eq 'no_host') {
1815: return 'not_found';
1.1 albertel 1816: }
1817: my $answer=reply("sub:$fname",$home);
1.64 www 1818: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1819: $answer.=' by '.$home;
1820: }
1.1 albertel 1821: return $answer;
1822: }
1823:
1.8 www 1824: # -------------------------------------------------------------- Replicate file
1825:
1826: sub repcopy {
1827: my $filename=shift;
1.23 www 1828: $filename=~s/\/+/\//g;
1.607 raeburn 1829: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1830: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1831: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1832: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1833: return &repcopy_userfile($filename);
1834: }
1.532 albertel 1835: $filename=~s/[\n\r]//g;
1.8 www 1836: my $transname="$filename.in.transfer";
1.828 www 1837: # FIXME: this should flock
1.607 raeburn 1838: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1839: my $remoteurl=subscribe($filename);
1.64 www 1840: if ($remoteurl =~ /^con_lost by/) {
1841: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1842: return 'unavailable';
1.8 www 1843: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1844: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1845: return 'not_found';
1.64 www 1846: } elsif ($remoteurl =~ /^rejected by/) {
1847: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1848: return 'forbidden';
1.20 www 1849: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1850: return 'ok';
1.8 www 1851: } else {
1.290 www 1852: my $author=$filename;
1853: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1854: my ($udom,$uname)=split(/\//,$author);
1855: my $home=homeserver($uname,$udom);
1856: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1857: my @parts=split(/\//,$filename);
1858: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1859: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1860: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1861: return 'bad_request';
1.8 www 1862: }
1863: my $count;
1864: for ($count=5;$count<$#parts;$count++) {
1865: $path.="/$parts[$count]";
1866: if ((-e $path)!=1) {
1867: mkdir($path,0777);
1868: }
1869: }
1870: my $ua=new LWP::UserAgent;
1871: my $request=new HTTP::Request('GET',"$remoteurl");
1872: my $response=$ua->request($request,$transname);
1873: if ($response->is_error()) {
1874: unlink($transname);
1875: my $message=$response->status_line;
1.672 albertel 1876: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1877: ." LWP get: $message: $filename</font>");
1.607 raeburn 1878: return 'unavailable';
1.8 www 1879: } else {
1.16 www 1880: if ($remoteurl!~/\.meta$/) {
1881: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1882: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1883: if ($mresponse->is_error()) {
1884: unlink($filename.'.meta');
1885: &logthis(
1.672 albertel 1886: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1887: }
1888: }
1.8 www 1889: rename($transname,$filename);
1.607 raeburn 1890: return 'ok';
1.8 www 1891: }
1.290 www 1892: }
1.8 www 1893: }
1.330 www 1894: }
1895:
1896: # ------------------------------------------------ Get server side include body
1897: sub ssi_body {
1.381 albertel 1898: my ($filelink,%form)=@_;
1.606 matthew 1899: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1900: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1901: }
1.953 www 1902: my $output='';
1903: my $response;
1.980 raeburn 1904: if ($filelink=~/^https?\:/) {
1.954 raeburn 1905: ($output,$response)=&externalssi($filelink);
1.953 www 1906: } else {
1.1004 droeschl 1907: $filelink .= $filelink=~/\?/ ? '&' : '?';
1908: $filelink .= 'inhibitmenu=yes';
1.953 www 1909: ($output,$response)=&ssi($filelink,%form);
1910: }
1.778 albertel 1911: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1912: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1913: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1914: if (wantarray) {
1915: return ($output, $response);
1916: } else {
1917: return $output;
1918: }
1.8 www 1919: }
1920:
1.15 www 1921: # --------------------------------------------------------- Server Side Include
1922:
1.782 albertel 1923: sub absolute_url {
1924: my ($host_name) = @_;
1925: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1926: if ($host_name eq '') {
1927: $host_name = $ENV{'SERVER_NAME'};
1928: }
1929: return $protocol.$host_name;
1930: }
1931:
1.942 foxr 1932: #
1933: # Server side include.
1934: # Parameters:
1935: # fn Possibly encrypted resource name/id.
1936: # form Hash that describes how the rendering should be done
1937: # and other things.
1.944 foxr 1938: # Returns:
1.950 raeburn 1939: # Scalar context: The content of the response.
1940: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1941: #
1.15 www 1942: sub ssi {
1943:
1.944 foxr 1944: my ($fn,%form)=@_;
1.15 www 1945: my $ua=new LWP::UserAgent;
1.23 www 1946: my $request;
1.711 albertel 1947:
1948: $form{'no_update_last_known'}=1;
1.895 albertel 1949: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1950: if (%form) {
1.782 albertel 1951: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 1952: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 1953: } else {
1.782 albertel 1954: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1955: }
1956:
1.15 www 1957: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1958: my $response=$ua->request($request);
1959:
1.944 foxr 1960: if (wantarray) {
1961: return ($response->content, $response);
1962: } else {
1963: return $response->content;
1.942 foxr 1964: }
1.324 www 1965: }
1966:
1967: sub externalssi {
1968: my ($url)=@_;
1969: my $ua=new LWP::UserAgent;
1970: my $request=new HTTP::Request('GET',$url);
1971: my $response=$ua->request($request);
1.954 raeburn 1972: if (wantarray) {
1973: return ($response->content, $response);
1974: } else {
1975: return $response->content;
1976: }
1.15 www 1977: }
1.254 www 1978:
1.492 albertel 1979: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1980:
1981: sub allowuploaded {
1982: my ($srcurl,$url)=@_;
1983: $url=&clutter(&declutter($url));
1984: my $dir=$url;
1985: $dir=~s/\/[^\/]+$//;
1986: my %httpref=();
1987: my $httpurl=&hreflocation('',$url);
1988: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 1989: &Apache::lonnet::appenv(\%httpref);
1.254 www 1990: }
1.477 raeburn 1991:
1.478 albertel 1992: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1993: # input: action, courseID, current domain, intended
1.637 raeburn 1994: # path to file, source of file, instruction to parse file for objects,
1995: # ref to hash for embedded objects,
1996: # ref to hash for codebase of java objects.
1997: #
1.485 raeburn 1998: # output: url to file (if action was uploaddoc),
1999: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2000: #
1.478 albertel 2001: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2002: # course.
1.477 raeburn 2003: #
1.478 albertel 2004: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2005: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2006: # course's home server.
1.477 raeburn 2007: #
1.478 albertel 2008: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2009: # be copied from $source (current location) to
2010: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2011: # and will then be copied to
2012: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2013: # course's home server.
1.485 raeburn 2014: #
1.481 raeburn 2015: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2016: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2017: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2018: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2019: # in course's home server.
1.637 raeburn 2020: #
1.477 raeburn 2021:
2022: sub process_coursefile {
1.638 albertel 2023: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2024: my $fetchresult;
1.638 albertel 2025: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2026: if ($action eq 'propagate') {
1.638 albertel 2027: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2028: $home);
1.481 raeburn 2029: } else {
1.477 raeburn 2030: my $fpath = '';
2031: my $fname = $file;
1.478 albertel 2032: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2033: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2034: my $filepath = &build_filepath($fpath);
1.481 raeburn 2035: if ($action eq 'copy') {
2036: if ($source eq '') {
2037: $fetchresult = 'no source file';
2038: return $fetchresult;
2039: } else {
2040: my $destination = $filepath.'/'.$fname;
2041: rename($source,$destination);
2042: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2043: $home);
1.481 raeburn 2044: }
2045: } elsif ($action eq 'uploaddoc') {
2046: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2047: print $fh $env{'form.'.$source};
1.481 raeburn 2048: close($fh);
1.637 raeburn 2049: if ($parser eq 'parse') {
1.1024 raeburn 2050: my $mm = new File::MMagic;
2051: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2052: if ($mime_type eq 'text/html') {
2053: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2054: unless ($parse_result eq 'ok') {
2055: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2056: }
1.637 raeburn 2057: }
2058: }
1.477 raeburn 2059: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2060: $home);
1.481 raeburn 2061: if ($fetchresult eq 'ok') {
2062: return '/uploaded/'.$fpath.'/'.$fname;
2063: } else {
2064: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2065: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2066: return '/adm/notfound.html';
2067: }
1.477 raeburn 2068: }
2069: }
1.485 raeburn 2070: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2071: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2072: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2073: }
2074: return $fetchresult;
2075: }
2076:
1.637 raeburn 2077: sub build_filepath {
2078: my ($fpath) = @_;
2079: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2080: unless ($fpath eq '') {
2081: my @parts=split('/',$fpath);
2082: foreach my $part (@parts) {
2083: $filepath.= '/'.$part;
2084: if ((-e $filepath)!=1) {
2085: mkdir($filepath,0777);
2086: }
2087: }
2088: }
2089: return $filepath;
2090: }
2091:
2092: sub store_edited_file {
1.638 albertel 2093: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2094: my $file = $primary_url;
2095: $file =~ s#^/uploaded/$docudom/$docuname/##;
2096: my $fpath = '';
2097: my $fname = $file;
2098: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2099: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2100: my $filepath = &build_filepath($fpath);
2101: open(my $fh,'>'.$filepath.'/'.$fname);
2102: print $fh $content;
2103: close($fh);
1.638 albertel 2104: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2105: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2106: $home);
1.637 raeburn 2107: if ($$fetchresult eq 'ok') {
2108: return '/uploaded/'.$fpath.'/'.$fname;
2109: } else {
1.638 albertel 2110: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2111: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2112: return '/adm/notfound.html';
2113: }
2114: }
2115:
1.531 albertel 2116: sub clean_filename {
1.831 albertel 2117: my ($fname,$args)=@_;
1.315 www 2118: # Replace Windows backslashes by forward slashes
1.257 www 2119: $fname=~s/\\/\//g;
1.831 albertel 2120: if (!$args->{'keep_path'}) {
2121: # Get rid of everything but the actual filename
2122: $fname=~s/^.*\/([^\/]+)$/$1/;
2123: }
1.315 www 2124: # Replace spaces by underscores
2125: $fname=~s/\s+/\_/g;
2126: # Replace all other weird characters by nothing
1.831 albertel 2127: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2128: # Replace all .\d. sequences with _\d. so they no longer look like version
2129: # numbers
2130: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2131: return $fname;
2132: }
1.1051 raeburn 2133: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2134: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2135: # image with the same aspect ratio as the original, but with dimensions which do
2136: # not exceed $resizewidth and $resizeheight.
2137:
1.984 neumanie 2138: sub resizeImage {
1.1051 raeburn 2139: my ($img_path,$resizewidth,$resizeheight) = @_;
2140: my $ima = Image::Magick->new;
2141: my $resized;
2142: if (-e $img_path) {
2143: $ima->Read($img_path);
2144: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2145: my $width = $ima->Get('width');
2146: my $height = $ima->Get('height');
2147: if ($width > $resizewidth) {
2148: my $factor = $width/$resizewidth;
2149: my $newheight = $height/$factor;
2150: $ima->Scale(width=>$resizewidth,height=>$newheight);
2151: $resized = 1;
2152: }
2153: }
2154: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2155: my $width = $ima->Get('width');
2156: my $height = $ima->Get('height');
2157: if ($height > $resizeheight) {
2158: my $factor = $height/$resizeheight;
2159: my $newwidth = $width/$factor;
2160: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2161: $resized = 1;
2162: }
2163: }
2164: if ($resized) {
2165: $ima->Write($img_path);
2166: }
2167: }
2168: return;
1.977 amueller 2169: }
2170:
1.608 albertel 2171: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2172: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2173: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2174: # $coursedoc - if true up to the current course
2175: # if false
2176: # $subdir - directory in userfile to store the file into
1.858 raeburn 2177: # $parser - instruction to parse file for objects ($parser = parse)
2178: # $allfiles - reference to hash for embedded objects
2179: # $codebase - reference to hash for codebase of java objects
2180: # $desuname - username for permanent storage of uploaded file
2181: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2182: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2183: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2184: # $resizewidth - width (pixels) to which to resize uploaded image
2185: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2186: #
1.686 albertel 2187: # output: url of file in userspace, or error: <message>
2188: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2189:
1.531 albertel 2190: sub userfileupload {
1.860 raeburn 2191: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2192: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2193: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2194: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2195: $fname=&clean_filename($fname);
1.315 www 2196: # See if there is anything left
1.257 www 2197: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2198: chop($env{'form.'.$formname});
1.523 raeburn 2199: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2200: my $now = time;
2201: my $filepath = 'tmp/helprequests/'.$now;
2202: my @parts=split(/\//,$filepath);
2203: my $fullpath = $perlvar{'lonDaemons'};
2204: for (my $i=0;$i<@parts;$i++) {
2205: $fullpath .= '/'.$parts[$i];
2206: if ((-e $fullpath)!=1) {
2207: mkdir($fullpath,0777);
2208: }
2209: }
2210: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2211: print $fh $env{'form.'.$formname};
1.523 raeburn 2212: close($fh);
1.741 raeburn 2213: return $fullpath.'/'.$fname;
2214: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2215: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2216: '_'.$env{'user.domain'}.'/pending';
2217: my @parts=split(/\//,$filepath);
2218: my $fullpath = $perlvar{'lonDaemons'};
2219: for (my $i=0;$i<@parts;$i++) {
2220: $fullpath .= '/'.$parts[$i];
2221: if ((-e $fullpath)!=1) {
2222: mkdir($fullpath,0777);
2223: }
2224: }
2225: open(my $fh,'>'.$fullpath.'/'.$fname);
2226: print $fh $env{'form.'.$formname};
2227: close($fh);
2228: return $fullpath.'/'.$fname;
1.523 raeburn 2229: }
1.995 raeburn 2230: if ($subdir eq 'scantron') {
2231: $fname = 'scantron_orig_'.$fname;
2232: } else {
1.258 www 2233: # Create the directory if not present
1.995 raeburn 2234: $fname="$subdir/$fname";
2235: }
1.259 www 2236: if ($coursedoc) {
1.638 albertel 2237: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2238: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2239: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2240: return &finishuserfileupload($docuname,$docudom,
2241: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2242: $codebase,$thumbwidth,$thumbheight,
2243: $resizewidth,$resizeheight);
1.481 raeburn 2244: } else {
1.620 albertel 2245: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2246: return &process_coursefile('uploaddoc',$docuname,$docudom,
2247: $fname,$formname,$parser,
2248: $allfiles,$codebase);
1.481 raeburn 2249: }
1.719 banghart 2250: } elsif (defined($destuname)) {
2251: my $docuname=$destuname;
2252: my $docudom=$destudom;
1.860 raeburn 2253: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2254: $parser,$allfiles,$codebase,
1.1051 raeburn 2255: $thumbwidth,$thumbheight,
2256: $resizewidth,$resizeheight);
1.719 banghart 2257:
1.259 www 2258: } else {
1.638 albertel 2259: my $docuname=$env{'user.name'};
2260: my $docudom=$env{'user.domain'};
1.714 raeburn 2261: if (exists($env{'form.group'})) {
2262: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2263: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2264: }
1.860 raeburn 2265: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2266: $parser,$allfiles,$codebase,
1.1051 raeburn 2267: $thumbwidth,$thumbheight,
2268: $resizewidth,$resizeheight);
1.259 www 2269: }
1.271 www 2270: }
2271:
2272: sub finishuserfileupload {
1.860 raeburn 2273: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2274: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2275: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2276: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2277:
1.860 raeburn 2278: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2279: $file=$fname;
2280: if ($fname=~m|/|) {
2281: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2282: $path.=$fnamepath.'/';
2283: }
1.259 www 2284: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2285: my $count;
2286: for ($count=4;$count<=$#parts;$count++) {
2287: $filepath.="/$parts[$count]";
2288: if ((-e $filepath)!=1) {
2289: mkdir($filepath,0777);
2290: }
2291: }
1.984 neumanie 2292:
1.258 www 2293: # Save the file
2294: {
1.701 albertel 2295: if (!open(FH,'>'.$filepath.'/'.$file)) {
2296: &logthis('Failed to create '.$filepath.'/'.$file);
2297: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2298: return '/adm/notfound.html';
2299: }
2300: if (!print FH ($env{'form.'.$formname})) {
2301: &logthis('Failed to write to '.$filepath.'/'.$file);
2302: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2303: return '/adm/notfound.html';
2304: }
1.570 albertel 2305: close(FH);
1.1051 raeburn 2306: if ($resizewidth && $resizeheight) {
2307: my $mm = new File::MMagic;
2308: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2309: if ($mime_type =~ m{^image/}) {
2310: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2311: }
1.977 amueller 2312: }
1.258 www 2313: }
1.637 raeburn 2314: if ($parser eq 'parse') {
1.1024 raeburn 2315: my $mm = new File::MMagic;
2316: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2317: if ($mime_type eq 'text/html') {
2318: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2319: $allfiles,$codebase);
2320: unless ($parse_result eq 'ok') {
2321: &logthis('Failed to parse '.$filepath.$file.
2322: ' for embedded media: '.$parse_result);
2323: }
1.637 raeburn 2324: }
2325: }
1.860 raeburn 2326: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2327: my $input = $filepath.'/'.$file;
2328: my $output = $filepath.'/'.'tn-'.$file;
2329: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2330: system("convert -sample $thumbsize $input $output");
2331: if (-e $filepath.'/'.'tn-'.$file) {
2332: $fetchthumb = 1;
2333: }
2334: }
1.858 raeburn 2335:
1.259 www 2336: # Notify homeserver to grep it
2337: #
1.984 neumanie 2338: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2339: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2340: if ($fetchresult eq 'ok') {
1.860 raeburn 2341: if ($fetchthumb) {
2342: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2343: if ($thumbresult ne 'ok') {
2344: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2345: $docuhome.': '.$thumbresult);
2346: }
2347: }
1.259 www 2348: #
1.258 www 2349: # Return the URL to it
1.494 albertel 2350: return '/uploaded/'.$path.$file;
1.263 www 2351: } else {
1.494 albertel 2352: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2353: ': '.$fetchresult);
1.263 www 2354: return '/adm/notfound.html';
1.858 raeburn 2355: }
1.493 albertel 2356: }
2357:
1.637 raeburn 2358: sub extract_embedded_items {
1.961 raeburn 2359: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2360: my @state = ();
2361: my %javafiles = (
2362: codebase => '',
2363: code => '',
2364: archive => ''
2365: );
2366: my %mediafiles = (
2367: src => '',
2368: movie => '',
2369: );
1.648 raeburn 2370: my $p;
2371: if ($content) {
2372: $p = HTML::LCParser->new($content);
2373: } else {
1.961 raeburn 2374: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2375: }
1.641 albertel 2376: while (my $t=$p->get_token()) {
1.640 albertel 2377: if ($t->[0] eq 'S') {
2378: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2379: push(@state, $tagname);
1.648 raeburn 2380: if (lc($tagname) eq 'allow') {
2381: &add_filetype($allfiles,$attr->{'src'},'src');
2382: }
1.640 albertel 2383: if (lc($tagname) eq 'img') {
2384: &add_filetype($allfiles,$attr->{'src'},'src');
2385: }
1.886 albertel 2386: if (lc($tagname) eq 'a') {
2387: &add_filetype($allfiles,$attr->{'href'},'href');
2388: }
1.645 raeburn 2389: if (lc($tagname) eq 'script') {
2390: if ($attr->{'archive'} =~ /\.jar$/i) {
2391: &add_filetype($allfiles,$attr->{'archive'},'archive');
2392: } else {
2393: &add_filetype($allfiles,$attr->{'src'},'src');
2394: }
2395: }
2396: if (lc($tagname) eq 'link') {
2397: if (lc($attr->{'rel'}) eq 'stylesheet') {
2398: &add_filetype($allfiles,$attr->{'href'},'href');
2399: }
2400: }
1.640 albertel 2401: if (lc($tagname) eq 'object' ||
2402: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2403: foreach my $item (keys(%javafiles)) {
2404: $javafiles{$item} = '';
2405: }
2406: }
2407: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2408: my $name = lc($attr->{'name'});
2409: foreach my $item (keys(%javafiles)) {
2410: if ($name eq $item) {
2411: $javafiles{$item} = $attr->{'value'};
2412: last;
2413: }
2414: }
2415: foreach my $item (keys(%mediafiles)) {
2416: if ($name eq $item) {
2417: &add_filetype($allfiles, $attr->{'value'}, 'value');
2418: last;
2419: }
2420: }
2421: }
2422: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2423: foreach my $item (keys(%javafiles)) {
2424: if ($attr->{$item}) {
2425: $javafiles{$item} = $attr->{$item};
2426: last;
2427: }
2428: }
2429: foreach my $item (keys(%mediafiles)) {
2430: if ($attr->{$item}) {
2431: &add_filetype($allfiles,$attr->{$item},$item);
2432: last;
2433: }
2434: }
2435: }
2436: } elsif ($t->[0] eq 'E') {
2437: my ($tagname) = ($t->[1]);
2438: if ($javafiles{'codebase'} ne '') {
2439: $javafiles{'codebase'} .= '/';
2440: }
2441: if (lc($tagname) eq 'applet' ||
2442: lc($tagname) eq 'object' ||
2443: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2444: ) {
2445: foreach my $item (keys(%javafiles)) {
2446: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2447: my $file=$javafiles{'codebase'}.$javafiles{$item};
2448: &add_filetype($allfiles,$file,$item);
2449: }
2450: }
2451: }
2452: pop @state;
2453: }
2454: }
1.637 raeburn 2455: return 'ok';
2456: }
2457:
1.639 albertel 2458: sub add_filetype {
2459: my ($allfiles,$file,$type)=@_;
2460: if (exists($allfiles->{$file})) {
2461: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2462: push(@{$allfiles->{$file}}, &escape($type));
2463: }
2464: } else {
2465: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2466: }
2467: }
2468:
1.493 albertel 2469: sub removeuploadedurl {
1.984 neumanie 2470: my ($url)=@_;
2471: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2472: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2473: }
2474:
2475: sub removeuserfile {
2476: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2477: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2478: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2479: if ($result eq 'ok') {
1.798 raeburn 2480: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2481: my $metafile = $fname.'.meta';
2482: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2483: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2484: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2485: my $sqlresult =
1.823 albertel 2486: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2487: 'portfolio_metadata',$group,
2488: 'delete');
1.798 raeburn 2489: }
2490: }
2491: return $result;
1.257 www 2492: }
1.15 www 2493:
1.530 albertel 2494: sub mkdiruserfile {
2495: my ($docuname,$docudom,$dir)=@_;
2496: my $home=&homeserver($docuname,$docudom);
2497: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2498: }
2499:
1.531 albertel 2500: sub renameuserfile {
2501: my ($docuname,$docudom,$old,$new)=@_;
2502: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2503: my $result = &reply("renameuserfile:$docudom:$docuname:".
2504: &escape("$old").':'.&escape("$new"),$home);
2505: if ($result eq 'ok') {
2506: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2507: my $oldmeta = $old.'.meta';
2508: my $newmeta = $new.'.meta';
2509: my $metaresult =
2510: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2511: my $url = "/uploaded/$docudom/$docuname/$old";
2512: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2513: my $sqlresult =
1.823 albertel 2514: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2515: 'portfolio_metadata',$group,
2516: 'delete');
1.798 raeburn 2517: }
2518: }
2519: return $result;
1.531 albertel 2520: }
2521:
1.14 www 2522: # ------------------------------------------------------------------------- Log
2523:
2524: sub log {
2525: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2526: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2527: }
2528:
2529: # ------------------------------------------------------------------ Course Log
1.352 www 2530: #
2531: # This routine flushes several buffers of non-mission-critical nature
2532: #
1.157 www 2533:
2534: sub flushcourselogs {
1.352 www 2535: &logthis('Flushing log buffers');
2536: #
2537: # course logs
2538: # This is a log of all transactions in a course, which can be used
2539: # for data mining purposes
2540: #
2541: # It also collects the courseid database, which lists last transaction
2542: # times and course titles for all courseids
2543: #
2544: my %courseidbuffer=();
1.921 raeburn 2545: foreach my $crsid (keys(%courselogs)) {
1.352 www 2546: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2547: &escape($courselogs{$crsid}),
2548: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2549: delete $courselogs{$crsid};
2550: } else {
2551: &logthis('Failed to flush log buffer for '.$crsid);
2552: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2553: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2554: " exceeded maximum size, deleting.</font>");
2555: delete $courselogs{$crsid};
2556: }
1.352 www 2557: }
1.920 raeburn 2558: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2559: 'description' => $coursedescrbuf{$crsid},
2560: 'inst_code' => $courseinstcodebuf{$crsid},
2561: 'type' => $coursetypebuf{$crsid},
2562: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2563: };
1.191 harris41 2564: }
1.352 www 2565: #
2566: # Write course id database (reverse lookup) to homeserver of courses
2567: # Is used in pickcourse
2568: #
1.840 albertel 2569: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2570: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2571: $courseidbuffer{$crs_home},
2572: $crs_home,'timeonly');
1.352 www 2573: }
2574: #
2575: # File accesses
2576: # Writes to the dynamic metadata of resources to get hit counts, etc.
2577: #
1.449 matthew 2578: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2579: if ($entry =~ /___count$/) {
2580: my ($dom,$name);
1.807 albertel 2581: ($dom,$name,undef)=
1.811 albertel 2582: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2583: if (! defined($dom) || $dom eq '' ||
2584: ! defined($name) || $name eq '') {
1.620 albertel 2585: my $cid = $env{'request.course.id'};
2586: $dom = $env{'request.'.$cid.'.domain'};
2587: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2588: }
1.450 matthew 2589: my $value = $accesshash{$entry};
2590: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2591: my %temphash=($url => $value);
1.449 matthew 2592: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2593: if ($result eq 'ok') {
2594: delete $accesshash{$entry};
2595: } elsif ($result eq 'unknown_cmd') {
2596: # Target server has old code running on it.
1.450 matthew 2597: my %temphash=($entry => $value);
1.449 matthew 2598: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2599: delete $accesshash{$entry};
2600: }
2601: }
2602: } else {
1.811 albertel 2603: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2604: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2605: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2606: delete $accesshash{$entry};
2607: }
1.185 www 2608: }
1.191 harris41 2609: }
1.352 www 2610: #
2611: # Roles
2612: # Reverse lookup of user roles for course faculty/staff and co-authorship
2613: #
1.800 albertel 2614: foreach my $entry (keys(%userrolehash)) {
1.351 www 2615: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2616: split(/\:/,$entry);
2617: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2618: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2619: $rudom,$runame) eq 'ok') {
2620: delete $userrolehash{$entry};
2621: }
2622: }
1.662 raeburn 2623: #
2624: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2625: #
2626: my %domrolebuffer = ();
1.1000 raeburn 2627: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2628: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2629: if ($domrolebuffer{$rudom}) {
2630: $domrolebuffer{$rudom}.='&'.&escape($entry).
2631: '='.&escape($domainrolehash{$entry});
2632: } else {
2633: $domrolebuffer{$rudom}.=&escape($entry).
2634: '='.&escape($domainrolehash{$entry});
2635: }
2636: delete $domainrolehash{$entry};
2637: }
2638: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2639: my %servers = &get_servers($dom,'library');
2640: foreach my $tryserver (keys(%servers)) {
2641: unless (&reply('domroleput:'.$dom.':'.
2642: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2643: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2644: }
1.662 raeburn 2645: }
2646: }
1.186 www 2647: $dumpcount++;
1.157 www 2648: }
2649:
2650: sub courselog {
2651: my $what=shift;
1.158 www 2652: $what=time.':'.$what;
1.620 albertel 2653: unless ($env{'request.course.id'}) { return ''; }
2654: $coursedombuf{$env{'request.course.id'}}=
2655: $env{'course.'.$env{'request.course.id'}.'.domain'};
2656: $coursenumbuf{$env{'request.course.id'}}=
2657: $env{'course.'.$env{'request.course.id'}.'.num'};
2658: $coursehombuf{$env{'request.course.id'}}=
2659: $env{'course.'.$env{'request.course.id'}.'.home'};
2660: $coursedescrbuf{$env{'request.course.id'}}=
2661: $env{'course.'.$env{'request.course.id'}.'.description'};
2662: $courseinstcodebuf{$env{'request.course.id'}}=
2663: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2664: $courseownerbuf{$env{'request.course.id'}}=
2665: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2666: $coursetypebuf{$env{'request.course.id'}}=
2667: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2668: if (defined $courselogs{$env{'request.course.id'}}) {
2669: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2670: } else {
1.620 albertel 2671: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2672: }
1.620 albertel 2673: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2674: &flushcourselogs();
2675: }
1.158 www 2676: }
2677:
2678: sub courseacclog {
2679: my $fnsymb=shift;
1.620 albertel 2680: unless ($env{'request.course.id'}) { return ''; }
2681: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2682: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2683: $what.=':POST';
1.583 matthew 2684: # FIXME: Probably ought to escape things....
1.800 albertel 2685: foreach my $key (keys(%env)) {
2686: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2687: my $formitem = $1;
2688: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2689: $what.=':'.$formitem.'='.$env{$key};
2690: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2691: $what.=':'.$formitem.'='.$env{$key};
2692: }
1.158 www 2693: }
1.191 harris41 2694: }
1.583 matthew 2695: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2696: # FIXME: We should not be depending on a form parameter that someone
2697: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2698: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2699: $what.= ':POST';
2700: # FIXME: Probably ought to escape things....
2701: foreach my $element ('courseexp','crsfulltext','crsrelated',
2702: 'crsdiscuss') {
1.620 albertel 2703: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2704: }
2705: }
1.158 www 2706: }
2707: &courselog($what);
1.149 www 2708: }
2709:
1.185 www 2710: sub countacc {
2711: my $url=&declutter(shift);
1.458 matthew 2712: return if (! defined($url) || $url eq '');
1.620 albertel 2713: unless ($env{'request.course.id'}) { return ''; }
2714: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2715: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2716: $accesshash{$key}++;
1.185 www 2717: }
1.349 www 2718:
1.361 www 2719: sub linklog {
2720: my ($from,$to)=@_;
2721: $from=&declutter($from);
2722: $to=&declutter($to);
2723: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2724: $accesshash{$to.'___'.$from.'___goto'}=1;
2725: }
2726:
1.349 www 2727: sub userrolelog {
2728: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2729: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2730: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2731: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2732: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2733: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2734: $userrolehash
2735: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2736: =$tend.':'.$tstart;
1.662 raeburn 2737: }
1.898 albertel 2738: if (($env{'request.role'} =~ /dc\./) &&
2739: (($trole=~/^au/) || ($trole=~/^in/) ||
2740: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2741: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2742: ($trole=~/^co/))) {
1.898 albertel 2743: $userrolehash
2744: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2745: =$tend.':'.$tstart;
2746: }
1.662 raeburn 2747: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2748: ($trole=~/^li/) || ($trole=~/^li/) ||
2749: ($trole=~/^au/) || ($trole=~/^dg/) ||
2750: ($trole=~/^sc/)) {
2751: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2752: $domainrolehash
2753: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2754: = $tend.':'.$tstart;
2755: }
1.351 www 2756: }
2757:
1.957 raeburn 2758: sub courserolelog {
2759: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2760: if (($trole eq 'cc') || ($trole eq 'in') ||
2761: ($trole eq 'ep') || ($trole eq 'ad') ||
2762: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2763: ($trole=~/^cr/) || ($trole eq 'gr') ||
2764: ($trole eq 'co')) {
1.957 raeburn 2765: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2766: my $cdom = $1;
2767: my $cnum = $2;
2768: my $sec = $3;
2769: my $namespace = 'rolelog';
2770: my %storehash = (
2771: role => $trole,
2772: start => $tstart,
2773: end => $tend,
2774: selfenroll => $selfenroll,
2775: context => $context,
2776: );
2777: if ($trole eq 'gr') {
2778: $namespace = 'groupslog';
2779: $storehash{'group'} = $sec;
2780: } else {
2781: $storehash{'section'} = $sec;
2782: }
2783: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2784: if (($trole ne 'st') || ($sec ne '')) {
2785: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2786: }
1.957 raeburn 2787: }
2788: }
2789: return;
2790: }
2791:
1.351 www 2792: sub get_course_adv_roles {
1.948 raeburn 2793: my ($cid,$codes) = @_;
1.620 albertel 2794: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2795: my %coursehash=&coursedescription($cid);
1.988 raeburn 2796: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2797: my %nothide=();
1.800 albertel 2798: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2799: if ($user !~ /:/) {
2800: $nothide{join(':',split(/[\@]/,$user))}=1;
2801: } else {
2802: $nothide{$user}=1;
2803: }
1.470 www 2804: }
1.351 www 2805: my %returnhash=();
2806: my %dumphash=
2807: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2808: my $now=time;
1.997 raeburn 2809: my %privileged;
1.1000 raeburn 2810: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2811: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2812: if (($tstart) && ($tstart<0)) { next; }
2813: if (($tend) && ($tend<$now)) { next; }
2814: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2815: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2816: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2817: unless (ref($privileged{$domain}) eq 'HASH') {
2818: my %dompersonnel =
1.998 raeburn 2819: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2820: $privileged{$domain} = {};
2821: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2822: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2823: foreach my $user (keys(%{$dompersonnel{$server}})) {
2824: my ($trole,$uname,$udom) = split(/:/,$user);
2825: $privileged{$udom}{$uname} = 1;
2826: }
2827: }
2828: }
2829: }
2830: if ((exists($privileged{$domain}{$username})) &&
2831: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2832: if ($role eq 'cr') { next; }
1.948 raeburn 2833: if ($codes) {
2834: if ($section) { $role .= ':'.$section; }
2835: if ($returnhash{$role}) {
2836: $returnhash{$role}.=','.$username.':'.$domain;
2837: } else {
2838: $returnhash{$role}=$username.':'.$domain;
2839: }
1.351 www 2840: } else {
1.988 raeburn 2841: my $key=&plaintext($role,$crstype);
1.973 bisitz 2842: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2843: if ($returnhash{$key}) {
2844: $returnhash{$key}.=','.$username.':'.$domain;
2845: } else {
2846: $returnhash{$key}=$username.':'.$domain;
2847: }
1.351 www 2848: }
1.948 raeburn 2849: }
1.400 www 2850: return %returnhash;
2851: }
2852:
2853: sub get_my_roles {
1.937 raeburn 2854: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2855: unless (defined($uname)) { $uname=$env{'user.name'}; }
2856: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2857: my (%dumphash,%nothide);
1.858 raeburn 2858: if ($context eq 'userroles') {
2859: %dumphash = &dump('roles',$udom,$uname);
2860: } else {
2861: %dumphash=
1.400 www 2862: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2863: if ($hidepriv) {
2864: my %coursehash=&coursedescription($udom.'_'.$uname);
2865: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2866: if ($user !~ /:/) {
2867: $nothide{join(':',split(/[\@]/,$user))} = 1;
2868: } else {
2869: $nothide{$user} = 1;
2870: }
2871: }
2872: }
1.858 raeburn 2873: }
1.400 www 2874: my %returnhash=();
2875: my $now=time;
1.999 raeburn 2876: my %privileged;
1.800 albertel 2877: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2878: my ($role,$tend,$tstart);
2879: if ($context eq 'userroles') {
2880: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2881: } else {
2882: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2883: }
1.400 www 2884: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2885: my $status = 'active';
1.939 raeburn 2886: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2887: $status = 'previous';
2888: }
2889: if (($tstart) && ($now<$tstart)) {
2890: $status = 'future';
2891: }
2892: if (ref($types) eq 'ARRAY') {
2893: if (!grep(/^\Q$status\E$/,@{$types})) {
2894: next;
2895: }
2896: } else {
2897: if ($status ne 'active') {
2898: next;
2899: }
2900: }
1.867 raeburn 2901: my ($rolecode,$username,$domain,$section,$area);
2902: if ($context eq 'userroles') {
2903: ($area,$rolecode) = split(/_/,$entry);
2904: (undef,$domain,$username,$section) = split(/\//,$area);
2905: } else {
2906: ($role,$username,$domain,$section) = split(/\:/,$entry);
2907: }
1.832 raeburn 2908: if (ref($roledoms) eq 'ARRAY') {
2909: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2910: next;
2911: }
2912: }
2913: if (ref($roles) eq 'ARRAY') {
2914: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2915: if ($role =~ /^cr\//) {
2916: if (!grep(/^cr$/,@{$roles})) {
2917: next;
2918: }
2919: } else {
2920: next;
2921: }
1.832 raeburn 2922: }
1.867 raeburn 2923: }
1.937 raeburn 2924: if ($hidepriv) {
1.999 raeburn 2925: if ($context eq 'userroles') {
2926: if ((&privileged($username,$domain)) &&
2927: (!$nothide{$username.':'.$domain})) {
2928: next;
2929: }
2930: } else {
2931: unless (ref($privileged{$domain}) eq 'HASH') {
2932: my %dompersonnel =
2933: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2934: $privileged{$domain} = {};
2935: if (keys(%dompersonnel)) {
2936: foreach my $server (keys(%dompersonnel)) {
2937: if (ref($dompersonnel{$server}) eq 'HASH') {
2938: foreach my $user (keys(%{$dompersonnel{$server}})) {
2939: my ($trole,$uname,$udom) = split(/:/,$user);
2940: $privileged{$udom}{$uname} = $trole;
2941: }
2942: }
2943: }
2944: }
2945: }
2946: if (exists($privileged{$domain}{$username})) {
2947: if (!$nothide{$username.':'.$domain}) {
2948: next;
2949: }
2950: }
1.937 raeburn 2951: }
2952: }
1.933 raeburn 2953: if ($withsec) {
2954: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2955: $tstart.':'.$tend;
2956: } else {
2957: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2958: }
1.832 raeburn 2959: }
1.373 www 2960: return %returnhash;
1.399 www 2961: }
2962:
2963: # ----------------------------------------------------- Frontpage Announcements
2964: #
2965: #
2966:
2967: sub postannounce {
2968: my ($server,$text)=@_;
1.844 albertel 2969: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2970: unless ($text=~/\w/) { $text=''; }
2971: return &reply('setannounce:'.&escape($text),$server);
2972: }
2973:
2974: sub getannounce {
1.448 albertel 2975:
2976: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2977: my $announcement='';
1.800 albertel 2978: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2979: close($fh);
1.399 www 2980: if ($announcement=~/\w/) {
2981: return
2982: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2983: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2984: } else {
2985: return '';
2986: }
2987: } else {
2988: return '';
2989: }
1.351 www 2990: }
1.353 www 2991:
2992: # ---------------------------------------------------------- Course ID routines
2993: # Deal with domain's nohist_courseid.db files
2994: #
2995:
2996: sub courseidput {
1.921 raeburn 2997: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 2998: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 2999: my $outcome;
3000: if ($caller eq 'timeonly') {
3001: my $cids = '';
3002: foreach my $item (keys(%$storehash)) {
3003: $cids.=&escape($item).'&';
3004: }
3005: $cids=~s/\&$//;
3006: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3007: $coursehome);
3008: } else {
3009: my $items = '';
3010: foreach my $item (keys(%$storehash)) {
3011: $items.= &escape($item).'='.
3012: &freeze_escape($$storehash{$item}).'&';
3013: }
3014: $items=~s/\&$//;
3015: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3016: $coursehome);
1.918 raeburn 3017: }
3018: if ($outcome eq 'unknown_cmd') {
3019: my $what;
3020: foreach my $cid (keys(%$storehash)) {
3021: $what .= &escape($cid).'=';
1.921 raeburn 3022: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3023: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3024: }
3025: $what =~ s/\:$/&/;
3026: }
3027: $what =~ s/\&$//;
3028: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3029: } else {
3030: return $outcome;
3031: }
1.353 www 3032: }
3033:
3034: sub courseiddump {
1.921 raeburn 3035: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3036: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3037: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 ! raeburn 3038: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3039: my $as_hash = 1;
3040: my %returnhash;
3041: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3042: my %libserv = &all_library();
3043: foreach my $tryserver (keys(%libserv)) {
3044: if ( ( $hostidflag == 1
3045: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3046: || (!defined($hostidflag)) ) {
3047:
1.918 raeburn 3048: if (($domfilter eq '') ||
3049: (&host_domain($tryserver) eq $domfilter)) {
3050: my $rep =
3051: &reply('courseiddump:'.&host_domain($tryserver).':'.
3052: $sincefilter.':'.&escape($descfilter).':'.
3053: &escape($instcodefilter).':'.&escape($ownerfilter).
3054: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3055: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3056: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3057: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3058: &escape($cc_clone).':'.$cloneonly.':'.
3059: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 ! raeburn 3060: &escape($creationcontext).':'.$domcloner,
! 3061: $tryserver);
1.918 raeburn 3062: my @pairs=split(/\&/,$rep);
3063: foreach my $item (@pairs) {
3064: my ($key,$value)=split(/\=/,$item,2);
3065: $key = &unescape($key);
3066: next if ($key =~ /^error: 2 /);
3067: my $result = &thaw_unescape($value);
3068: if (ref($result) eq 'HASH') {
3069: $returnhash{$key}=$result;
3070: } else {
1.921 raeburn 3071: my @responses = split(/:/,$value);
3072: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3073: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3074: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3075: }
1.1008 raeburn 3076: }
1.353 www 3077: }
3078: }
3079: }
3080: }
3081: return %returnhash;
3082: }
3083:
1.1055 raeburn 3084: sub courselastaccess {
3085: my ($cdom,$cnum,$hostidref) = @_;
3086: my %returnhash;
3087: if ($cdom && $cnum) {
3088: my $chome = &homeserver($cnum,$cdom);
3089: if ($chome ne 'no_host') {
3090: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3091: &extract_lastaccess(\%returnhash,$rep);
3092: }
3093: } else {
3094: if (!$cdom) { $cdom=''; }
3095: my %libserv = &all_library();
3096: foreach my $tryserver (keys(%libserv)) {
3097: if (ref($hostidref) eq 'ARRAY') {
3098: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3099: }
3100: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3101: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3102: &extract_lastaccess(\%returnhash,$rep);
3103: }
3104: }
3105: }
3106: return %returnhash;
3107: }
3108:
3109: sub extract_lastaccess {
3110: my ($returnhash,$rep) = @_;
3111: if (ref($returnhash) eq 'HASH') {
3112: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3113: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3114: $rep eq '') {
3115: my @pairs=split(/\&/,$rep);
3116: foreach my $item (@pairs) {
3117: my ($key,$value)=split(/\=/,$item,2);
3118: $key = &unescape($key);
3119: next if ($key =~ /^error: 2 /);
3120: $returnhash->{$key} = &thaw_unescape($value);
3121: }
3122: }
3123: }
3124: return;
3125: }
3126:
1.658 raeburn 3127: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3128:
3129: sub dcmailput {
1.685 raeburn 3130: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3131: my $status = &Apache::lonnet::critical(
1.740 www 3132: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3133: &escape($message),$server);
1.662 raeburn 3134: return $status;
3135: }
3136:
1.658 raeburn 3137: sub dcmaildump {
3138: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3139: my %returnhash=();
1.846 albertel 3140:
3141: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3142: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3143: &escape($enddate).':';
3144: my @esc_senders=map { &escape($_)} @$senders;
3145: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3146: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3147: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3148: if (($key) && ($value)) {
3149: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3150: }
3151: }
3152: }
3153: return %returnhash;
3154: }
1.662 raeburn 3155: # ---------------------------------------------------------- Domain roles
3156:
3157: sub get_domain_roles {
3158: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3159: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3160: $startdate = '.';
3161: }
1.1018 raeburn 3162: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3163: $enddate = '.';
3164: }
1.922 raeburn 3165: my $rolelist;
3166: if (ref($roles) eq 'ARRAY') {
3167: $rolelist = join(':',@{$roles});
3168: }
1.662 raeburn 3169: my %personnel = ();
1.841 albertel 3170:
3171: my %servers = &get_servers($dom,'library');
3172: foreach my $tryserver (keys(%servers)) {
3173: %{$personnel{$tryserver}}=();
3174: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3175: &escape($startdate).':'.
3176: &escape($enddate).':'.
3177: &escape($rolelist), $tryserver))) {
3178: my ($key,$value) = split(/\=/,$line,2);
3179: if (($key) && ($value)) {
3180: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3181: }
3182: }
1.662 raeburn 3183: }
3184: return %personnel;
3185: }
1.658 raeburn 3186:
1.1057 www 3187: # ----------------------------------------------------------- Interval timing
1.149 www 3188:
1.504 albertel 3189: sub get_first_access {
3190: my ($type,$argsymb)=@_;
1.790 albertel 3191: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3192: if ($argsymb) { $symb=$argsymb; }
3193: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3194: if ($type eq 'course') {
3195: $res='course';
3196: } elsif ($type eq 'map') {
1.588 albertel 3197: $res=&symbread($map);
3198: } else {
3199: $res=$symb;
3200: }
3201: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3202: return $times{"$courseid\0$res"};
1.504 albertel 3203: }
3204:
3205: sub set_first_access {
3206: my ($type)=@_;
1.790 albertel 3207: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3208: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3209: if ($type eq 'course') {
3210: $res='course';
3211: } elsif ($type eq 'map') {
1.588 albertel 3212: $res=&symbread($map);
3213: } else {
3214: $res=$symb;
3215: }
3216: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3217: if (!$firstaccess) {
1.588 albertel 3218: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3219: }
3220: return 'already_set';
1.504 albertel 3221: }
3222:
1.110 www 3223: # --------------------------------------------- Set Expire Date for Spreadsheet
3224:
3225: sub expirespread {
3226: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3227: my $cid=$env{'request.course.id'};
1.110 www 3228: if ($cid) {
3229: my $now=time;
3230: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3231: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3232: $env{'course.'.$cid.'.num'}.
1.110 www 3233: ':nohist_expirationdates:'.
3234: &escape($key).'='.$now,
1.620 albertel 3235: $env{'course.'.$cid.'.home'})
1.110 www 3236: }
3237: return 'ok';
1.14 www 3238: }
3239:
1.109 www 3240: # ----------------------------------------------------- Devalidate Spreadsheets
3241:
3242: sub devalidate {
1.325 www 3243: my ($symb,$uname,$udom)=@_;
1.620 albertel 3244: my $cid=$env{'request.course.id'};
1.109 www 3245: if ($cid) {
1.391 matthew 3246: # delete the stored spreadsheets for
3247: # - the student level sheet of this user in course's homespace
3248: # - the assessment level sheet for this resource
3249: # for this user in user's homespace
1.553 albertel 3250: # - current conditional state info
1.325 www 3251: my $key=$uname.':'.$udom.':';
1.109 www 3252: my $status=
1.299 matthew 3253: &del('nohist_calculatedsheets',
1.391 matthew 3254: [$key.'studentcalc:'],
1.620 albertel 3255: $env{'course.'.$cid.'.domain'},
3256: $env{'course.'.$cid.'.num'})
1.133 albertel 3257: .' '.
3258: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3259: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3260: unless ($status eq 'ok ok') {
3261: &logthis('Could not devalidate spreadsheet '.
1.325 www 3262: $uname.' at '.$udom.' for '.
1.109 www 3263: $symb.': '.$status);
1.133 albertel 3264: }
1.553 albertel 3265: &delenv('user.state.'.$cid);
1.109 www 3266: }
3267: }
3268:
1.265 albertel 3269: sub get_scalar {
3270: my ($string,$end) = @_;
3271: my $value;
3272: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3273: $value = $1;
3274: } elsif ($$string =~ s/^([^&]*?)&//) {
3275: $value = $1;
3276: }
3277: return &unescape($value);
3278: }
3279:
3280: sub array2str {
3281: my (@array) = @_;
3282: my $result=&arrayref2str(\@array);
3283: $result=~s/^__ARRAY_REF__//;
3284: $result=~s/__END_ARRAY_REF__$//;
3285: return $result;
3286: }
3287:
1.204 albertel 3288: sub arrayref2str {
3289: my ($arrayref) = @_;
1.265 albertel 3290: my $result='__ARRAY_REF__';
1.204 albertel 3291: foreach my $elem (@$arrayref) {
1.265 albertel 3292: if(ref($elem) eq 'ARRAY') {
3293: $result.=&arrayref2str($elem).'&';
3294: } elsif(ref($elem) eq 'HASH') {
3295: $result.=&hashref2str($elem).'&';
3296: } elsif(ref($elem)) {
3297: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3298: } else {
3299: $result.=&escape($elem).'&';
3300: }
3301: }
3302: $result=~s/\&$//;
1.265 albertel 3303: $result .= '__END_ARRAY_REF__';
1.204 albertel 3304: return $result;
3305: }
3306:
1.168 albertel 3307: sub hash2str {
1.204 albertel 3308: my (%hash) = @_;
3309: my $result=&hashref2str(\%hash);
1.265 albertel 3310: $result=~s/^__HASH_REF__//;
3311: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3312: return $result;
3313: }
3314:
3315: sub hashref2str {
3316: my ($hashref)=@_;
1.265 albertel 3317: my $result='__HASH_REF__';
1.800 albertel 3318: foreach my $key (sort(keys(%$hashref))) {
3319: if (ref($key) eq 'ARRAY') {
3320: $result.=&arrayref2str($key).'=';
3321: } elsif (ref($key) eq 'HASH') {
3322: $result.=&hashref2str($key).'=';
3323: } elsif (ref($key)) {
1.265 albertel 3324: $result.='=';
1.800 albertel 3325: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3326: } else {
1.800 albertel 3327: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3328: }
3329:
1.800 albertel 3330: if(ref($hashref->{$key}) eq 'ARRAY') {
3331: $result.=&arrayref2str($hashref->{$key}).'&';
3332: } elsif(ref($hashref->{$key}) eq 'HASH') {
3333: $result.=&hashref2str($hashref->{$key}).'&';
3334: } elsif(ref($hashref->{$key})) {
1.265 albertel 3335: $result.='&';
1.800 albertel 3336: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3337: } else {
1.800 albertel 3338: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3339: }
3340: }
1.168 albertel 3341: $result=~s/\&$//;
1.265 albertel 3342: $result .= '__END_HASH_REF__';
1.168 albertel 3343: return $result;
3344: }
3345:
3346: sub str2hash {
1.265 albertel 3347: my ($string)=@_;
3348: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3349: return %$hash;
3350: }
3351:
3352: sub str2hashref {
1.168 albertel 3353: my ($string) = @_;
1.265 albertel 3354:
3355: my %hash;
3356:
3357: if($string !~ /^__HASH_REF__/) {
3358: if (! ($string eq '' || !defined($string))) {
3359: $hash{'error'}='Not hash reference';
3360: }
3361: return (\%hash, $string);
3362: }
3363:
3364: $string =~ s/^__HASH_REF__//;
3365:
3366: while($string !~ /^__END_HASH_REF__/) {
3367: #key
3368: my $key='';
3369: if($string =~ /^__HASH_REF__/) {
3370: ($key, $string)=&str2hashref($string);
3371: if(defined($key->{'error'})) {
3372: $hash{'error'}='Bad data';
3373: return (\%hash, $string);
3374: }
3375: } elsif($string =~ /^__ARRAY_REF__/) {
3376: ($key, $string)=&str2arrayref($string);
3377: if($key->[0] eq 'Array reference error') {
3378: $hash{'error'}='Bad data';
3379: return (\%hash, $string);
3380: }
3381: } else {
3382: $string =~ s/^(.*?)=//;
1.267 albertel 3383: $key=&unescape($1);
1.265 albertel 3384: }
3385: $string =~ s/^=//;
3386:
3387: #value
3388: my $value='';
3389: if($string =~ /^__HASH_REF__/) {
3390: ($value, $string)=&str2hashref($string);
3391: if(defined($value->{'error'})) {
3392: $hash{'error'}='Bad data';
3393: return (\%hash, $string);
3394: }
3395: } elsif($string =~ /^__ARRAY_REF__/) {
3396: ($value, $string)=&str2arrayref($string);
3397: if($value->[0] eq 'Array reference error') {
3398: $hash{'error'}='Bad data';
3399: return (\%hash, $string);
3400: }
3401: } else {
3402: $value=&get_scalar(\$string,'__END_HASH_REF__');
3403: }
3404: $string =~ s/^&//;
3405:
3406: $hash{$key}=$value;
1.204 albertel 3407: }
1.265 albertel 3408:
3409: $string =~ s/^__END_HASH_REF__//;
3410:
3411: return (\%hash, $string);
1.204 albertel 3412: }
3413:
3414: sub str2array {
1.265 albertel 3415: my ($string)=@_;
3416: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3417: return @$array;
3418: }
3419:
3420: sub str2arrayref {
1.204 albertel 3421: my ($string) = @_;
1.265 albertel 3422: my @array;
3423:
3424: if($string !~ /^__ARRAY_REF__/) {
3425: if (! ($string eq '' || !defined($string))) {
3426: $array[0]='Array reference error';
3427: }
3428: return (\@array, $string);
3429: }
3430:
3431: $string =~ s/^__ARRAY_REF__//;
3432:
3433: while($string !~ /^__END_ARRAY_REF__/) {
3434: my $value='';
3435: if($string =~ /^__HASH_REF__/) {
3436: ($value, $string)=&str2hashref($string);
3437: if(defined($value->{'error'})) {
3438: $array[0] ='Array reference error';
3439: return (\@array, $string);
3440: }
3441: } elsif($string =~ /^__ARRAY_REF__/) {
3442: ($value, $string)=&str2arrayref($string);
3443: if($value->[0] eq 'Array reference error') {
3444: $array[0] ='Array reference error';
3445: return (\@array, $string);
3446: }
3447: } else {
3448: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3449: }
3450: $string =~ s/^&//;
3451:
3452: push(@array, $value);
1.191 harris41 3453: }
1.265 albertel 3454:
3455: $string =~ s/^__END_ARRAY_REF__//;
3456:
3457: return (\@array, $string);
1.168 albertel 3458: }
3459:
1.167 albertel 3460: # -------------------------------------------------------------------Temp Store
3461:
1.168 albertel 3462: sub tmpreset {
3463: my ($symb,$namespace,$domain,$stuname) = @_;
3464: if (!$symb) {
3465: $symb=&symbread();
1.620 albertel 3466: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3467: }
3468: $symb=escape($symb);
3469:
1.620 albertel 3470: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3471: $namespace=~s/\//\_/g;
3472: $namespace=~s/\W//g;
3473:
1.620 albertel 3474: if (!$domain) { $domain=$env{'user.domain'}; }
3475: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3476: if ($domain eq 'public' && $stuname eq 'public') {
3477: $stuname=$ENV{'REMOTE_ADDR'};
3478: }
1.168 albertel 3479: my $path=$perlvar{'lonDaemons'}.'/tmp';
3480: my %hash;
3481: if (tie(%hash,'GDBM_File',
3482: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3483: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3484: foreach my $key (keys(%hash)) {
1.180 albertel 3485: if ($key=~ /:$symb/) {
1.168 albertel 3486: delete($hash{$key});
3487: }
3488: }
3489: }
3490: }
3491:
1.167 albertel 3492: sub tmpstore {
1.168 albertel 3493: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3494:
3495: if (!$symb) {
3496: $symb=&symbread();
1.620 albertel 3497: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3498: }
3499: $symb=escape($symb);
3500:
3501: if (!$namespace) {
3502: # I don't think we would ever want to store this for a course.
3503: # it seems this will only be used if we don't have a course.
1.620 albertel 3504: #$namespace=$env{'request.course.id'};
1.168 albertel 3505: #if (!$namespace) {
1.620 albertel 3506: $namespace=$env{'request.state'};
1.168 albertel 3507: #}
3508: }
3509: $namespace=~s/\//\_/g;
3510: $namespace=~s/\W//g;
1.620 albertel 3511: if (!$domain) { $domain=$env{'user.domain'}; }
3512: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3513: if ($domain eq 'public' && $stuname eq 'public') {
3514: $stuname=$ENV{'REMOTE_ADDR'};
3515: }
1.168 albertel 3516: my $now=time;
3517: my %hash;
3518: my $path=$perlvar{'lonDaemons'}.'/tmp';
3519: if (tie(%hash,'GDBM_File',
3520: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3521: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3522: $hash{"version:$symb"}++;
3523: my $version=$hash{"version:$symb"};
3524: my $allkeys='';
3525: foreach my $key (keys(%$storehash)) {
3526: $allkeys.=$key.':';
1.591 albertel 3527: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3528: }
3529: $hash{"$version:$symb:timestamp"}=$now;
3530: $allkeys.='timestamp';
3531: $hash{"$version:keys:$symb"}=$allkeys;
3532: if (untie(%hash)) {
3533: return 'ok';
3534: } else {
3535: return "error:$!";
3536: }
3537: } else {
3538: return "error:$!";
3539: }
3540: }
1.167 albertel 3541:
1.168 albertel 3542: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3543:
1.168 albertel 3544: sub tmprestore {
3545: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3546:
1.168 albertel 3547: if (!$symb) {
3548: $symb=&symbread();
1.620 albertel 3549: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3550: }
3551: $symb=escape($symb);
3552:
1.620 albertel 3553: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3554:
1.620 albertel 3555: if (!$domain) { $domain=$env{'user.domain'}; }
3556: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3557: if ($domain eq 'public' && $stuname eq 'public') {
3558: $stuname=$ENV{'REMOTE_ADDR'};
3559: }
1.168 albertel 3560: my %returnhash;
3561: $namespace=~s/\//\_/g;
3562: $namespace=~s/\W//g;
3563: my %hash;
3564: my $path=$perlvar{'lonDaemons'}.'/tmp';
3565: if (tie(%hash,'GDBM_File',
3566: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3567: &GDBM_READER(),0640)) {
1.168 albertel 3568: my $version=$hash{"version:$symb"};
3569: $returnhash{'version'}=$version;
3570: my $scope;
3571: for ($scope=1;$scope<=$version;$scope++) {
3572: my $vkeys=$hash{"$scope:keys:$symb"};
3573: my @keys=split(/:/,$vkeys);
3574: my $key;
3575: $returnhash{"$scope:keys"}=$vkeys;
3576: foreach $key (@keys) {
1.591 albertel 3577: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3578: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3579: }
3580: }
1.168 albertel 3581: if (!(untie(%hash))) {
3582: return "error:$!";
3583: }
3584: } else {
3585: return "error:$!";
3586: }
3587: return %returnhash;
1.167 albertel 3588: }
3589:
1.9 www 3590: # ----------------------------------------------------------------------- Store
3591:
3592: sub store {
1.124 www 3593: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3594: my $home='';
3595:
1.168 albertel 3596: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3597:
1.213 www 3598: $symb=&symbclean($symb);
1.122 albertel 3599: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3600:
1.620 albertel 3601: if (!$domain) { $domain=$env{'user.domain'}; }
3602: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3603:
3604: &devalidate($symb,$stuname,$domain);
1.109 www 3605:
3606: $symb=escape($symb);
1.187 www 3607: if (!$namespace) {
1.620 albertel 3608: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3609: return '';
3610: }
3611: }
1.620 albertel 3612: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3613:
3614: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3615: $$storehash{'host'}=$perlvar{'lonHostID'};
3616:
1.12 www 3617: my $namevalue='';
1.800 albertel 3618: foreach my $key (keys(%$storehash)) {
3619: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3620: }
1.12 www 3621: $namevalue=~s/\&$//;
1.187 www 3622: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3623: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3624: }
3625:
1.47 www 3626: # -------------------------------------------------------------- Critical Store
3627:
3628: sub cstore {
1.124 www 3629: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3630: my $home='';
3631:
1.168 albertel 3632: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3633:
1.213 www 3634: $symb=&symbclean($symb);
1.122 albertel 3635: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3636:
1.620 albertel 3637: if (!$domain) { $domain=$env{'user.domain'}; }
3638: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3639:
3640: &devalidate($symb,$stuname,$domain);
1.109 www 3641:
3642: $symb=escape($symb);
1.187 www 3643: if (!$namespace) {
1.620 albertel 3644: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3645: return '';
3646: }
3647: }
1.620 albertel 3648: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3649:
3650: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3651: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3652:
1.47 www 3653: my $namevalue='';
1.800 albertel 3654: foreach my $key (keys(%$storehash)) {
3655: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3656: }
1.47 www 3657: $namevalue=~s/\&$//;
1.187 www 3658: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3659: return critical
3660: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3661: }
3662:
1.9 www 3663: # --------------------------------------------------------------------- Restore
3664:
3665: sub restore {
1.124 www 3666: my ($symb,$namespace,$domain,$stuname) = @_;
3667: my $home='';
3668:
1.168 albertel 3669: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3670:
1.122 albertel 3671: if (!$symb) {
3672: unless ($symb=escape(&symbread())) { return ''; }
3673: } else {
1.213 www 3674: $symb=&escape(&symbclean($symb));
1.122 albertel 3675: }
1.188 www 3676: if (!$namespace) {
1.620 albertel 3677: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3678: return '';
3679: }
3680: }
1.620 albertel 3681: if (!$domain) { $domain=$env{'user.domain'}; }
3682: if (!$stuname) { $stuname=$env{'user.name'}; }
3683: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3684: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3685:
1.12 www 3686: my %returnhash=();
1.800 albertel 3687: foreach my $line (split(/\&/,$answer)) {
3688: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3689: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3690: }
1.75 www 3691: my $version;
3692: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3693: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3694: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3695: }
1.75 www 3696: }
1.13 www 3697: return %returnhash;
1.34 www 3698: }
3699:
3700: # ---------------------------------------------------------- Course Description
3701:
3702: sub coursedescription {
1.731 albertel 3703: my ($courseid,$args)=@_;
1.34 www 3704: $courseid=~s/^\///;
1.49 www 3705: $courseid=~s/\_/\//g;
1.34 www 3706: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3707: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3708: my $normalid=$cdomain.'_'.$cnum;
3709: # need to always cache even if we get errors otherwise we keep
3710: # trying and trying and trying to get the course description.
3711: my %envhash=();
3712: my %returnhash=();
1.731 albertel 3713:
3714: my $expiretime=600;
3715: if ($env{'request.course.id'} eq $normalid) {
3716: $expiretime=120;
3717: }
3718:
3719: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3720: if (!$args->{'freshen_cache'}
3721: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3722: foreach my $key (keys(%env)) {
3723: next if ($key !~ /^\Q$prefix\E(.*)/);
3724: my ($setting) = $1;
3725: $returnhash{$setting} = $env{$key};
3726: }
3727: return %returnhash;
3728: }
3729:
3730: # get the data agin
3731: if (!$args->{'one_time'}) {
3732: $envhash{'course.'.$normalid.'.last_cache'}=time;
3733: }
1.811 albertel 3734:
1.34 www 3735: if ($chome ne 'no_host') {
1.302 albertel 3736: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3737: if (!exists($returnhash{'con_lost'})) {
3738: $returnhash{'home'}= $chome;
3739: $returnhash{'domain'} = $cdomain;
3740: $returnhash{'num'} = $cnum;
1.741 raeburn 3741: if (!defined($returnhash{'type'})) {
3742: $returnhash{'type'} = 'Course';
3743: }
1.130 albertel 3744: while (my ($name,$value) = each %returnhash) {
1.53 www 3745: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3746: }
1.270 www 3747: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3748: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3749: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3750: $envhash{'course.'.$normalid.'.home'}=$chome;
3751: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3752: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3753: }
3754: }
1.731 albertel 3755: if (!$args->{'one_time'}) {
1.949 raeburn 3756: &appenv(\%envhash);
1.731 albertel 3757: }
1.302 albertel 3758: return %returnhash;
1.461 www 3759: }
3760:
3761: # -------------------------------------------------See if a user is privileged
3762:
3763: sub privileged {
3764: my ($username,$domain)=@_;
3765: my $rolesdump=&reply("dump:$domain:$username:roles",
3766: &homeserver($username,$domain));
1.1033 raeburn 3767: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3768: ($rolesdump =~ /^error:/)) {
3769: return 0;
3770: }
1.461 www 3771: my $now=time;
3772: if ($rolesdump ne '') {
1.800 albertel 3773: foreach my $entry (split(/&/,$rolesdump)) {
3774: if ($entry!~/^rolesdef_/) {
3775: my ($area,$role)=split(/=/,$entry);
1.461 www 3776: $area=~s/\_\w\w$//;
3777: my ($trole,$tend,$tstart)=split(/_/,$role);
3778: if (($trole eq 'dc') || ($trole eq 'su')) {
3779: my $active=1;
3780: if ($tend) {
3781: if ($tend<$now) { $active=0; }
3782: }
3783: if ($tstart) {
3784: if ($tstart>$now) { $active=0; }
3785: }
3786: if ($active) { return 1; }
3787: }
3788: }
3789: }
3790: }
3791: return 0;
1.9 www 3792: }
1.1 albertel 3793:
1.103 harris41 3794: # -------------------------------------------------------- Get user privileges
1.11 www 3795:
3796: sub rolesinit {
3797: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 3798: my $now=time;
3799: my %userroles = ('user.login.time' => $now);
1.11 www 3800: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033 raeburn 3801: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3802: ($rolesdump =~ /^error:/)) {
3803: return \%userroles;
3804: }
1.11 www 3805: my %allroles=();
1.678 raeburn 3806: my %allgroups=();
3807: my $group_privs;
1.11 www 3808:
3809: if ($rolesdump ne '') {
1.800 albertel 3810: foreach my $entry (split(/&/,$rolesdump)) {
3811: if ($entry!~/^rolesdef_/) {
3812: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3813: $area=~s/\_\w\w$//;
1.678 raeburn 3814: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3815: if ($role=~/^cr/) {
1.807 albertel 3816: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3817: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3818: ($tend,$tstart)=split('_',$trest);
3819: } else {
3820: $trole=$role;
3821: }
1.678 raeburn 3822: } elsif ($role =~ m|^gr/|) {
3823: ($trole,$tend,$tstart) = split(/_/,$role);
3824: ($trole,$group_privs) = split(/\//,$trole);
3825: $group_privs = &unescape($group_privs);
1.587 albertel 3826: } else {
3827: ($trole,$tend,$tstart)=split(/_/,$role);
3828: }
1.743 albertel 3829: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3830: $username);
3831: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3832: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3833: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3834: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3835: my $spec=$trole.'.'.$area;
3836: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3837: if ($trole =~ /^cr\//) {
1.567 raeburn 3838: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3839: } elsif ($trole eq 'gr') {
3840: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3841: } else {
1.567 raeburn 3842: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3843: }
1.12 www 3844: }
1.662 raeburn 3845: }
1.191 harris41 3846: }
1.743 albertel 3847: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3848: $userroles{'user.adv'} = $adv;
3849: $userroles{'user.author'} = $author;
1.620 albertel 3850: $env{'user.adv'}=$adv;
1.11 www 3851: }
1.743 albertel 3852: return \%userroles;
1.11 www 3853: }
3854:
1.567 raeburn 3855: sub set_arearole {
3856: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3857: # log the associated role with the area
3858: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3859: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3860: }
3861:
3862: sub custom_roleprivs {
3863: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3864: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3865: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3866: if (&hostname($homsvr) ne '') {
1.567 raeburn 3867: my ($rdummy,$roledef)=
3868: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3869: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3870: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3871: if (defined($syspriv)) {
1.1043 raeburn 3872: if ($trest =~ /^$match_community$/) {
3873: $syspriv =~ s/bre\&S//;
3874: }
1.567 raeburn 3875: $$allroles{'cm./'}.=':'.$syspriv;
3876: $$allroles{$spec.'./'}.=':'.$syspriv;
3877: }
3878: if ($tdomain ne '') {
3879: if (defined($dompriv)) {
3880: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3881: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3882: }
3883: if (($trest ne '') && (defined($coursepriv))) {
3884: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3885: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3886: }
3887: }
3888: }
3889: }
3890: }
3891:
1.678 raeburn 3892: sub group_roleprivs {
3893: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3894: my $access = 1;
3895: my $now = time;
3896: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3897: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3898: if ($access) {
1.811 albertel 3899: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3900: $$allgroups{$course}{$group} .=':'.$group_privs;
3901: }
3902: }
1.567 raeburn 3903:
3904: sub standard_roleprivs {
3905: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3906: if (defined($pr{$trole.':s'})) {
3907: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3908: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3909: }
3910: if ($tdomain ne '') {
3911: if (defined($pr{$trole.':d'})) {
3912: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3913: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3914: }
3915: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3916: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3917: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3918: }
3919: }
3920: }
3921:
3922: sub set_userprivs {
1.1064 raeburn 3923: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 3924: my $author=0;
3925: my $adv=0;
1.678 raeburn 3926: my %grouproles = ();
3927: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 3928: my @groupkeys;
1.1000 raeburn 3929: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 3930: push(@groupkeys,$role);
3931: }
3932: if (ref($groups_roles) eq 'HASH') {
3933: foreach my $key (keys(%{$groups_roles})) {
3934: unless (grep(/^\Q$key\E$/,@groupkeys)) {
3935: push(@groupkeys,$key);
3936: }
3937: }
3938: }
3939: if (@groupkeys > 0) {
3940: foreach my $role (@groupkeys) {
3941: my ($trole,$area,$sec,$extendedarea);
3942: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
3943: $trole = $1;
3944: $area = $2;
3945: $sec = $3;
3946: $extendedarea = $area.$sec;
3947: if (exists($$allgroups{$area})) {
3948: foreach my $group (keys(%{$$allgroups{$area}})) {
3949: my $spec = $trole.'.'.$extendedarea;
3950: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 3951: $$allgroups{$area}{$group};
1.1064 raeburn 3952: }
1.678 raeburn 3953: }
3954: }
3955: }
3956: }
3957: }
1.800 albertel 3958: foreach my $group (keys(%grouproles)) {
3959: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3960: }
1.800 albertel 3961: foreach my $role (keys(%{$allroles})) {
3962: my %thesepriv;
1.941 raeburn 3963: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3964: foreach my $item (split(/:/,$$allroles{$role})) {
3965: if ($item ne '') {
3966: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3967: if ($restrictions eq '') {
3968: $thesepriv{$privilege}='F';
3969: } elsif ($thesepriv{$privilege} ne 'F') {
3970: $thesepriv{$privilege}.=$restrictions;
3971: }
3972: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3973: }
3974: }
3975: my $thesestr='';
1.800 albertel 3976: foreach my $priv (keys(%thesepriv)) {
3977: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3978: }
3979: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3980: }
3981: return ($author,$adv);
3982: }
3983:
1.994 raeburn 3984: sub role_status {
1.1002 raeburn 3985: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 3986: my @pwhere = ();
3987: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
3988: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
3989: unless (!defined($$role) || $$role eq '') {
3990: $$where=join('.',@pwhere);
3991: $$trolecode=$$role.'.'.$$where;
3992: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
3993: $$tstatus='is';
3994: if ($$tstart && $$tstart>$then) {
3995: $$tstatus='future';
1.1034 raeburn 3996: if ($$tstart<$now) {
3997: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 3998: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 3999: my (%allroles,%allgroups,$group_privs,
4000: %groups_roles,@rolecodes);
1.1002 raeburn 4001: my %userroles = (
4002: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4003: );
1.1064 raeburn 4004: @rolecodes = ('cm');
1.1002 raeburn 4005: my $spec=$$role.'.'.$$where;
4006: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4007: if ($$role =~ /^cr\//) {
4008: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4009: push(@rolecodes,'cr');
1.1002 raeburn 4010: } elsif ($$role eq 'gr') {
1.1064 raeburn 4011: push(@rolecodes,$$role);
1.1002 raeburn 4012: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4013: $env{'user.name'});
1.1064 raeburn 4014: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4015: (undef,my $group_privs) = split(/\//,$trole);
4016: $group_privs = &unescape($group_privs);
4017: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4018: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4019: if (keys(%course_roles) > 0) {
4020: my ($tnum) = ($trest =~ /^($match_courseid)/);
4021: if ($tdomain ne '' && $tnum ne '') {
4022: foreach my $key (keys(%course_roles)) {
4023: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4024: my $crsrole = $1;
4025: my $crssec = $2;
4026: if ($crsrole =~ /^cr/) {
4027: unless (grep(/^cr$/,@rolecodes)) {
4028: push(@rolecodes,'cr');
4029: }
4030: } else {
4031: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4032: push(@rolecodes,$crsrole);
4033: }
4034: }
4035: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4036: if ($crssec ne '') {
4037: $rolekey .= '/'.$crssec;
4038: }
4039: $rolekey .= './';
4040: $groups_roles{$rolekey} = \@rolecodes;
4041: }
4042: }
4043: }
4044: }
1.1002 raeburn 4045: } else {
1.1064 raeburn 4046: push(@rolecodes,$$role);
1.1002 raeburn 4047: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4048: }
1.1064 raeburn 4049: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4050: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4051: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4052: }
4053: }
1.1034 raeburn 4054: $$tstatus = 'is';
1.1002 raeburn 4055: }
1.994 raeburn 4056: }
4057: if ($$tend) {
4058: if ($$tend<$then) {
4059: $$tstatus='expired';
4060: } elsif ($$tend<$now) {
4061: $$tstatus='will_not';
4062: }
4063: }
4064: }
4065: }
4066: }
4067:
4068: sub check_adhoc_privs {
1.1002 raeburn 4069: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4070: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4071: if ($env{$cckey}) {
4072: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4073: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4074: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4075: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4076: }
4077: } else {
4078: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4079: }
4080: }
4081:
4082: sub set_adhoc_privileges {
4083: # role can be cc or ca
4084: my ($dcdom,$pickedcourse,$role) = @_;
4085: my $area = '/'.$dcdom.'/'.$pickedcourse;
4086: my $spec = $role.'.'.$area;
4087: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4088: $env{'user.name'});
4089: my %ccrole = ();
4090: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4091: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4092: &appenv(\%userroles,[$role,'cm']);
4093: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4094: &appenv( {'request.role' => $spec,
4095: 'request.role.domain' => $dcdom,
4096: 'request.course.sec' => ''
4097: }
4098: );
4099: my $tadv=0;
4100: if (&allowed('adv') eq 'F') { $tadv=1; }
4101: &appenv({'request.role.adv' => $tadv});
4102: }
4103:
1.12 www 4104: # --------------------------------------------------------------- get interface
4105:
4106: sub get {
1.131 albertel 4107: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4108: my $items='';
1.800 albertel 4109: foreach my $item (@$storearr) {
4110: $items.=&escape($item).'&';
1.191 harris41 4111: }
1.12 www 4112: $items=~s/\&$//;
1.620 albertel 4113: if (!$udomain) { $udomain=$env{'user.domain'}; }
4114: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4115: my $uhome=&homeserver($uname,$udomain);
4116:
1.133 albertel 4117: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4118: my @pairs=split(/\&/,$rep);
1.273 albertel 4119: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4120: return @pairs;
4121: }
1.15 www 4122: my %returnhash=();
1.42 www 4123: my $i=0;
1.800 albertel 4124: foreach my $item (@$storearr) {
4125: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4126: $i++;
1.191 harris41 4127: }
1.15 www 4128: return %returnhash;
1.27 www 4129: }
4130:
4131: # --------------------------------------------------------------- del interface
4132:
4133: sub del {
1.133 albertel 4134: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4135: my $items='';
1.800 albertel 4136: foreach my $item (@$storearr) {
4137: $items.=&escape($item).'&';
1.191 harris41 4138: }
1.984 neumanie 4139:
1.27 www 4140: $items=~s/\&$//;
1.620 albertel 4141: if (!$udomain) { $udomain=$env{'user.domain'}; }
4142: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4143: my $uhome=&homeserver($uname,$udomain);
4144: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4145: }
4146:
4147: # -------------------------------------------------------------- dump interface
4148:
4149: sub dump {
1.755 albertel 4150: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4151: if (!$udomain) { $udomain=$env{'user.domain'}; }
4152: if (!$uname) { $uname=$env{'user.name'}; }
4153: my $uhome=&homeserver($uname,$udomain);
4154: if ($regexp) {
4155: $regexp=&escape($regexp);
4156: } else {
4157: $regexp='.';
4158: }
4159: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4160: my @pairs=split(/\&/,$rep);
4161: my %returnhash=();
4162: foreach my $item (@pairs) {
4163: my ($key,$value)=split(/=/,$item,2);
4164: $key = &unescape($key);
4165: next if ($key =~ /^error: 2 /);
4166: $returnhash{$key}=&thaw_unescape($value);
4167: }
4168: return %returnhash;
1.407 www 4169: }
4170:
1.717 albertel 4171: # --------------------------------------------------------- dumpstore interface
4172:
4173: sub dumpstore {
4174: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4175: if (!$udomain) { $udomain=$env{'user.domain'}; }
4176: if (!$uname) { $uname=$env{'user.name'}; }
4177: my $uhome=&homeserver($uname,$udomain);
4178: if ($regexp) {
4179: $regexp=&escape($regexp);
4180: } else {
4181: $regexp='.';
4182: }
4183: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4184: my @pairs=split(/\&/,$rep);
4185: my %returnhash=();
4186: foreach my $item (@pairs) {
4187: my ($key,$value)=split(/=/,$item,2);
4188: next if ($key =~ /^error: 2 /);
4189: $returnhash{$key}=&thaw_unescape($value);
4190: }
4191: return %returnhash;
1.717 albertel 4192: }
4193:
1.407 www 4194: # -------------------------------------------------------------- keys interface
4195:
4196: sub getkeys {
4197: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4198: if (!$udomain) { $udomain=$env{'user.domain'}; }
4199: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4200: my $uhome=&homeserver($uname,$udomain);
4201: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4202: my @keyarray=();
1.800 albertel 4203: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4204: next if ($key =~ /^error: 2 /);
1.800 albertel 4205: push(@keyarray,&unescape($key));
1.407 www 4206: }
4207: return @keyarray;
1.318 matthew 4208: }
4209:
1.319 matthew 4210: # --------------------------------------------------------------- currentdump
4211: sub currentdump {
1.328 matthew 4212: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4213: $courseid = $env{'request.course.id'} if (! defined($courseid));
4214: $sdom = $env{'user.domain'} if (! defined($sdom));
4215: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4216: my $uhome = &homeserver($sname,$sdom);
4217: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4218: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4219: #
1.318 matthew 4220: my %returnhash=();
1.319 matthew 4221: #
4222: if ($rep eq "unknown_cmd") {
4223: # an old lond will not know currentdump
4224: # Do a dump and make it look like a currentdump
1.822 albertel 4225: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4226: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4227: my %hash = @tmp;
4228: @tmp=();
1.424 matthew 4229: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4230: } else {
4231: my @pairs=split(/\&/,$rep);
1.800 albertel 4232: foreach my $pair (@pairs) {
4233: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4234: my ($symb,$param) = split(/:/,$key);
4235: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4236: &thaw_unescape($value);
1.319 matthew 4237: }
1.191 harris41 4238: }
1.12 www 4239: return %returnhash;
1.424 matthew 4240: }
4241:
4242: sub convert_dump_to_currentdump{
4243: my %hash = %{shift()};
4244: my %returnhash;
4245: # Code ripped from lond, essentially. The only difference
4246: # here is the unescaping done by lonnet::dump(). Conceivably
4247: # we might run in to problems with parameter names =~ /^v\./
4248: while (my ($key,$value) = each(%hash)) {
4249: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4250: $symb = &unescape($symb);
4251: $param = &unescape($param);
1.424 matthew 4252: next if ($v eq 'version' || $symb eq 'keys');
4253: next if (exists($returnhash{$symb}) &&
4254: exists($returnhash{$symb}->{$param}) &&
4255: $returnhash{$symb}->{'v.'.$param} > $v);
4256: $returnhash{$symb}->{$param}=$value;
4257: $returnhash{$symb}->{'v.'.$param}=$v;
4258: }
4259: #
4260: # Remove all of the keys in the hashes which keep track of
4261: # the version of the parameter.
4262: while (my ($symb,$param_hash) = each(%returnhash)) {
4263: # use a foreach because we are going to delete from the hash.
4264: foreach my $key (keys(%$param_hash)) {
4265: delete($param_hash->{$key}) if ($key =~ /^v\./);
4266: }
4267: }
4268: return \%returnhash;
1.12 www 4269: }
4270:
1.627 albertel 4271: # ------------------------------------------------------ critical inc interface
4272:
4273: sub cinc {
4274: return &inc(@_,'critical');
4275: }
4276:
1.449 matthew 4277: # --------------------------------------------------------------- inc interface
4278:
4279: sub inc {
1.627 albertel 4280: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4281: if (!$udomain) { $udomain=$env{'user.domain'}; }
4282: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4283: my $uhome=&homeserver($uname,$udomain);
4284: my $items='';
4285: if (! ref($store)) {
4286: # got a single value, so use that instead
4287: $items = &escape($store).'=&';
4288: } elsif (ref($store) eq 'SCALAR') {
4289: $items = &escape($$store).'=&';
4290: } elsif (ref($store) eq 'ARRAY') {
4291: $items = join('=&',map {&escape($_);} @{$store});
4292: } elsif (ref($store) eq 'HASH') {
4293: while (my($key,$value) = each(%{$store})) {
4294: $items.= &escape($key).'='.&escape($value).'&';
4295: }
4296: }
4297: $items=~s/\&$//;
1.627 albertel 4298: if ($critical) {
4299: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4300: } else {
4301: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4302: }
1.449 matthew 4303: }
4304:
1.12 www 4305: # --------------------------------------------------------------- put interface
4306:
4307: sub put {
1.134 albertel 4308: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4309: if (!$udomain) { $udomain=$env{'user.domain'}; }
4310: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4311: my $uhome=&homeserver($uname,$udomain);
1.12 www 4312: my $items='';
1.800 albertel 4313: foreach my $item (keys(%$storehash)) {
4314: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4315: }
1.12 www 4316: $items=~s/\&$//;
1.134 albertel 4317: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4318: }
4319:
1.631 albertel 4320: # ------------------------------------------------------------ newput interface
4321:
4322: sub newput {
4323: my ($namespace,$storehash,$udomain,$uname)=@_;
4324: if (!$udomain) { $udomain=$env{'user.domain'}; }
4325: if (!$uname) { $uname=$env{'user.name'}; }
4326: my $uhome=&homeserver($uname,$udomain);
4327: my $items='';
4328: foreach my $key (keys(%$storehash)) {
4329: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4330: }
4331: $items=~s/\&$//;
4332: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4333: }
4334:
4335: # --------------------------------------------------------- putstore interface
4336:
1.524 raeburn 4337: sub putstore {
1.715 albertel 4338: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4339: if (!$udomain) { $udomain=$env{'user.domain'}; }
4340: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4341: my $uhome=&homeserver($uname,$udomain);
4342: my $items='';
1.715 albertel 4343: foreach my $key (keys(%$storehash)) {
4344: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4345: }
1.715 albertel 4346: $items=~s/\&$//;
1.716 albertel 4347: my $esc_symb=&escape($symb);
4348: my $esc_v=&escape($version);
1.715 albertel 4349: my $reply =
1.716 albertel 4350: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4351: $uhome);
4352: if ($reply eq 'unknown_cmd') {
1.716 albertel 4353: # gfall back to way things use to be done
1.715 albertel 4354: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4355: $uname);
1.524 raeburn 4356: }
1.715 albertel 4357: return $reply;
4358: }
4359:
4360: sub old_putstore {
1.716 albertel 4361: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4362: if (!$udomain) { $udomain=$env{'user.domain'}; }
4363: if (!$uname) { $uname=$env{'user.name'}; }
4364: my $uhome=&homeserver($uname,$udomain);
4365: my %newstorehash;
1.800 albertel 4366: foreach my $item (keys(%$storehash)) {
4367: my $key = $version.':'.&escape($symb).':'.$item;
4368: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4369: }
4370: my $items='';
4371: my %allitems = ();
1.800 albertel 4372: foreach my $item (keys(%newstorehash)) {
4373: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4374: my $key = $1.':keys:'.$2;
4375: $allitems{$key} .= $3.':';
4376: }
1.800 albertel 4377: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4378: }
1.800 albertel 4379: foreach my $item (keys(%allitems)) {
4380: $allitems{$item} =~ s/\:$//;
4381: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4382: }
4383: $items=~s/\&$//;
4384: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4385: }
4386:
1.47 www 4387: # ------------------------------------------------------ critical put interface
4388:
4389: sub cput {
1.134 albertel 4390: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4391: if (!$udomain) { $udomain=$env{'user.domain'}; }
4392: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4393: my $uhome=&homeserver($uname,$udomain);
1.47 www 4394: my $items='';
1.800 albertel 4395: foreach my $item (keys(%$storehash)) {
4396: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4397: }
1.47 www 4398: $items=~s/\&$//;
1.134 albertel 4399: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4400: }
4401:
4402: # -------------------------------------------------------------- eget interface
4403:
4404: sub eget {
1.133 albertel 4405: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4406: my $items='';
1.800 albertel 4407: foreach my $item (@$storearr) {
4408: $items.=&escape($item).'&';
1.191 harris41 4409: }
1.12 www 4410: $items=~s/\&$//;
1.620 albertel 4411: if (!$udomain) { $udomain=$env{'user.domain'}; }
4412: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4413: my $uhome=&homeserver($uname,$udomain);
4414: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4415: my @pairs=split(/\&/,$rep);
4416: my %returnhash=();
1.42 www 4417: my $i=0;
1.800 albertel 4418: foreach my $item (@$storearr) {
4419: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4420: $i++;
1.191 harris41 4421: }
1.12 www 4422: return %returnhash;
4423: }
4424:
1.667 albertel 4425: # ------------------------------------------------------------ tmpput interface
4426: sub tmpput {
1.802 raeburn 4427: my ($storehash,$server,$context)=@_;
1.667 albertel 4428: my $items='';
1.800 albertel 4429: foreach my $item (keys(%$storehash)) {
4430: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4431: }
4432: $items=~s/\&$//;
1.802 raeburn 4433: if (defined($context)) {
4434: $items .= ':'.&escape($context);
4435: }
1.667 albertel 4436: return &reply("tmpput:$items",$server);
4437: }
4438:
4439: # ------------------------------------------------------------ tmpget interface
4440: sub tmpget {
1.688 albertel 4441: my ($token,$server)=@_;
4442: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4443: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4444: my %returnhash;
4445: foreach my $item (split(/\&/,$rep)) {
4446: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4447: next if ($key =~ /^error: 2 /);
1.667 albertel 4448: $returnhash{&unescape($key)}=&thaw_unescape($value);
4449: }
4450: return %returnhash;
4451: }
4452:
1.688 albertel 4453: # ------------------------------------------------------------ tmpget interface
4454: sub tmpdel {
4455: my ($token,$server)=@_;
4456: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4457: return &reply("tmpdel:$token",$server);
4458: }
4459:
1.765 albertel 4460: # -------------------------------------------------- portfolio access checking
4461:
4462: sub portfolio_access {
1.766 albertel 4463: my ($requrl) = @_;
1.765 albertel 4464: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4465: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4466: if ($result) {
4467: my %setters;
4468: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4469: my ($startblock,$endblock) =
4470: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4471: if ($startblock && $endblock) {
4472: return 'B';
4473: }
4474: } else {
4475: my ($startblock,$endblock) =
4476: &Apache::loncommon::blockcheck(\%setters,'port');
4477: if ($startblock && $endblock) {
4478: return 'B';
4479: }
4480: }
4481: }
1.765 albertel 4482: if ($result eq 'ok') {
1.766 albertel 4483: return 'F';
1.765 albertel 4484: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4485: return 'A';
1.765 albertel 4486: }
1.766 albertel 4487: return '';
1.765 albertel 4488: }
4489:
4490: sub get_portfolio_access {
1.767 albertel 4491: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4492:
4493: if (!ref($access_hash)) {
4494: my $current_perms = &get_portfile_permissions($udom,$unum);
4495: my %access_controls = &get_access_controls($current_perms,$group,
4496: $file_name);
4497: $access_hash = $access_controls{$file_name};
4498: }
4499:
1.765 albertel 4500: my ($public,$guest,@domains,@users,@courses,@groups);
4501: my $now = time;
4502: if (ref($access_hash) eq 'HASH') {
4503: foreach my $key (keys(%{$access_hash})) {
4504: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4505: if ($start > $now) {
4506: next;
4507: }
4508: if ($end && $end<$now) {
4509: next;
4510: }
4511: if ($scope eq 'public') {
4512: $public = $key;
4513: last;
4514: } elsif ($scope eq 'guest') {
4515: $guest = $key;
4516: } elsif ($scope eq 'domains') {
4517: push(@domains,$key);
4518: } elsif ($scope eq 'users') {
4519: push(@users,$key);
4520: } elsif ($scope eq 'course') {
4521: push(@courses,$key);
4522: } elsif ($scope eq 'group') {
4523: push(@groups,$key);
4524: }
4525: }
4526: if ($public) {
4527: return 'ok';
4528: }
4529: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4530: if ($guest) {
4531: return $guest;
4532: }
4533: } else {
4534: if (@domains > 0) {
4535: foreach my $domkey (@domains) {
4536: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4537: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4538: return 'ok';
4539: }
4540: }
4541: }
4542: }
4543: if (@users > 0) {
4544: foreach my $userkey (@users) {
1.865 raeburn 4545: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4546: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4547: if (ref($item) eq 'HASH') {
4548: if (($item->{'uname'} eq $env{'user.name'}) &&
4549: ($item->{'udom'} eq $env{'user.domain'})) {
4550: return 'ok';
4551: }
4552: }
4553: }
4554: }
1.765 albertel 4555: }
4556: }
4557: my %roleshash;
4558: my @courses_and_groups = @courses;
4559: push(@courses_and_groups,@groups);
4560: if (@courses_and_groups > 0) {
4561: my (%allgroups,%allroles);
4562: my ($start,$end,$role,$sec,$group);
4563: foreach my $envkey (%env) {
1.1060 raeburn 4564: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4565: my $cid = $2.'_'.$3;
4566: if ($1 eq 'gr') {
4567: $group = $4;
4568: $allgroups{$cid}{$group} = $env{$envkey};
4569: } else {
4570: if ($4 eq '') {
4571: $sec = 'none';
4572: } else {
4573: $sec = $4;
4574: }
4575: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4576: }
1.811 albertel 4577: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4578: my $cid = $2.'_'.$3;
4579: if ($4 eq '') {
4580: $sec = 'none';
4581: } else {
4582: $sec = $4;
4583: }
4584: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4585: }
4586: }
4587: if (keys(%allroles) == 0) {
4588: return;
4589: }
4590: foreach my $key (@courses_and_groups) {
4591: my %content = %{$$access_hash{$key}};
4592: my $cnum = $content{'number'};
4593: my $cdom = $content{'domain'};
4594: my $cid = $cdom.'_'.$cnum;
4595: if (!exists($allroles{$cid})) {
4596: next;
4597: }
4598: foreach my $role_id (keys(%{$content{'roles'}})) {
4599: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4600: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4601: my @status = @{$content{'roles'}{$role_id}{'access'}};
4602: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4603: foreach my $role (keys(%{$allroles{$cid}})) {
4604: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4605: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4606: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4607: if (grep/^all$/,@sections) {
4608: return 'ok';
4609: } else {
4610: if (grep/^$sec$/,@sections) {
4611: return 'ok';
4612: }
4613: }
4614: }
4615: }
4616: if (keys(%{$allgroups{$cid}}) == 0) {
4617: if (grep/^none$/,@groups) {
4618: return 'ok';
4619: }
4620: } else {
4621: if (grep/^all$/,@groups) {
4622: return 'ok';
4623: }
4624: foreach my $group (keys(%{$allgroups{$cid}})) {
4625: if (grep/^$group$/,@groups) {
4626: return 'ok';
4627: }
4628: }
4629: }
4630: }
4631: }
4632: }
4633: }
4634: }
4635: if ($guest) {
4636: return $guest;
4637: }
4638: }
4639: }
4640: return;
4641: }
4642:
4643: sub course_group_datechecker {
4644: my ($dates,$now,$status) = @_;
4645: my ($start,$end) = split(/\./,$dates);
4646: if (!$start && !$end) {
4647: return 'ok';
4648: }
4649: if (grep/^active$/,@{$status}) {
4650: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4651: return 'ok';
4652: }
4653: }
4654: if (grep/^previous$/,@{$status}) {
4655: if ($end > $now ) {
4656: return 'ok';
4657: }
4658: }
4659: if (grep/^future$/,@{$status}) {
4660: if ($start > $now) {
4661: return 'ok';
4662: }
4663: }
4664: return;
4665: }
4666:
4667: sub parse_portfolio_url {
4668: my ($url) = @_;
4669:
4670: my ($type,$udom,$unum,$group,$file_name);
4671:
1.823 albertel 4672: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4673: $type = 1;
4674: $udom = $1;
4675: $unum = $2;
4676: $file_name = $3;
1.823 albertel 4677: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4678: $type = 2;
4679: $udom = $1;
4680: $unum = $2;
4681: $group = $3;
4682: $file_name = $3.'/'.$4;
4683: }
4684: if (wantarray) {
4685: return ($type,$udom,$unum,$file_name,$group);
4686: }
4687: return $type;
4688: }
4689:
4690: sub is_portfolio_url {
4691: my ($url) = @_;
4692: return scalar(&parse_portfolio_url($url));
4693: }
4694:
1.798 raeburn 4695: sub is_portfolio_file {
4696: my ($file) = @_;
1.820 raeburn 4697: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4698: return 1;
4699: }
4700: return;
4701: }
4702:
1.976 raeburn 4703: sub usertools_access {
1.985 raeburn 4704: my ($uname,$udom,$tool,$action,$context) = @_;
4705: my ($access,%tools);
4706: if ($context eq '') {
4707: $context = 'tools';
4708: }
4709: if ($context eq 'requestcourses') {
4710: %tools = (
4711: official => 1,
4712: unofficial => 1,
1.1006 raeburn 4713: community => 1,
1.985 raeburn 4714: );
4715: } else {
4716: %tools = (
4717: aboutme => 1,
4718: blog => 1,
4719: portfolio => 1,
4720: );
4721: }
1.976 raeburn 4722: return if (!defined($tools{$tool}));
4723:
4724: if ((!defined($udom)) || (!defined($uname))) {
4725: $udom = $env{'user.domain'};
4726: $uname = $env{'user.name'};
4727: }
4728:
1.978 raeburn 4729: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4730: if ($action ne 'reload') {
1.985 raeburn 4731: if ($context eq 'requestcourses') {
4732: return $env{'environment.canrequest.'.$tool};
4733: } else {
4734: return $env{'environment.availabletools.'.$tool};
4735: }
4736: }
1.976 raeburn 4737: }
4738:
4739: my ($toolstatus,$inststatus);
4740:
1.985 raeburn 4741: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4742: ($action ne 'reload')) {
4743: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4744: $inststatus = $env{'environment.inststatus'};
4745: } else {
1.1025 raeburn 4746: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985 raeburn 4747: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4748: $inststatus = $userenv{'inststatus'};
4749: }
4750:
4751: if ($toolstatus ne '') {
4752: if ($toolstatus) {
4753: $access = 1;
4754: } else {
4755: $access = 0;
4756: }
4757: return $access;
4758: }
4759:
4760: my $is_adv = &is_advanced_user($udom,$uname);
4761: my %domdef = &get_domain_defaults($udom);
4762: if (ref($domdef{$tool}) eq 'HASH') {
4763: if ($is_adv) {
4764: if ($domdef{$tool}{'_LC_adv'} ne '') {
4765: if ($domdef{$tool}{'_LC_adv'}) {
4766: $access = 1;
4767: } else {
4768: $access = 0;
4769: }
4770: return $access;
4771: }
4772: }
4773: if ($inststatus ne '') {
4774: my ($hasaccess,$hasnoaccess);
4775: foreach my $affiliation (split(/:/,$inststatus)) {
4776: if ($domdef{$tool}{$affiliation} ne '') {
4777: if ($domdef{$tool}{$affiliation}) {
4778: $hasaccess = 1;
4779: } else {
4780: $hasnoaccess = 1;
4781: }
4782: }
4783: }
4784: if ($hasaccess || $hasnoaccess) {
4785: if ($hasaccess) {
4786: $access = 1;
4787: } elsif ($hasnoaccess) {
4788: $access = 0;
4789: }
4790: return $access;
4791: }
4792: } else {
4793: if ($domdef{$tool}{'default'} ne '') {
4794: if ($domdef{$tool}{'default'}) {
4795: $access = 1;
4796: } elsif ($domdef{$tool}{'default'} == 0) {
4797: $access = 0;
4798: }
4799: return $access;
4800: }
4801: }
4802: } else {
1.985 raeburn 4803: if ($context eq 'tools') {
4804: $access = 1;
4805: } else {
4806: $access = 0;
4807: }
1.976 raeburn 4808: return $access;
4809: }
4810: }
4811:
1.1050 raeburn 4812: sub is_course_owner {
4813: my ($cdom,$cnum,$udom,$uname) = @_;
4814: if (($udom eq '') || ($uname eq '')) {
4815: $udom = $env{'user.domain'};
4816: $uname = $env{'user.name'};
4817: }
4818: unless (($udom eq '') || ($uname eq '')) {
4819: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
4820: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
4821: return 1;
4822: } else {
4823: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
4824: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
4825: return 1;
4826: }
4827: }
4828: }
4829: }
4830: return;
4831: }
4832:
1.976 raeburn 4833: sub is_advanced_user {
4834: my ($udom,$uname) = @_;
4835: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4836: my %allroles;
4837: my $is_adv;
4838: foreach my $role (keys(%roleshash)) {
4839: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4840: my $area = '/'.$tdomain.'/'.$trest;
4841: if ($sec ne '') {
4842: $area .= '/'.$sec;
4843: }
4844: if (($area ne '') && ($trole ne '')) {
4845: my $spec=$trole.'.'.$area;
4846: if ($trole =~ /^cr\//) {
4847: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4848: } elsif ($trole ne 'gr') {
4849: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4850: }
4851: }
4852: }
4853: foreach my $role (keys(%allroles)) {
4854: last if ($is_adv);
4855: foreach my $item (split(/:/,$allroles{$role})) {
4856: if ($item ne '') {
4857: my ($privilege,$restrictions)=split(/&/,$item);
4858: if ($privilege eq 'adv') {
4859: $is_adv = 1;
4860: last;
4861: }
4862: }
4863: }
4864: }
4865: return $is_adv;
4866: }
1.798 raeburn 4867:
1.1035 raeburn 4868: sub check_can_request {
1.1036 raeburn 4869: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 4870: my $canreq = 0;
4871: my ($types,$typename) = &Apache::loncommon::course_types();
4872: my @options = ('approval','validate','autolimit');
4873: my $optregex = join('|',@options);
4874: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
4875: foreach my $type (@{$types}) {
4876: if (&usertools_access($env{'user.name'},
4877: $env{'user.domain'},
4878: $type,undef,'requestcourses')) {
4879: $canreq ++;
1.1036 raeburn 4880: if (ref($request_domains) eq 'HASH') {
4881: push(@{$request_domains->{$type}},$env{'user.domain'});
4882: }
1.1035 raeburn 4883: if ($dom eq $env{'user.domain'}) {
4884: $can_request->{$type} = 1;
4885: }
4886: }
4887: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
4888: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
4889: if (@curr > 0) {
1.1036 raeburn 4890: foreach my $item (@curr) {
4891: if (ref($request_domains) eq 'HASH') {
4892: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
4893: if ($otherdom ne '') {
4894: if (ref($request_domains->{$type}) eq 'ARRAY') {
4895: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
4896: push(@{$request_domains->{$type}},$otherdom);
4897: }
4898: } else {
4899: push(@{$request_domains->{$type}},$otherdom);
4900: }
4901: }
4902: }
4903: }
4904: unless($dom eq $env{'user.domain'}) {
4905: $canreq ++;
1.1035 raeburn 4906: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
4907: $can_request->{$type} = 1;
4908: }
4909: }
4910: }
4911: }
4912: }
4913: }
4914: return $canreq;
4915: }
4916:
1.341 www 4917: # ---------------------------------------------- Custom access rule evaluation
4918:
4919: sub customaccess {
4920: my ($priv,$uri)=@_;
1.807 albertel 4921: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4922: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4923: $udom = &LONCAPA::clean_domain($udom);
4924: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4925: my $access=0;
1.800 albertel 4926: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4927: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4928: if ($type eq 'user') {
4929: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4930: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4931: if ($tdom) {
4932: if ($tdom ne $env{'user.domain'}) { next; }
4933: }
1.896 albertel 4934: if ($tuname) {
4935: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4936: }
4937: $access=($effect eq 'allow');
4938: last;
4939: }
4940: } else {
4941: if ($role) {
4942: if ($role ne $urole) { next; }
4943: }
4944: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4945: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4946: if ($tdom) {
4947: if ($tdom ne $udom) { next; }
4948: }
4949: if ($tcrs) {
4950: if ($tcrs ne $ucrs) { next; }
4951: }
4952: if ($tsec) {
4953: if ($tsec ne $usec) { next; }
4954: }
4955: $access=($effect eq 'allow');
4956: last;
4957: }
4958: if ($realm eq '' && $role eq '') {
4959: $access=($effect eq 'allow');
4960: }
1.402 bowersj2 4961: }
1.341 www 4962: }
4963: return $access;
4964: }
4965:
1.103 harris41 4966: # ------------------------------------------------- Check for a user privilege
1.12 www 4967:
4968: sub allowed {
1.810 raeburn 4969: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4970: my $ver_orguri=$uri;
1.439 www 4971: $uri=&deversion($uri);
1.152 www 4972: my $orguri=$uri;
1.52 www 4973: $uri=&declutter($uri);
1.809 raeburn 4974:
1.810 raeburn 4975: if ($priv eq 'evb') {
4976: # Evade communication block restrictions for specified role in a course
4977: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4978: return $1;
4979: } else {
4980: return;
4981: }
4982: }
4983:
1.620 albertel 4984: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4985: # Free bre access to adm and meta resources
1.775 albertel 4986: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4987: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4988: && ($priv eq 'bre')) {
1.14 www 4989: return 'F';
1.159 www 4990: }
4991:
1.545 banghart 4992: # Free bre access to user's own portfolio contents
1.714 raeburn 4993: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4994: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4995: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4996: my %setters;
4997: my ($startblock,$endblock) =
4998: &Apache::loncommon::blockcheck(\%setters,'port');
4999: if ($startblock && $endblock) {
5000: return 'B';
5001: } else {
5002: return 'F';
5003: }
1.545 banghart 5004: }
5005:
1.762 raeburn 5006: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5007: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5008: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5009: if (exists($env{'request.course.id'})) {
5010: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5011: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5012: if (($domain eq $cdom) && ($name eq $cnum)) {
5013: my $courseprivid=$env{'request.course.id'};
5014: $courseprivid=~s/\_/\//;
5015: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5016: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5017: return $1;
1.762 raeburn 5018: } else {
5019: if ($env{'request.course.sec'}) {
5020: $courseprivid.='/'.$env{'request.course.sec'};
5021: }
5022: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5023: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5024: return $2;
5025: }
1.714 raeburn 5026: }
5027: }
5028: }
5029: }
5030:
1.159 www 5031: # Free bre to public access
5032:
5033: if ($priv eq 'bre') {
1.238 www 5034: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5035: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5036: return 'F';
5037: }
1.238 www 5038: if ($copyright eq 'priv') {
5039: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5040: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5041: return '';
5042: }
5043: }
5044: if ($copyright eq 'domain') {
5045: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5046: unless (($env{'user.domain'} eq $1) ||
5047: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5048: return '';
5049: }
1.262 matthew 5050: }
1.620 albertel 5051: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5052: # Library role, so allow browsing of resources in this domain.
5053: return 'F';
1.238 www 5054: }
1.341 www 5055: if ($copyright eq 'custom') {
5056: unless (&customaccess($priv,$uri)) { return ''; }
5057: }
1.14 www 5058: }
1.264 matthew 5059: # Domain coordinator is trying to create a course
1.620 albertel 5060: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5061: # uri is the requested domain in this case.
5062: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5063: # a role of dc for the domain in question.
1.620 albertel 5064: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5065: }
1.29 www 5066:
1.52 www 5067: my $thisallowed='';
5068: my $statecond=0;
5069: my $courseprivid='';
5070:
1.1039 raeburn 5071: my $ownaccess;
1.1043 raeburn 5072: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5073: if (($priv eq 'bro') && ($env{'user.author'})) {
5074: if ($uri eq '') {
5075: $ownaccess = 1;
5076: } else {
5077: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5078: my $udom = $env{'user.domain'};
5079: my $uname = $env{'user.name'};
5080: if ($uri =~ m{^\Q$udom\E/?$}) {
5081: $ownaccess = 1;
1.1040 raeburn 5082: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5083: unless ($uri =~ m{\.\./}) {
5084: $ownaccess = 1;
5085: }
5086: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5087: my $now = time;
5088: if ($uri =~ m{^([^/]+)/?$}) {
5089: my $adom = $1;
5090: foreach my $key (keys(%env)) {
1.1042 raeburn 5091: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5092: my ($start,$end) = split('.',$env{$key});
5093: if (($now >= $start) && (!$end || $end < $now)) {
5094: $ownaccess = 1;
5095: last;
5096: }
5097: }
5098: }
5099: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5100: my $adom = $1;
5101: my $aname = $2;
1.1042 raeburn 5102: foreach my $role ('ca','aa') {
5103: if ($env{"user.role.$role./$adom/$aname"}) {
5104: my ($start,$end) =
5105: split('.',$env{"user.role.$role./$adom/$aname"});
5106: if (($now >= $start) && (!$end || $end < $now)) {
5107: $ownaccess = 1;
5108: last;
5109: }
1.1039 raeburn 5110: }
5111: }
5112: }
5113: }
5114: }
5115: }
5116: }
5117:
1.52 www 5118: # Course
5119:
1.620 albertel 5120: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5121: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5122: $thisallowed.=$1;
5123: }
1.52 www 5124: }
1.29 www 5125:
1.52 www 5126: # Domain
5127:
1.620 albertel 5128: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5129: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5130: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5131: $thisallowed.=$1;
5132: }
1.12 www 5133: }
1.52 www 5134:
5135: # Course: uri itself is a course
1.66 www 5136: my $courseuri=$uri;
5137: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5138: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5139:
1.620 albertel 5140: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5141: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5142: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5143: $thisallowed.=$1;
5144: }
1.12 www 5145: }
1.29 www 5146:
1.665 albertel 5147: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5148: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5149: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5150: $thisallowed='';
1.671 raeburn 5151: my ($match)=&is_on_map($uri);
5152: if ($match) {
5153: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5154: =~/\Q$priv\E\&([^\:]*)/) {
5155: $thisallowed.=$1;
5156: }
5157: } else {
1.705 albertel 5158: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5159: if ($refuri) {
5160: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5161: $thisallowed='F';
1.671 raeburn 5162: } else {
5163: $refuri=&declutter($refuri);
5164: my ($match) = &is_on_map($refuri);
5165: if ($match) {
5166: $thisallowed='F';
5167: }
1.669 raeburn 5168: }
1.671 raeburn 5169: }
5170: }
1.314 www 5171: }
1.492 albertel 5172:
1.766 albertel 5173: if ($priv eq 'bre'
5174: && $thisallowed ne 'F'
5175: && $thisallowed ne '2'
5176: && &is_portfolio_url($uri)) {
5177: $thisallowed = &portfolio_access($uri);
5178: }
5179:
1.52 www 5180: # Full access at system, domain or course-wide level? Exit.
1.29 www 5181: if ($thisallowed=~/F/) {
5182: return 'F';
5183: }
5184:
1.52 www 5185: # If this is generating or modifying users, exit with special codes
1.29 www 5186:
1.643 www 5187: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5188: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5189: my ($audom,$auname)=split('/',$uri);
1.643 www 5190: # no author name given, so this just checks on the general right to make a co-author in this domain
5191: unless ($auname) { return $thisallowed; }
5192: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5193: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5194: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5195: ($audom ne $env{'request.role.domain'}))) { return ''; }
5196: }
1.52 www 5197: return $thisallowed;
5198: }
5199: #
1.103 harris41 5200: # Gathered so far: system, domain and course wide privileges
1.52 www 5201: #
5202: # Course: See if uri or referer is an individual resource that is part of
5203: # the course
5204:
1.620 albertel 5205: if ($env{'request.course.id'}) {
1.232 www 5206:
1.620 albertel 5207: $courseprivid=$env{'request.course.id'};
5208: if ($env{'request.course.sec'}) {
5209: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5210: }
5211: $courseprivid=~s/\_/\//;
5212: my $checkreferer=1;
1.232 www 5213: my ($match,$cond)=&is_on_map($uri);
5214: if ($match) {
5215: $statecond=$cond;
1.620 albertel 5216: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5217: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5218: $thisallowed.=$1;
5219: $checkreferer=0;
5220: }
1.29 www 5221: }
1.83 www 5222:
1.148 www 5223: if ($checkreferer) {
1.620 albertel 5224: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5225: unless ($refuri) {
1.800 albertel 5226: foreach my $key (keys(%env)) {
5227: if ($key=~/^httpref\..*\*/) {
5228: my $pattern=$key;
1.156 www 5229: $pattern=~s/^httpref\.\/res\///;
1.148 www 5230: $pattern=~s/\*/\[\^\/\]\+/g;
5231: $pattern=~s/\//\\\//g;
1.152 www 5232: if ($orguri=~/$pattern/) {
1.800 albertel 5233: $refuri=$env{$key};
1.148 www 5234: }
5235: }
1.191 harris41 5236: }
1.148 www 5237: }
1.232 www 5238:
1.148 www 5239: if ($refuri) {
1.152 www 5240: $refuri=&declutter($refuri);
1.232 www 5241: my ($match,$cond)=&is_on_map($refuri);
5242: if ($match) {
5243: my $refstatecond=$cond;
1.620 albertel 5244: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5245: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5246: $thisallowed.=$1;
1.53 www 5247: $uri=$refuri;
5248: $statecond=$refstatecond;
1.52 www 5249: }
5250: }
1.148 www 5251: }
1.29 www 5252: }
1.52 www 5253: }
1.29 www 5254:
1.52 www 5255: #
1.103 harris41 5256: # Gathered now: all privileges that could apply, and condition number
1.52 www 5257: #
5258: #
5259: # Full or no access?
5260: #
1.29 www 5261:
1.52 www 5262: if ($thisallowed=~/F/) {
5263: return 'F';
5264: }
1.29 www 5265:
1.52 www 5266: unless ($thisallowed) {
5267: return '';
5268: }
1.29 www 5269:
1.52 www 5270: # Restrictions exist, deal with them
5271: #
5272: # C:according to course preferences
5273: # R:according to resource settings
5274: # L:unless locked
5275: # X:according to user session state
5276: #
5277:
5278: # Possibly locked functionality, check all courses
1.54 www 5279: # Locks might take effect only after 10 minutes cache expiration for other
5280: # courses, and 2 minutes for current course
1.52 www 5281:
5282: my $envkey;
5283: if ($thisallowed=~/L/) {
1.1000 raeburn 5284: foreach $envkey (keys(%env)) {
1.54 www 5285: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5286: my $courseid=$2;
5287: my $roleid=$1.'.'.$2;
1.92 www 5288: $courseid=~s/^\///;
1.54 www 5289: my $expiretime=600;
1.620 albertel 5290: if ($env{'request.role'} eq $roleid) {
1.54 www 5291: $expiretime=120;
5292: }
5293: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5294: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5295: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5296: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5297: }
1.620 albertel 5298: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5299: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5300: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5301: &log($env{'user.domain'},$env{'user.name'},
5302: $env{'user.home'},
1.57 www 5303: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5304: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5305: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5306: return '';
5307: }
5308: }
1.620 albertel 5309: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5310: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5311: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5312: &log($env{'user.domain'},$env{'user.name'},
5313: $env{'user.home'},
1.57 www 5314: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5315: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5316: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5317: return '';
5318: }
5319: }
5320: }
1.29 www 5321: }
1.52 www 5322: }
5323:
5324: #
5325: # Rest of the restrictions depend on selected course
5326: #
5327:
1.620 albertel 5328: unless ($env{'request.course.id'}) {
1.766 albertel 5329: if ($thisallowed eq 'A') {
5330: return 'A';
1.814 raeburn 5331: } elsif ($thisallowed eq 'B') {
5332: return 'B';
1.766 albertel 5333: } else {
5334: return '1';
5335: }
1.52 www 5336: }
1.29 www 5337:
1.52 www 5338: #
5339: # Now user is definitely in a course
5340: #
1.53 www 5341:
5342:
5343: # Course preferences
5344:
5345: if ($thisallowed=~/C/) {
1.620 albertel 5346: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5347: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5348: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5349: =~/\Q$rolecode\E/) {
1.689 albertel 5350: if ($priv ne 'pch') {
5351: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5352: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5353: $env{'request.course.id'});
5354: }
1.237 www 5355: return '';
5356: }
5357:
1.620 albertel 5358: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5359: =~/\Q$unamedom\E/) {
1.689 albertel 5360: if ($priv ne 'pch') {
5361: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5362: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5363: $env{'request.course.id'});
5364: }
1.54 www 5365: return '';
5366: }
1.53 www 5367: }
5368:
5369: # Resource preferences
5370:
5371: if ($thisallowed=~/R/) {
1.620 albertel 5372: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5373: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5374: if ($priv ne 'pch') {
5375: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5376: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5377: }
5378: return '';
1.54 www 5379: }
1.53 www 5380: }
1.30 www 5381:
1.246 www 5382: # Restricted by state or randomout?
1.30 www 5383:
1.52 www 5384: if ($thisallowed=~/X/) {
1.620 albertel 5385: if ($env{'acc.randomout'}) {
1.579 albertel 5386: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5387: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5388: return '';
5389: }
1.247 www 5390: }
5391: if (&condval($statecond)) {
1.52 www 5392: return '2';
5393: } else {
5394: return '';
5395: }
5396: }
1.30 www 5397:
1.766 albertel 5398: if ($thisallowed eq 'A') {
5399: return 'A';
1.814 raeburn 5400: } elsif ($thisallowed eq 'B') {
5401: return 'B';
1.766 albertel 5402: }
1.52 www 5403: return 'F';
1.232 www 5404: }
5405:
1.710 albertel 5406: sub split_uri_for_cond {
5407: my $uri=&deversion(&declutter(shift));
5408: my @uriparts=split(/\//,$uri);
5409: my $filename=pop(@uriparts);
5410: my $pathname=join('/',@uriparts);
5411: return ($pathname,$filename);
5412: }
1.232 www 5413: # --------------------------------------------------- Is a resource on the map?
5414:
5415: sub is_on_map {
1.710 albertel 5416: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5417: #Trying to find the conditional for the file
1.620 albertel 5418: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5419: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5420: if ($match) {
1.289 bowersj2 5421: return (1,$1);
5422: } else {
1.434 www 5423: return (0,0);
1.289 bowersj2 5424: }
1.12 www 5425: }
5426:
1.427 www 5427: # --------------------------------------------------------- Get symb from alias
5428:
5429: sub get_symb_from_alias {
5430: my $symb=shift;
5431: my ($map,$resid,$url)=&decode_symb($symb);
5432: # Already is a symb
5433: if ($url) { return $symb; }
5434: # Must be an alias
5435: my $aliassymb='';
5436: my %bighash;
1.620 albertel 5437: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5438: &GDBM_READER(),0640)) {
5439: my $rid=$bighash{'mapalias_'.$symb};
5440: if ($rid) {
5441: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5442: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5443: $resid,$bighash{'src_'.$rid});
1.427 www 5444: }
5445: untie %bighash;
5446: }
5447: return $aliassymb;
5448: }
5449:
1.12 www 5450: # ----------------------------------------------------------------- Define Role
5451:
5452: sub definerole {
5453: if (allowed('mcr','/')) {
5454: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5455: foreach my $role (split(':',$sysrole)) {
5456: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5457: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5458: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5459: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5460: return "refused:s:$crole&$cqual";
5461: }
5462: }
1.191 harris41 5463: }
1.800 albertel 5464: foreach my $role (split(':',$domrole)) {
5465: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5466: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5467: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5468: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5469: return "refused:d:$crole&$cqual";
5470: }
5471: }
1.191 harris41 5472: }
1.800 albertel 5473: foreach my $role (split(':',$courole)) {
5474: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5475: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5476: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5477: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5478: return "refused:c:$crole&$cqual";
5479: }
5480: }
1.191 harris41 5481: }
1.620 albertel 5482: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5483: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5484: "rolesdef_$rolename=".
5485: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5486: return reply($command,$env{'user.home'});
1.12 www 5487: } else {
5488: return 'refused';
5489: }
1.105 harris41 5490: }
5491:
5492: # ---------------- Make a metadata query against the network of library servers
5493:
5494: sub metadata_query {
1.244 matthew 5495: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5496: my %rhash;
1.845 albertel 5497: my %libserv = &all_library();
1.244 matthew 5498: my @server_list = (defined($server_array) ? @$server_array
5499: : keys(%libserv) );
5500: for my $server (@server_list) {
1.118 harris41 5501: unless ($custom or $customshow) {
5502: my $reply=&reply("querysend:".&escape($query),$server);
5503: $rhash{$server}=$reply;
5504: }
5505: else {
5506: my $reply=&reply("querysend:".&escape($query).':'.
5507: &escape($custom).':'.&escape($customshow),
5508: $server);
5509: $rhash{$server}=$reply;
5510: }
1.112 harris41 5511: }
1.118 harris41 5512: return \%rhash;
1.240 www 5513: }
5514:
5515: # ----------------------------------------- Send log queries and wait for reply
5516:
5517: sub log_query {
5518: my ($uname,$udom,$query,%filters)=@_;
5519: my $uhome=&homeserver($uname,$udom);
5520: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5521: my $uhost=&hostname($uhome);
1.800 albertel 5522: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5523: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5524: $uhome);
1.479 albertel 5525: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5526: return get_query_reply($queryid);
5527: }
5528:
1.818 raeburn 5529: # -------------------------- Update MySQL table for portfolio file
5530:
5531: sub update_portfolio_table {
1.821 raeburn 5532: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5533: if ($group ne '') {
5534: $file_name =~s /^\Q$group\E//;
5535: }
1.818 raeburn 5536: my $homeserver = &homeserver($uname,$udom);
5537: my $queryid=
1.821 raeburn 5538: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5539: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5540: my $reply = &get_query_reply($queryid);
5541: return $reply;
5542: }
5543:
1.899 raeburn 5544: # -------------------------- Update MySQL allusers table
5545:
5546: sub update_allusers_table {
5547: my ($uname,$udom,$names) = @_;
5548: my $homeserver = &homeserver($uname,$udom);
5549: my $queryid=
5550: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5551: 'lastname='.&escape($names->{'lastname'}).'%%'.
5552: 'firstname='.&escape($names->{'firstname'}).'%%'.
5553: 'middlename='.&escape($names->{'middlename'}).'%%'.
5554: 'generation='.&escape($names->{'generation'}).'%%'.
5555: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5556: 'id='.&escape($names->{'id'}),$homeserver);
5557: my $reply = &get_query_reply($queryid);
5558: return $reply;
5559: }
5560:
1.508 raeburn 5561: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5562:
5563: sub fetch_enrollment_query {
1.511 raeburn 5564: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5565: my $homeserver;
1.547 raeburn 5566: my $maxtries = 1;
1.508 raeburn 5567: if ($context eq 'automated') {
5568: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5569: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5570: } else {
5571: $homeserver = &homeserver($cnum,$dom);
5572: }
1.838 albertel 5573: my $host=&hostname($homeserver);
1.506 raeburn 5574: my $cmd = '';
1.1000 raeburn 5575: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5576: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5577: }
5578: $cmd =~ s/%%$//;
5579: $cmd = &escape($cmd);
5580: my $query = 'fetchenrollment';
1.620 albertel 5581: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5582: unless ($queryid=~/^\Q$host\E\_/) {
5583: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5584: return 'error: '.$queryid;
5585: }
1.506 raeburn 5586: my $reply = &get_query_reply($queryid);
1.547 raeburn 5587: my $tries = 1;
5588: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5589: $reply = &get_query_reply($queryid);
5590: $tries ++;
5591: }
1.526 raeburn 5592: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5593: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5594: } else {
1.901 albertel 5595: my @responses = split(/:/,$reply);
1.515 raeburn 5596: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5597: foreach my $line (@responses) {
5598: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5599: $$replyref{$key} = $value;
5600: }
5601: } else {
1.506 raeburn 5602: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5603: foreach my $line (@responses) {
5604: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5605: $$replyref{$key} = $value;
5606: if ($value > 0) {
1.800 albertel 5607: foreach my $item (@{$$affiliatesref{$key}}) {
5608: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5609: my $destname = $pathname.'/'.$filename;
5610: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5611: if ($xml_classlist =~ /^error/) {
5612: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5613: } else {
1.506 raeburn 5614: if ( open(FILE,">$destname") ) {
5615: print FILE &unescape($xml_classlist);
5616: close(FILE);
1.526 raeburn 5617: } else {
5618: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5619: }
5620: }
5621: }
5622: }
5623: }
5624: }
5625: return 'ok';
5626: }
5627: return 'error';
5628: }
5629:
1.242 www 5630: sub get_query_reply {
5631: my $queryid=shift;
1.240 www 5632: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5633: my $reply='';
5634: for (1..100) {
5635: sleep 2;
5636: if (-e $replyfile.'.end') {
1.448 albertel 5637: if (open(my $fh,$replyfile)) {
1.904 albertel 5638: $reply = join('',<$fh>);
5639: close($fh);
1.240 www 5640: } else { return 'error: reply_file_error'; }
1.242 www 5641: return &unescape($reply);
5642: }
1.240 www 5643: }
1.242 www 5644: return 'timeout:'.$queryid;
1.240 www 5645: }
5646:
5647: sub courselog_query {
1.241 www 5648: #
5649: # possible filters:
5650: # url: url or symb
5651: # username
5652: # domain
5653: # action: view, submit, grade
5654: # start: timestamp
5655: # end: timestamp
5656: #
1.240 www 5657: my (%filters)=@_;
1.620 albertel 5658: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5659: if ($filters{'url'}) {
5660: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5661: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5662: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5663: }
1.620 albertel 5664: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5665: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5666: return &log_query($cname,$cdom,'courselog',%filters);
5667: }
5668:
5669: sub userlog_query {
1.858 raeburn 5670: #
5671: # possible filters:
5672: # action: log check role
5673: # start: timestamp
5674: # end: timestamp
5675: #
1.240 www 5676: my ($uname,$udom,%filters)=@_;
5677: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5678: }
5679:
1.506 raeburn 5680: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5681:
5682: sub auto_run {
1.508 raeburn 5683: my ($cnum,$cdom) = @_;
1.876 raeburn 5684: my $response = 0;
5685: my $settings;
5686: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5687: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5688: $settings = $domconfig{'autoenroll'};
5689: if ($settings->{'run'} eq '1') {
5690: $response = 1;
5691: }
5692: } else {
1.934 raeburn 5693: my $homeserver;
5694: if (&is_course($cdom,$cnum)) {
5695: $homeserver = &homeserver($cnum,$cdom);
5696: } else {
5697: $homeserver = &domain($cdom,'primary');
5698: }
5699: if ($homeserver ne 'no_host') {
5700: $response = &reply('autorun:'.$cdom,$homeserver);
5701: }
1.876 raeburn 5702: }
1.506 raeburn 5703: return $response;
5704: }
1.776 albertel 5705:
1.506 raeburn 5706: sub auto_get_sections {
1.508 raeburn 5707: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5708: my $homeserver;
5709: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5710: $homeserver = &homeserver($cnum,$cdom);
5711: }
5712: if (!defined($homeserver)) {
5713: if ($cdom =~ /^$match_domain$/) {
5714: $homeserver = &domain($cdom,'primary');
5715: }
5716: }
5717: my @secs;
5718: if (defined($homeserver)) {
5719: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5720: unless ($response eq 'refused') {
5721: @secs = split(/:/,$response);
5722: }
1.506 raeburn 5723: }
5724: return @secs;
5725: }
1.776 albertel 5726:
1.506 raeburn 5727: sub auto_new_course {
1.508 raeburn 5728: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5729: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5730: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5731: return $response;
5732: }
1.776 albertel 5733:
1.506 raeburn 5734: sub auto_validate_courseID {
1.508 raeburn 5735: my ($cnum,$cdom,$inst_course_id) = @_;
5736: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5737: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5738: return $response;
5739: }
1.776 albertel 5740:
1.1007 raeburn 5741: sub auto_validate_instcode {
1.1020 raeburn 5742: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5743: my ($homeserver,$response);
5744: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5745: $homeserver = &homeserver($cnum,$cdom);
5746: }
5747: if (!defined($homeserver)) {
5748: if ($cdom =~ /^$match_domain$/) {
5749: $homeserver = &domain($cdom,'primary');
5750: }
5751: }
1.1065 raeburn 5752: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5753: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5754: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5755: return ($outcome,$description);
1.1007 raeburn 5756: }
5757:
1.506 raeburn 5758: sub auto_create_password {
1.873 raeburn 5759: my ($cnum,$cdom,$authparam,$udom) = @_;
5760: my ($homeserver,$response);
1.506 raeburn 5761: my $create_passwd = 0;
5762: my $authchk = '';
1.873 raeburn 5763: if ($udom =~ /^$match_domain$/) {
5764: $homeserver = &domain($udom,'primary');
5765: }
5766: if ($homeserver eq '') {
5767: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5768: $homeserver = &homeserver($cnum,$cdom);
5769: }
5770: }
5771: if ($homeserver eq '') {
5772: $authchk = 'nodomain';
1.506 raeburn 5773: } else {
1.873 raeburn 5774: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5775: if ($response eq 'refused') {
5776: $authchk = 'refused';
5777: } else {
1.901 albertel 5778: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5779: }
1.506 raeburn 5780: }
5781: return ($authparam,$create_passwd,$authchk);
5782: }
5783:
1.706 raeburn 5784: sub auto_photo_permission {
5785: my ($cnum,$cdom,$students) = @_;
5786: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5787: my ($outcome,$perm_reqd,$conditions) =
5788: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5789: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5790: return (undef,undef);
5791: }
1.706 raeburn 5792: return ($outcome,$perm_reqd,$conditions);
5793: }
5794:
5795: sub auto_checkphotos {
5796: my ($uname,$udom,$pid) = @_;
5797: my $homeserver = &homeserver($uname,$udom);
5798: my ($result,$resulttype);
5799: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5800: &escape($uname).':'.&escape($pid),
5801: $homeserver));
1.709 albertel 5802: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5803: return (undef,undef);
5804: }
1.706 raeburn 5805: if ($outcome) {
5806: ($result,$resulttype) = split(/:/,$outcome);
5807: }
5808: return ($result,$resulttype);
5809: }
5810:
5811: sub auto_photochoice {
5812: my ($cnum,$cdom) = @_;
5813: my $homeserver = &homeserver($cnum,$cdom);
5814: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5815: &escape($cdom),
5816: $homeserver)));
1.709 albertel 5817: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5818: return (undef,undef);
5819: }
1.706 raeburn 5820: return ($update,$comment);
5821: }
5822:
5823: sub auto_photoupdate {
5824: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5825: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5826: my $host=&hostname($homeserver);
1.706 raeburn 5827: my $cmd = '';
5828: my $maxtries = 1;
1.800 albertel 5829: foreach my $affiliate (keys(%{$affiliatesref})) {
5830: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5831: }
5832: $cmd =~ s/%%$//;
5833: $cmd = &escape($cmd);
5834: my $query = 'institutionalphotos';
5835: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5836: unless ($queryid=~/^\Q$host\E\_/) {
5837: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5838: return 'error: '.$queryid;
5839: }
5840: my $reply = &get_query_reply($queryid);
5841: my $tries = 1;
5842: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5843: $reply = &get_query_reply($queryid);
5844: $tries ++;
5845: }
5846: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5847: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5848: } else {
5849: my @responses = split(/:/,$reply);
5850: my $outcome = shift(@responses);
5851: foreach my $item (@responses) {
5852: my ($key,$value) = split(/=/,$item);
5853: $$photo{$key} = $value;
5854: }
5855: return $outcome;
5856: }
5857: return 'error';
5858: }
5859:
1.521 raeburn 5860: sub auto_instcode_format {
1.793 albertel 5861: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5862: $cat_order) = @_;
1.521 raeburn 5863: my $courses = '';
1.772 raeburn 5864: my @homeservers;
1.521 raeburn 5865: if ($caller eq 'global') {
1.841 albertel 5866: my %servers = &get_servers($codedom,'library');
5867: foreach my $tryserver (keys(%servers)) {
5868: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5869: push(@homeservers,$tryserver);
5870: }
1.584 raeburn 5871: }
1.1022 raeburn 5872: } elsif ($caller eq 'requests') {
5873: if ($codedom =~ /^$match_domain$/) {
5874: my $chome = &domain($codedom,'primary');
5875: unless ($chome eq 'no_host') {
5876: push(@homeservers,$chome);
5877: }
5878: }
1.521 raeburn 5879: } else {
1.772 raeburn 5880: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5881: }
1.793 albertel 5882: foreach my $code (keys(%{$instcodes})) {
5883: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5884: }
5885: chop($courses);
1.772 raeburn 5886: my $ok_response = 0;
5887: my $response;
5888: while (@homeservers > 0 && $ok_response == 0) {
5889: my $server = shift(@homeservers);
5890: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5891: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5892: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5893: split(/:/,$response);
1.772 raeburn 5894: %{$codes} = (%{$codes},&str2hash($codes_str));
5895: push(@{$codetitles},&str2array($codetitles_str));
5896: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5897: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5898: $ok_response = 1;
5899: }
5900: }
5901: if ($ok_response) {
1.521 raeburn 5902: return 'ok';
1.772 raeburn 5903: } else {
5904: return $response;
1.521 raeburn 5905: }
5906: }
5907:
1.792 raeburn 5908: sub auto_instcode_defaults {
5909: my ($domain,$returnhash,$code_order) = @_;
5910: my @homeservers;
1.841 albertel 5911:
5912: my %servers = &get_servers($domain,'library');
5913: foreach my $tryserver (keys(%servers)) {
5914: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5915: push(@homeservers,$tryserver);
5916: }
1.792 raeburn 5917: }
1.841 albertel 5918:
1.792 raeburn 5919: my $response;
1.841 albertel 5920: foreach my $server (@homeservers) {
1.792 raeburn 5921: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5922: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5923:
5924: foreach my $pair (split(/\&/,$response)) {
5925: my ($name,$value)=split(/\=/,$pair);
5926: if ($name eq 'code_order') {
5927: @{$code_order} = split(/\&/,&unescape($value));
5928: } else {
5929: $returnhash->{&unescape($name)}=&unescape($value);
5930: }
5931: }
5932: return 'ok';
1.792 raeburn 5933: }
1.841 albertel 5934:
5935: return $response;
1.1003 raeburn 5936: }
5937:
5938: sub auto_possible_instcodes {
1.1007 raeburn 5939: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
5940: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
5941: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
5942: return;
5943: }
1.1003 raeburn 5944: my (@homeservers,$uhome);
5945: if (defined(&domain($domain,'primary'))) {
5946: $uhome=&domain($domain,'primary');
5947: push(@homeservers,&domain($domain,'primary'));
5948: } else {
5949: my %servers = &get_servers($domain,'library');
5950: foreach my $tryserver (keys(%servers)) {
5951: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5952: push(@homeservers,$tryserver);
5953: }
5954: }
5955: }
5956: my $response;
5957: foreach my $server (@homeservers) {
5958: $response=&reply('autopossibleinstcodes:'.$domain,$server);
5959: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 5960: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
5961: split(':',$response);
5962: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
5963: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 5964: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 5965: my ($name,$value)=split('=',$item);
5966: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5967: }
5968: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 5969: my ($name,$value)=split('=',$item);
5970: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5971: }
5972: return 'ok';
5973: }
5974: return $response;
5975: }
1.792 raeburn 5976:
1.1010 raeburn 5977: sub auto_courserequest_checks {
5978: my ($dom) = @_;
1.1020 raeburn 5979: my ($homeserver,%validations);
5980: if ($dom =~ /^$match_domain$/) {
5981: $homeserver = &domain($dom,'primary');
5982: }
5983: unless ($homeserver eq 'no_host') {
5984: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
5985: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
5986: my @items = split(/&/,$response);
5987: foreach my $item (@items) {
5988: my ($key,$value) = split('=',$item);
5989: $validations{&unescape($key)} = &thaw_unescape($value);
5990: }
5991: }
5992: }
1.1010 raeburn 5993: return %validations;
5994: }
5995:
1.1020 raeburn 5996: sub auto_courserequest_validation {
5997: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
5998: my ($homeserver,$response);
5999: if ($dom =~ /^$match_domain$/) {
6000: $homeserver = &domain($dom,'primary');
6001: }
6002: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6003:
1.1020 raeburn 6004: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6005: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6006: ':'.&escape($instcode).':'.&escape($instseclist),
6007: $homeserver));
6008: }
6009: return $response;
6010: }
6011:
1.777 albertel 6012: sub auto_validate_class_sec {
1.918 raeburn 6013: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6014: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6015: my $ownerlist;
6016: if (ref($owners) eq 'ARRAY') {
6017: $ownerlist = join(',',@{$owners});
6018: } else {
6019: $ownerlist = $owners;
6020: }
1.773 raeburn 6021: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6022: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6023: return $response;
6024: }
6025:
1.679 raeburn 6026: # ------------------------------------------------------- Course Group routines
6027:
6028: sub get_coursegroups {
1.809 raeburn 6029: my ($cdom,$cnum,$group,$namespace) = @_;
6030: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6031: }
6032:
1.679 raeburn 6033: sub modify_coursegroup {
6034: my ($cdom,$cnum,$groupsettings) = @_;
6035: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6036: }
6037:
1.809 raeburn 6038: sub toggle_coursegroup_status {
6039: my ($cdom,$cnum,$group,$action) = @_;
6040: my ($from_namespace,$to_namespace);
6041: if ($action eq 'delete') {
6042: $from_namespace = 'coursegroups';
6043: $to_namespace = 'deleted_groups';
6044: } else {
6045: $from_namespace = 'deleted_groups';
6046: $to_namespace = 'coursegroups';
6047: }
6048: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6049: if (my $tmp = &error(%curr_group)) {
6050: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6051: return ('read error',$tmp);
6052: } else {
6053: my %savedsettings = %curr_group;
1.809 raeburn 6054: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6055: my $deloutcome;
6056: if ($result eq 'ok') {
1.809 raeburn 6057: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6058: } else {
6059: return ('write error',$result);
6060: }
6061: if ($deloutcome eq 'ok') {
6062: return 'ok';
6063: } else {
6064: return ('delete error',$deloutcome);
6065: }
6066: }
6067: }
6068:
1.679 raeburn 6069: sub modify_group_roles {
1.957 raeburn 6070: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6071: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6072: my $role = 'gr/'.&escape($userprivs);
6073: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6074: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6075: if ($result eq 'ok') {
6076: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6077: }
1.679 raeburn 6078: return $result;
6079: }
6080:
6081: sub modify_coursegroup_membership {
6082: my ($cdom,$cnum,$membership) = @_;
6083: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6084: return $result;
6085: }
6086:
1.682 raeburn 6087: sub get_active_groups {
6088: my ($udom,$uname,$cdom,$cnum) = @_;
6089: my $now = time;
6090: my %groups = ();
6091: foreach my $key (keys(%env)) {
1.811 albertel 6092: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6093: my ($start,$end) = split(/\./,$env{$key});
6094: if (($end!=0) && ($end<$now)) { next; }
6095: if (($start!=0) && ($start>$now)) { next; }
6096: if ($1 eq $cdom && $2 eq $cnum) {
6097: $groups{$3} = $env{$key} ;
6098: }
6099: }
6100: }
6101: return %groups;
6102: }
6103:
1.683 raeburn 6104: sub get_group_membership {
6105: my ($cdom,$cnum,$group) = @_;
6106: return(&dump('groupmembership',$cdom,$cnum,$group));
6107: }
6108:
6109: sub get_users_groups {
6110: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6111: my @usersgroups;
1.683 raeburn 6112: my $cachetime=1800;
6113:
6114: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6115: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6116: if (defined($cached)) {
1.734 albertel 6117: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6118: } else {
6119: $grouplist = '';
1.816 raeburn 6120: my $courseurl = &courseid_to_courseurl($courseid);
6121: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6122: my $access_end = $env{'course.'.$courseid.
6123: '.default_enrollment_end_date'};
6124: my $now = time;
6125: foreach my $key (keys(%roleshash)) {
6126: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6127: my $group = $1;
6128: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6129: my $start = $2;
6130: my $end = $1;
6131: if ($start == -1) { next; } # deleted from group
6132: if (($start!=0) && ($start>$now)) { next; }
6133: if (($end!=0) && ($end<$now)) {
6134: if ($access_end && $access_end < $now) {
6135: if ($access_end - $end < 86400) {
6136: push(@usersgroups,$group);
1.733 raeburn 6137: }
6138: }
1.817 raeburn 6139: next;
1.733 raeburn 6140: }
1.817 raeburn 6141: push(@usersgroups,$group);
1.683 raeburn 6142: }
6143: }
6144: }
1.817 raeburn 6145: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6146: $grouplist = join(':',@usersgroups);
6147: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6148: }
1.733 raeburn 6149: return @usersgroups;
1.683 raeburn 6150: }
6151:
6152: sub devalidate_getgroups_cache {
6153: my ($udom,$uname,$cdom,$cnum)=@_;
6154: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6155:
1.683 raeburn 6156: my $hashid="$udom:$uname:$courseid";
6157: &devalidate_cache_new('getgroups',$hashid);
6158: }
6159:
1.12 www 6160: # ------------------------------------------------------------------ Plain Text
6161:
6162: sub plaintext {
1.988 raeburn 6163: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6164: if ($short =~ m{^cr/}) {
1.758 albertel 6165: return (split('/',$short))[-1];
6166: }
1.742 raeburn 6167: if (!defined($cid)) {
6168: $cid = $env{'request.course.id'};
6169: }
6170: my %rolenames = (
1.1008 raeburn 6171: Course => 'std',
6172: Community => 'alt1',
1.742 raeburn 6173: );
1.1037 raeburn 6174: if ($cid ne '') {
6175: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6176: unless ($forcedefault) {
6177: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6178: &Apache::lonlocal::mt_escape(\$roletext);
6179: return &Apache::lonlocal::mt($roletext);
6180: }
6181: }
6182: }
6183: if ((defined($type)) && (defined($rolenames{$type})) &&
6184: (defined($rolenames{$type})) &&
6185: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6186: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6187: } elsif ($cid ne '') {
6188: my $crstype = $env{'course.'.$cid.'.type'};
6189: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6190: (defined($prp{$short}{$rolenames{$crstype}}))) {
6191: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6192: }
1.742 raeburn 6193: }
1.1037 raeburn 6194: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6195: }
6196:
6197: # ----------------------------------------------------------------- Assign Role
6198:
6199: sub assignrole {
1.957 raeburn 6200: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6201: $context)=@_;
1.21 www 6202: my $mrole;
6203: if ($role =~ /^cr\//) {
1.393 www 6204: my $cwosec=$url;
1.811 albertel 6205: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6206: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6207: my $refused = 1;
6208: if ($context eq 'requestcourses') {
6209: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6210: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6211: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6212: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6213: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6214: if ($crsenv{'internal.courseowner'} eq
6215: $env{'user.name'}.':'.$env{'user.domain'}) {
6216: $refused = '';
6217: }
6218: }
6219: }
6220: }
6221: }
6222: if ($refused) {
6223: &logthis('Refused custom assignrole: '.
6224: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6225: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6226: return 'refused';
6227: }
1.104 www 6228: }
1.21 www 6229: $mrole='cr';
1.678 raeburn 6230: } elsif ($role =~ /^gr\//) {
6231: my $cwogrp=$url;
1.811 albertel 6232: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6233: unless (&allowed('mdg',$cwogrp)) {
6234: &logthis('Refused group assignrole: '.
6235: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6236: $env{'user.name'}.' at '.$env{'user.domain'});
6237: return 'refused';
6238: }
6239: $mrole='gr';
1.21 www 6240: } else {
1.82 www 6241: my $cwosec=$url;
1.811 albertel 6242: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6243: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6244: my $refused;
6245: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6246: if (!(&allowed('c'.$role,$url))) {
6247: $refused = 1;
6248: }
6249: } else {
6250: $refused = 1;
6251: }
1.947 raeburn 6252: if ($refused) {
1.1045 raeburn 6253: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6254: if (!$selfenroll && $context eq 'course') {
6255: my %crsenv;
6256: if ($role eq 'cc' || $role eq 'co') {
6257: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6258: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6259: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6260: if ($crsenv{'internal.courseowner'} eq
6261: $env{'user.name'}.':'.$env{'user.domain'}) {
6262: $refused = '';
6263: }
6264: }
6265: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6266: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6267: if ($crsenv{'internal.courseowner'} eq
6268: $env{'user.name'}.':'.$env{'user.domain'}) {
6269: $refused = '';
6270: }
6271: }
6272: }
6273: }
6274: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6275: $refused = '';
1.1017 raeburn 6276: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6277: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6278: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6279: my $wrongcc;
6280: if ($cnum =~ /^$match_community$/) {
6281: $wrongcc = 1 if ($role eq 'cc');
6282: } else {
6283: $wrongcc = 1 if ($role eq 'co');
6284: }
6285: unless ($wrongcc) {
6286: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6287: if ($crsenv{'internal.courseowner'} eq
6288: $env{'user.name'}.':'.$env{'user.domain'}) {
6289: $refused = '';
6290: }
1.1017 raeburn 6291: }
6292: }
6293: }
6294: if ($refused) {
1.947 raeburn 6295: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6296: ' '.$role.' '.$end.' '.$start.' by '.
6297: $env{'user.name'}.' at '.$env{'user.domain'});
6298: return 'refused';
6299: }
1.932 raeburn 6300: }
1.104 www 6301: }
1.21 www 6302: $mrole=$role;
6303: }
1.620 albertel 6304: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6305: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6306: if ($end) { $command.='_'.$end; }
1.21 www 6307: if ($start) {
6308: if ($end) {
1.81 www 6309: $command.='_'.$start;
1.21 www 6310: } else {
1.81 www 6311: $command.='_0_'.$start;
1.21 www 6312: }
6313: }
1.739 raeburn 6314: my $origstart = $start;
6315: my $origend = $end;
1.957 raeburn 6316: my $delflag;
1.357 www 6317: # actually delete
6318: if ($deleteflag) {
1.373 www 6319: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6320: # modify command to delete the role
1.620 albertel 6321: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6322: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6323: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6324: # set start and finish to negative values for userrolelog
6325: $start=-1;
6326: $end=-1;
1.957 raeburn 6327: $delflag = 1;
1.357 www 6328: }
6329: }
6330: # send command
1.349 www 6331: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6332: # log new user role if status is ok
1.349 www 6333: if ($answer eq 'ok') {
1.663 raeburn 6334: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6335: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6336: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6337: unless ($role =~ /^gr/) {
6338: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6339: $origstart,$selfenroll,$context);
1.739 raeburn 6340: }
1.1053 raeburn 6341: if ($role eq 'cc') {
6342: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6343: }
1.349 www 6344: }
6345: return $answer;
1.169 harris41 6346: }
6347:
1.1053 raeburn 6348: sub autoupdate_coowners {
6349: my ($url,$end,$start,$uname,$udom) = @_;
6350: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6351: if (($cdom ne '') && ($cnum ne '')) {
6352: my $now = time;
6353: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6354: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6355: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6356: my $instcode = $coursehash{'internal.coursecode'};
6357: if ($instcode ne '') {
1.1056 raeburn 6358: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6359: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6360: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6361: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6362: if ($result eq 'valid') {
6363: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6364: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6365: push(@newcoowners,$coowner);
6366: }
6367: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6368: push(@newcoowners,$uname.':'.$udom);
6369: }
6370: @newcoowners = sort(@newcoowners);
6371: } else {
6372: push(@newcoowners,$uname.':'.$udom);
6373: }
6374: } else {
6375: if ($coursehash{'internal.co-owners'}) {
6376: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6377: unless ($coowner eq $uname.':'.$udom) {
6378: push(@newcoowners,$coowner);
6379: }
6380: }
6381: unless (@newcoowners > 0) {
6382: $delcoowners = 1;
6383: $coowners = '';
6384: }
6385: }
6386: }
6387: if (@newcoowners || $delcoowners) {
6388: &store_coowners($cdom,$cnum,$coursehash{'home'},
6389: $delcoowners,@newcoowners);
6390: }
6391: }
6392: }
6393: }
6394: }
6395: }
6396: }
6397:
6398: sub store_coowners {
6399: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6400: my $cid = $cdom.'_'.$cnum;
6401: my ($coowners,$delresult,$putresult);
6402: if (@newcoowners) {
6403: $coowners = join(',',@newcoowners);
6404: my %coownershash = (
6405: 'internal.co-owners' => $coowners,
6406: );
6407: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6408: if ($putresult eq 'ok') {
6409: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6410: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6411: }
6412: }
6413: }
6414: if ($delcoowners) {
6415: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6416: if ($delresult eq 'ok') {
6417: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6418: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6419: }
6420: }
6421: }
6422: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6423: my %crsinfo =
6424: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6425: if (ref($crsinfo{$cid}) eq 'HASH') {
6426: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6427: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6428: }
6429: }
6430: }
6431:
1.169 harris41 6432: # -------------------------------------------------- Modify user authentication
1.197 www 6433: # Overrides without validation
6434:
1.169 harris41 6435: sub modifyuserauth {
6436: my ($udom,$uname,$umode,$upass)=@_;
6437: my $uhome=&homeserver($uname,$udom);
1.197 www 6438: unless (&allowed('mau',$udom)) { return 'refused'; }
6439: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6440: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6441: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6442: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6443: &escape($upass),$uhome);
1.620 albertel 6444: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6445: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6446: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6447: &log($udom,,$uname,$uhome,
1.620 albertel 6448: 'Authentication changed by '.$env{'user.domain'}.', '.
6449: $env{'user.name'}.', '.$umode.
1.197 www 6450: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6451: unless ($reply eq 'ok') {
1.197 www 6452: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6453: return 'error: '.$reply;
6454: }
1.170 harris41 6455: return 'ok';
1.80 www 6456: }
6457:
1.81 www 6458: # --------------------------------------------------------------- Modify a user
1.80 www 6459:
1.81 www 6460: sub modifyuser {
1.206 matthew 6461: my ($udom, $uname, $uid,
6462: $umode, $upass, $first,
6463: $middle, $last, $gene,
1.1058 raeburn 6464: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6465: $udom= &LONCAPA::clean_domain($udom);
6466: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6467: my $showcandelete = 'none';
6468: if (ref($candelete) eq 'ARRAY') {
6469: if (@{$candelete} > 0) {
6470: $showcandelete = join(', ',@{$candelete});
6471: }
6472: }
1.81 www 6473: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6474: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6475: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6476: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6477: ' desiredhome not specified').
1.620 albertel 6478: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6479: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6480: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 6481: # ----------------------------------------------------------------- Create User
1.406 albertel 6482: if (($uhome eq 'no_host') &&
6483: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6484: my $unhome='';
1.844 albertel 6485: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6486: $unhome = $desiredhome;
1.620 albertel 6487: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6488: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6489: } else { # load balancing routine for determining $unhome
1.81 www 6490: my $loadm=10000000;
1.841 albertel 6491: my %servers = &get_servers($udom,'library');
6492: foreach my $tryserver (keys(%servers)) {
6493: my $answer=reply('load',$tryserver);
6494: if (($answer=~/\d+/) && ($answer<$loadm)) {
6495: $loadm=$answer;
6496: $unhome=$tryserver;
6497: }
1.80 www 6498: }
6499: }
6500: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6501: return 'error: unable to find a home server for '.$uname.
6502: ' in domain '.$udom;
1.80 www 6503: }
6504: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6505: &escape($upass),$unhome);
6506: unless ($reply eq 'ok') {
6507: return 'error: '.$reply;
6508: }
1.230 stredwic 6509: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6510: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6511: return 'error: unable verify users home machine.';
1.80 www 6512: }
1.209 matthew 6513: } # End of creation of new user
1.80 www 6514: # ---------------------------------------------------------------------- Add ID
6515: if ($uid) {
6516: $uid=~tr/A-Z/a-z/;
6517: my %uidhash=&idrget($udom,$uname);
1.196 www 6518: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6519: && (!$forceid)) {
1.80 www 6520: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6521: return 'error: user id "'.$uid.'" does not match '.
6522: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6523: }
6524: } else {
6525: &idput($udom,($uname => $uid));
6526: }
6527: }
6528: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6529: my @tmp=&get('environment',
1.899 raeburn 6530: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6531: 'permanentemail','inststatus'],
1.134 albertel 6532: $udom,$uname);
1.313 matthew 6533: my %names;
6534: if ($tmp[0] =~ m/^error:.*/) {
6535: %names=();
6536: } else {
6537: %names = @tmp;
6538: }
1.388 www 6539: #
1.1058 raeburn 6540: # If name, email and/or uid are blank (e.g., because an uploaded file
6541: # of users did not contain them), do not overwrite existing values
6542: # unless field is in $candelete array ref.
6543: #
6544:
6545: my @fields = ('firstname','middlename','lastname','generation',
6546: 'permanentemail','id');
6547: my %newvalues;
6548: if (ref($candelete) eq 'ARRAY') {
6549: foreach my $field (@fields) {
6550: if (grep(/^\Q$field\E$/,@{$candelete})) {
6551: if ($field eq 'firstname') {
6552: $names{$field} = $first;
6553: } elsif ($field eq 'middlename') {
6554: $names{$field} = $middle;
6555: } elsif ($field eq 'lastname') {
6556: $names{$field} = $last;
6557: } elsif ($field eq 'generation') {
6558: $names{$field} = $gene;
6559: } elsif ($field eq 'permanentemail') {
6560: $names{$field} = $email;
6561: } elsif ($field eq 'id') {
6562: $names{$field} = $uid;
6563: }
6564: }
6565: }
6566: }
1.388 www 6567: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6568: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6569: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6570: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6571: if ($email) {
6572: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6573: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6574: }
1.899 raeburn 6575: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6576: if (defined($inststatus)) {
6577: $names{'inststatus'} = '';
6578: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6579: if (ref($usertypes) eq 'HASH') {
6580: my @okstatuses;
6581: foreach my $item (split(/:/,$inststatus)) {
6582: if (defined($usertypes->{$item})) {
6583: push(@okstatuses,$item);
6584: }
6585: }
6586: if (@okstatuses) {
6587: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6588: }
6589: }
6590: }
1.134 albertel 6591: my $reply = &put('environment', \%names, $udom,$uname);
6592: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 6593: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 6594: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 6595: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6596: $umode.', '.$first.', '.$middle.', '.
6597: $last.', '.$gene.', '.$email.', '.$inststatus;
6598: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6599: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6600: } else {
6601: $logmsg .= ' during self creation';
6602: }
6603: &logthis($logmsg);
1.134 albertel 6604: return 'ok';
1.80 www 6605: }
6606:
1.81 www 6607: # -------------------------------------------------------------- Modify student
1.80 www 6608:
1.81 www 6609: sub modifystudent {
6610: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6611: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6612: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6613: if (!$cid) {
1.620 albertel 6614: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6615: return 'not_in_class';
6616: }
1.80 www 6617: }
6618: # --------------------------------------------------------------- Make the user
1.81 www 6619: my $reply=&modifyuser
1.209 matthew 6620: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6621: $desiredhome,$email,$inststatus);
1.80 www 6622: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6623: # This will cause &modify_student_enrollment to get the uid from the
6624: # students environment
6625: $uid = undef if (!$forceid);
1.455 albertel 6626: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6627: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6628: return $reply;
6629: }
6630:
6631: sub modify_student_enrollment {
1.957 raeburn 6632: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6633: my ($cdom,$cnum,$chome);
6634: if (!$cid) {
1.620 albertel 6635: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6636: return 'not_in_class';
6637: }
1.620 albertel 6638: $cdom=$env{'course.'.$cid.'.domain'};
6639: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6640: } else {
6641: ($cdom,$cnum)=split(/_/,$cid);
6642: }
1.620 albertel 6643: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6644: if (!$chome) {
1.457 raeburn 6645: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6646: }
1.455 albertel 6647: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6648: # Make sure the user exists
1.81 www 6649: my $uhome=&homeserver($uname,$udom);
6650: if (($uhome eq '') || ($uhome eq 'no_host')) {
6651: return 'error: no such user';
6652: }
1.297 matthew 6653: # Get student data if we were not given enough information
6654: if (!defined($first) || $first eq '' ||
6655: !defined($last) || $last eq '' ||
6656: !defined($uid) || $uid eq '' ||
6657: !defined($middle) || $middle eq '' ||
6658: !defined($gene) || $gene eq '') {
1.294 matthew 6659: # They did not supply us with enough data to enroll the student, so
6660: # we need to pick up more information.
1.297 matthew 6661: my %tmp = &get('environment',
1.294 matthew 6662: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6663: ,$udom,$uname);
6664:
1.800 albertel 6665: #foreach my $key (keys(%tmp)) {
6666: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6667: #}
1.294 matthew 6668: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6669: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6670: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6671: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6672: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6673: }
1.556 albertel 6674: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6675: my $reply=cput('classlist',
6676: {"$uname:$udom" =>
1.515 raeburn 6677: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6678: $cdom,$cnum);
1.81 www 6679: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6680: return 'error: '.$reply;
1.652 albertel 6681: } else {
6682: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6683: }
1.297 matthew 6684: # Add student role to user
1.83 www 6685: my $uurl='/'.$cid;
1.81 www 6686: $uurl=~s/\_/\//g;
6687: if ($usec) {
6688: $uurl.='/'.$usec;
6689: }
1.957 raeburn 6690: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6691: }
6692:
1.556 albertel 6693: sub format_name {
6694: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6695: my $name;
6696: if ($first ne 'lastname') {
6697: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6698: } else {
6699: if ($lastname=~/\S/) {
6700: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6701: $name=~s/\s+,/,/;
6702: } else {
6703: $name.= $firstname.' '.$middlename.' '.$generation;
6704: }
6705: }
6706: $name=~s/^\s+//;
6707: $name=~s/\s+$//;
6708: $name=~s/\s+/ /g;
6709: return $name;
6710: }
6711:
1.84 www 6712: # ------------------------------------------------- Write to course preferences
6713:
6714: sub writecoursepref {
6715: my ($courseid,%prefs)=@_;
6716: $courseid=~s/^\///;
6717: $courseid=~s/\_/\//g;
6718: my ($cdomain,$cnum)=split(/\//,$courseid);
6719: my $chome=homeserver($cnum,$cdomain);
6720: if (($chome eq '') || ($chome eq 'no_host')) {
6721: return 'error: no such course';
6722: }
6723: my $cstring='';
1.800 albertel 6724: foreach my $pref (keys(%prefs)) {
6725: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6726: }
1.84 www 6727: $cstring=~s/\&$//;
6728: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6729: }
6730:
6731: # ---------------------------------------------------------- Make/modify course
6732:
6733: sub createcourse {
1.741 raeburn 6734: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6735: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 6736: $url=&declutter($url);
6737: my $cid='';
1.1028 raeburn 6738: if ($context eq 'requestcourses') {
6739: my $can_create = 0;
6740: my ($ownername,$ownerdom) = split(':',$course_owner);
6741: if ($udom eq $ownerdom) {
6742: if (&usertools_access($ownername,$ownerdom,$category,undef,
6743: $context)) {
6744: $can_create = 1;
6745: }
6746: } else {
6747: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6748: $category);
6749: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6750: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6751: if (@curr > 0) {
6752: my @options = qw(approval validate autolimit);
6753: my $optregex = join('|',@options);
6754: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6755: $can_create = 1;
6756: }
6757: }
6758: }
6759: }
6760: if ($can_create) {
6761: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6762: unless (&allowed('ccc',$udom)) {
6763: return 'refused';
6764: }
1.1017 raeburn 6765: }
6766: } else {
6767: return 'refused';
6768: }
1.1028 raeburn 6769: } elsif (!&allowed('ccc',$udom)) {
6770: return 'refused';
1.84 www 6771: }
1.1011 raeburn 6772: # --------------------------------------------------------------- Get Unique ID
6773: my $uname;
6774: if ($cnum =~ /^$match_courseid$/) {
6775: my $chome=&homeserver($cnum,$udom,'true');
6776: if (($chome eq '') || ($chome eq 'no_host')) {
6777: $uname = $cnum;
6778: } else {
1.1038 raeburn 6779: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6780: }
6781: } else {
1.1038 raeburn 6782: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6783: }
6784: return $uname if ($uname =~ /^error/);
6785: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 6786: if (!defined($course_server)) {
6787: if (defined(&domain($udom,'primary'))) {
6788: $course_server = &domain($udom,'primary');
6789: } else {
6790: $course_server = $env{'user.home'};
6791: }
6792: }
6793: my %host_servers =
6794: &Apache::lonnet::get_servers($udom,'library');
6795: unless ($host_servers{$course_server}) {
6796: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 6797: }
1.84 www 6798: # ------------------------------------------------------------- Make the course
6799: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6800: $course_server);
1.84 www 6801: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 6802: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6803: if (($uhome eq '') || ($uhome eq 'no_host')) {
6804: return 'error: no such course';
6805: }
1.271 www 6806: # ----------------------------------------------------------------- Course made
1.516 raeburn 6807: # log existence
1.1029 raeburn 6808: my $now = time;
1.918 raeburn 6809: my $newcourse = {
6810: $udom.'_'.$uname => {
1.921 raeburn 6811: description => $description,
6812: inst_code => $inst_code,
6813: owner => $course_owner,
6814: type => $crstype,
1.1029 raeburn 6815: creator => $env{'user.name'}.':'.
6816: $env{'user.domain'},
6817: created => $now,
6818: context => $context,
1.918 raeburn 6819: },
6820: };
1.921 raeburn 6821: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6822: # set toplevel url
1.271 www 6823: my $topurl=$url;
6824: unless ($nonstandard) {
6825: # ------------------------------------------ For standard courses, make top url
6826: my $mapurl=&clutter($url);
1.278 www 6827: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6828: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6829: <map>
6830: <resource id="1" type="start"></resource>
6831: <resource id="2" src="$mapurl"></resource>
6832: <resource id="3" type="finish"></resource>
6833: <link index="1" from="1" to="2"></link>
6834: <link index="2" from="2" to="3"></link>
6835: </map>
6836: ENDINITMAP
6837: $topurl=&declutter(
1.638 albertel 6838: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6839: );
6840: }
6841: # ----------------------------------------------------------- Write preferences
1.84 www 6842: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 6843: ('description' => $description,
6844: 'url' => $topurl,
6845: 'internal.creator' => $env{'user.name'}.':'.
6846: $env{'user.domain'},
6847: 'internal.created' => $now,
6848: 'internal.creationcontext' => $context)
6849: );
1.84 www 6850: return '/'.$udom.'/'.$uname;
6851: }
6852:
1.1011 raeburn 6853: # ------------------------------------------------------------------- Create ID
6854: sub generate_coursenum {
1.1038 raeburn 6855: my ($udom,$crstype) = @_;
1.1011 raeburn 6856: my $domdesc = &domain($udom);
6857: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 6858: my $first;
6859: if ($crstype eq 'Community') {
6860: $first = '0';
6861: } else {
6862: $first = int(1+rand(9));
6863: }
6864: my $uname=$first.
1.1011 raeburn 6865: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6866: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6867: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6868: # ----------------------------------------------- Make sure that does not exist
6869: my $uhome=&homeserver($uname,$udom,'true');
6870: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 6871: if ($crstype eq 'Community') {
6872: $first = '0';
6873: } else {
6874: $first = int(1+rand(9));
6875: }
6876: $uname=$first.
1.1011 raeburn 6877: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6878: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6879: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6880: $uhome=&homeserver($uname,$udom,'true');
6881: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6882: return 'error: unable to generate unique course-ID';
6883: }
6884: }
6885: return $uname;
6886: }
6887:
1.813 albertel 6888: sub is_course {
6889: my ($cdom,$cnum) = @_;
6890: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6891: undef,'.');
1.813 albertel 6892: if (exists($courses{$cdom.'_'.$cnum})) {
6893: return 1;
6894: }
6895: return 0;
6896: }
6897:
1.1015 raeburn 6898: sub store_userdata {
6899: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 6900: my $result;
1.1016 raeburn 6901: if ($datakey ne '') {
1.1013 raeburn 6902: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 6903: if ($udom eq '' || $uname eq '') {
6904: $udom = $env{'user.domain'};
6905: $uname = $env{'user.name'};
6906: }
6907: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 6908: if (($uhome eq '') || ($uhome eq 'no_host')) {
6909: $result = 'error: no_host';
6910: } else {
6911: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
6912: $storehash->{'host'} = $perlvar{'lonHostID'};
6913:
6914: my $namevalue='';
6915: foreach my $key (keys(%{$storehash})) {
6916: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6917: }
6918: $namevalue=~s/\&$//;
6919: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 6920: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 6921: }
6922: } else {
6923: $result = 'error: data to store was not a hash reference';
6924: }
6925: } else {
6926: $result= 'error: invalid requestkey';
6927: }
6928: return $result;
6929: }
6930:
1.21 www 6931: # ---------------------------------------------------------- Assign Custom Role
6932:
6933: sub assigncustomrole {
1.957 raeburn 6934: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6935: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6936: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6937: }
6938:
6939: # ----------------------------------------------------------------- Revoke Role
6940:
6941: sub revokerole {
1.957 raeburn 6942: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6943: my $now=time;
1.965 raeburn 6944: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6945: }
6946:
6947: # ---------------------------------------------------------- Revoke Custom Role
6948:
6949: sub revokecustomrole {
1.957 raeburn 6950: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6951: my $now=time;
1.357 www 6952: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6953: $deleteflag,$selfenroll,$context);
1.17 www 6954: }
6955:
1.533 banghart 6956: # ------------------------------------------------------------ Disk usage
1.535 albertel 6957: sub diskusage {
1.955 raeburn 6958: my ($udom,$uname,$directorypath,$getpropath)=@_;
6959: $directorypath =~ s/\/$//;
6960: my $listing=&reply('du2:'.&escape($directorypath).':'
6961: .&escape($getpropath).':'.&escape($uname).':'
6962: .&escape($udom),homeserver($uname,$udom));
6963: if ($listing eq 'unknown_cmd') {
6964: if ($getpropath) {
6965: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6966: }
6967: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6968: }
1.514 albertel 6969: return $listing;
1.512 banghart 6970: }
6971:
1.566 banghart 6972: sub is_locked {
6973: my ($file_name, $domain, $user) = @_;
6974: my @check;
6975: my $is_locked;
6976: push @check, $file_name;
1.613 albertel 6977: my %locked = &get('file_permissions',\@check,
1.620 albertel 6978: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6979: my ($tmp)=keys(%locked);
6980: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6981:
1.566 banghart 6982: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6983: $is_locked = 'false';
6984: foreach my $entry (@{$locked{$file_name}}) {
6985: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6986: $is_locked = 'true';
6987: last;
1.745 raeburn 6988: }
6989: }
1.566 banghart 6990: } else {
6991: $is_locked = 'false';
6992: }
6993: }
6994:
1.759 albertel 6995: sub declutter_portfile {
6996: my ($file) = @_;
1.833 albertel 6997: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6998: return $file;
6999: }
7000:
1.559 banghart 7001: # ------------------------------------------------------------- Mark as Read Only
7002:
7003: sub mark_as_readonly {
7004: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7005: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7006: my ($tmp)=keys(%current_permissions);
7007: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7008: foreach my $file (@{$files}) {
1.759 albertel 7009: $file = &declutter_portfile($file);
1.561 banghart 7010: push(@{$current_permissions{$file}},$what);
1.559 banghart 7011: }
1.613 albertel 7012: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7013: return;
7014: }
7015:
1.572 banghart 7016: # ------------------------------------------------------------Save Selected Files
7017:
7018: sub save_selected_files {
7019: my ($user, $path, @files) = @_;
7020: my $filename = $user."savedfiles";
1.573 banghart 7021: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7022: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7023: foreach my $file (@files) {
1.620 albertel 7024: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7025: }
7026: foreach my $file (@other_files) {
1.574 banghart 7027: print (OUT $file."\n");
1.572 banghart 7028: }
1.574 banghart 7029: close (OUT);
1.572 banghart 7030: return 'ok';
7031: }
7032:
1.574 banghart 7033: sub clear_selected_files {
7034: my ($user) = @_;
7035: my $filename = $user."savedfiles";
7036: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7037: print (OUT undef);
7038: close (OUT);
7039: return ("ok");
7040: }
7041:
1.572 banghart 7042: sub files_in_path {
7043: my ($user, $path) = @_;
7044: my $filename = $user."savedfiles";
7045: my %return_files;
1.574 banghart 7046: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7047: while (my $line_in = <IN>) {
1.574 banghart 7048: chomp ($line_in);
7049: my @paths_and_file = split (m!/!, $line_in);
7050: my $file_part = pop (@paths_and_file);
7051: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7052: $path_part.='/';
7053: my $path_and_file = $path_part.$file_part;
7054: if ($path_part eq $path) {
7055: $return_files{$file_part}= 'selected';
7056: }
7057: }
1.574 banghart 7058: close (IN);
7059: return (\%return_files);
1.572 banghart 7060: }
7061:
7062: # called in portfolio select mode, to show files selected NOT in current directory
7063: sub files_not_in_path {
7064: my ($user, $path) = @_;
7065: my $filename = $user."savedfiles";
7066: my @return_files;
7067: my $path_part;
1.800 albertel 7068: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7069: while (my $line = <IN>) {
1.572 banghart 7070: #ok, I know it's clunky, but I want it to work
1.800 albertel 7071: my @paths_and_file = split(m|/|, $line);
7072: my $file_part = pop(@paths_and_file);
7073: chomp($file_part);
7074: my $path_part = join('/', @paths_and_file);
1.572 banghart 7075: $path_part .= '/';
7076: my $path_and_file = $path_part.$file_part;
7077: if ($path_part ne $path) {
1.800 albertel 7078: push(@return_files, ($path_and_file));
1.572 banghart 7079: }
7080: }
1.800 albertel 7081: close(OUT);
1.574 banghart 7082: return (@return_files);
1.572 banghart 7083: }
7084:
1.745 raeburn 7085: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7086:
1.745 raeburn 7087: sub get_portfile_permissions {
7088: my ($domain,$user) = @_;
1.613 albertel 7089: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7090: my ($tmp)=keys(%current_permissions);
7091: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7092: return \%current_permissions;
7093: }
7094:
7095: #---------------------------------------------Get portfolio file access controls
7096:
1.749 raeburn 7097: sub get_access_controls {
1.745 raeburn 7098: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7099: my %access;
7100: my $real_file = $file;
7101: $file =~ s/\.meta$//;
1.745 raeburn 7102: if (defined($file)) {
1.749 raeburn 7103: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7104: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7105: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7106: }
7107: }
1.745 raeburn 7108: } else {
1.749 raeburn 7109: foreach my $key (keys(%{$current_permissions})) {
7110: if ($key =~ /\0accesscontrol$/) {
7111: if (defined($group)) {
7112: if ($key !~ m-^\Q$group\E/-) {
7113: next;
7114: }
7115: }
7116: my ($fullpath) = split(/\0/,$key);
7117: if (ref($$current_permissions{$key}) eq 'HASH') {
7118: foreach my $control (keys(%{$$current_permissions{$key}})) {
7119: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7120: }
7121: }
7122: }
7123: }
7124: }
7125: return %access;
7126: }
7127:
7128: sub modify_access_controls {
7129: my ($file_name,$changes,$domain,$user)=@_;
7130: my ($outcome,$deloutcome);
7131: my %store_permissions;
7132: my %new_values;
7133: my %new_control;
7134: my %translation;
7135: my @deletions = ();
7136: my $now = time;
7137: if (exists($$changes{'activate'})) {
7138: if (ref($$changes{'activate'}) eq 'HASH') {
7139: my @newitems = sort(keys(%{$$changes{'activate'}}));
7140: my $numnew = scalar(@newitems);
7141: for (my $i=0; $i<$numnew; $i++) {
7142: my $newkey = $newitems[$i];
7143: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7144: if ($newkey =~ /^\d+:/) {
7145: $newkey =~ s/^(\d+)/$newid/;
7146: $translation{$1} = $newid;
7147: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7148: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7149: $translation{$1} = $newid;
7150: }
1.749 raeburn 7151: $new_values{$file_name."\0".$newkey} =
7152: $$changes{'activate'}{$newitems[$i]};
7153: $new_control{$newkey} = $now;
7154: }
7155: }
7156: }
7157: my %todelete;
7158: my %changed_items;
7159: foreach my $action ('delete','update') {
7160: if (exists($$changes{$action})) {
7161: if (ref($$changes{$action}) eq 'HASH') {
7162: foreach my $key (keys(%{$$changes{$action}})) {
7163: my ($itemnum) = ($key =~ /^([^:]+):/);
7164: if ($action eq 'delete') {
7165: $todelete{$itemnum} = 1;
7166: } else {
7167: $changed_items{$itemnum} = $key;
7168: }
7169: }
1.745 raeburn 7170: }
7171: }
1.749 raeburn 7172: }
7173: # get lock on access controls for file.
7174: my $lockhash = {
7175: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7176: ':'.$env{'user.domain'},
7177: };
7178: my $tries = 0;
7179: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7180:
7181: while (($gotlock ne 'ok') && $tries <3) {
7182: $tries ++;
7183: sleep 1;
7184: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7185: }
7186: if ($gotlock eq 'ok') {
7187: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7188: my ($tmp)=keys(%curr_permissions);
7189: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7190: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7191: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7192: if (ref($curr_controls) eq 'HASH') {
7193: foreach my $control_item (keys(%{$curr_controls})) {
7194: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7195: if (defined($todelete{$itemnum})) {
7196: push(@deletions,$file_name."\0".$control_item);
7197: } else {
7198: if (defined($changed_items{$itemnum})) {
7199: $new_control{$changed_items{$itemnum}} = $now;
7200: push(@deletions,$file_name."\0".$control_item);
7201: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7202: } else {
7203: $new_control{$control_item} = $$curr_controls{$control_item};
7204: }
7205: }
1.745 raeburn 7206: }
7207: }
7208: }
1.970 raeburn 7209: my ($group);
7210: if (&is_course($domain,$user)) {
7211: ($group,my $file) = split(/\//,$file_name,2);
7212: }
1.749 raeburn 7213: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7214: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7215: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7216: # remove lock
7217: my @del_lock = ($file_name."\0".'locked_access_records');
7218: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7219: my $sqlresult =
1.970 raeburn 7220: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7221: $group);
1.749 raeburn 7222: } else {
7223: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7224: }
1.749 raeburn 7225: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7226: }
7227:
1.827 raeburn 7228: sub make_public_indefinitely {
7229: my ($requrl) = @_;
7230: my $now = time;
7231: my $action = 'activate';
7232: my $aclnum = 0;
7233: if (&is_portfolio_url($requrl)) {
7234: my (undef,$udom,$unum,$file_name,$group) =
7235: &parse_portfolio_url($requrl);
7236: my $current_perms = &get_portfile_permissions($udom,$unum);
7237: my %access_controls = &get_access_controls($current_perms,
7238: $group,$file_name);
7239: foreach my $key (keys(%{$access_controls{$file_name}})) {
7240: my ($num,$scope,$end,$start) =
7241: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7242: if ($scope eq 'public') {
7243: if ($start <= $now && $end == 0) {
7244: $action = 'none';
7245: } else {
7246: $action = 'update';
7247: $aclnum = $num;
7248: }
7249: last;
7250: }
7251: }
7252: if ($action eq 'none') {
7253: return 'ok';
7254: } else {
7255: my %changes;
7256: my $newend = 0;
7257: my $newstart = $now;
7258: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7259: $changes{$action}{$newkey} = {
7260: type => 'public',
7261: time => {
7262: start => $newstart,
7263: end => $newend,
7264: },
7265: };
7266: my ($outcome,$deloutcome,$new_values,$translation) =
7267: &modify_access_controls($file_name,\%changes,$udom,$unum);
7268: return $outcome;
7269: }
7270: } else {
7271: return 'invalid';
7272: }
7273: }
7274:
1.745 raeburn 7275: #------------------------------------------------------Get Marked as Read Only
7276:
7277: sub get_marked_as_readonly {
7278: my ($domain,$user,$what,$group) = @_;
7279: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7280: my @readonly_files;
1.629 banghart 7281: my $cmp1=$what;
7282: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7283: while (my ($file_name,$value) = each(%{$current_permissions})) {
7284: if (defined($group)) {
7285: if ($file_name !~ m-^\Q$group\E/-) {
7286: next;
7287: }
7288: }
1.561 banghart 7289: if (ref($value) eq "ARRAY"){
7290: foreach my $stored_what (@{$value}) {
1.629 banghart 7291: my $cmp2=$stored_what;
1.759 albertel 7292: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7293: $cmp2=join('',@{$stored_what});
1.745 raeburn 7294: }
1.629 banghart 7295: if ($cmp1 eq $cmp2) {
1.561 banghart 7296: push(@readonly_files, $file_name);
1.745 raeburn 7297: last;
1.563 banghart 7298: } elsif (!defined($what)) {
7299: push(@readonly_files, $file_name);
1.745 raeburn 7300: last;
1.561 banghart 7301: }
7302: }
1.745 raeburn 7303: }
1.561 banghart 7304: }
7305: return @readonly_files;
7306: }
1.577 banghart 7307: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7308:
1.577 banghart 7309: sub get_marked_as_readonly_hash {
1.745 raeburn 7310: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7311: my %readonly_files;
1.745 raeburn 7312: while (my ($file_name,$value) = each(%{$current_permissions})) {
7313: if (defined($group)) {
7314: if ($file_name !~ m-^\Q$group\E/-) {
7315: next;
7316: }
7317: }
1.577 banghart 7318: if (ref($value) eq "ARRAY"){
7319: foreach my $stored_what (@{$value}) {
1.745 raeburn 7320: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7321: foreach my $lock_descriptor(@{$stored_what}) {
7322: if ($lock_descriptor eq 'graded') {
7323: $readonly_files{$file_name} = 'graded';
7324: } elsif ($lock_descriptor eq 'handback') {
7325: $readonly_files{$file_name} = 'handback';
7326: } else {
7327: if (!exists($readonly_files{$file_name})) {
7328: $readonly_files{$file_name} = 'locked';
7329: }
7330: }
1.745 raeburn 7331: }
1.750 banghart 7332: }
1.577 banghart 7333: }
7334: }
7335: }
7336: return %readonly_files;
7337: }
1.559 banghart 7338: # ------------------------------------------------------------ Unmark as Read Only
7339:
7340: sub unmark_as_readonly {
1.629 banghart 7341: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7342: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7343: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7344: $file_name = &declutter_portfile($file_name);
1.634 albertel 7345: my $symb_crs = $what;
7346: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7347: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7348: my ($tmp)=keys(%current_permissions);
7349: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7350: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7351: foreach my $file (@readonly_files) {
1.759 albertel 7352: my $clean_file = &declutter_portfile($file);
7353: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7354: my $current_locks = $current_permissions{$file};
1.563 banghart 7355: my @new_locks;
7356: my @del_keys;
7357: if (ref($current_locks) eq "ARRAY"){
7358: foreach my $locker (@{$current_locks}) {
1.632 albertel 7359: my $compare=$locker;
1.749 raeburn 7360: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7361: $compare=join('',@{$locker});
1.746 raeburn 7362: if ($compare ne $symb_crs) {
7363: push(@new_locks, $locker);
7364: }
1.563 banghart 7365: }
7366: }
1.650 albertel 7367: if (scalar(@new_locks) > 0) {
1.563 banghart 7368: $current_permissions{$file} = \@new_locks;
7369: } else {
7370: push(@del_keys, $file);
1.613 albertel 7371: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7372: delete($current_permissions{$file});
1.563 banghart 7373: }
7374: }
1.561 banghart 7375: }
1.613 albertel 7376: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7377: return;
7378: }
1.512 banghart 7379:
1.17 www 7380: # ------------------------------------------------------------ Directory lister
7381:
7382: sub dirlist {
1.955 raeburn 7383: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7384: $uri=~s/^\///;
7385: $uri=~s/\/$//;
1.253 stredwic 7386: my ($udom, $uname);
1.955 raeburn 7387: if ($getuserdir) {
1.253 stredwic 7388: $udom = $userdomain;
7389: $uname = $username;
1.955 raeburn 7390: } else {
7391: (undef,$udom,$uname)=split(/\//,$uri);
7392: if(defined($userdomain)) {
7393: $udom = $userdomain;
7394: }
7395: if(defined($username)) {
7396: $uname = $username;
7397: }
1.253 stredwic 7398: }
1.955 raeburn 7399: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7400:
1.955 raeburn 7401: $dirRoot = $perlvar{'lonDocRoot'};
7402: if (defined($getpropath)) {
7403: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7404: $dirRoot =~ s/\/$//;
1.955 raeburn 7405: } elsif (defined($getuserdir)) {
7406: my $subdir=$uname.'__';
7407: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7408: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7409: ."/$udom/$subdir/$uname";
7410: } elsif (defined($alternateRoot)) {
7411: $dirRoot = $alternateRoot;
1.751 banghart 7412: }
1.253 stredwic 7413:
7414: if($udom) {
7415: if($uname) {
1.955 raeburn 7416: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7417: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7418: .':'.&escape($uname).':'.&escape($udom),
7419: &homeserver($uname,$udom));
7420: if ($listing eq 'unknown_cmd') {
7421: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7422: &homeserver($uname,$udom));
7423: } else {
7424: @listing_results = map { &unescape($_); } split(/:/,$listing);
7425: }
1.605 matthew 7426: if ($listing eq 'unknown_cmd') {
1.800 albertel 7427: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7428: &homeserver($uname,$udom));
1.605 matthew 7429: @listing_results = split(/:/,$listing);
7430: } else {
7431: @listing_results = map { &unescape($_); } split(/:/,$listing);
7432: }
7433: return @listing_results;
1.955 raeburn 7434: } elsif(!$alternateRoot) {
1.800 albertel 7435: my %allusers;
1.841 albertel 7436: my %servers = &get_servers($udom,'library');
1.955 raeburn 7437: foreach my $tryserver (keys(%servers)) {
7438: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7439: &escape($udom),$tryserver);
7440: if ($listing eq 'unknown_cmd') {
7441: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7442: $udom, $tryserver);
7443: } else {
7444: @listing_results = map { &unescape($_); } split(/:/,$listing);
7445: }
1.841 albertel 7446: if ($listing eq 'unknown_cmd') {
7447: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7448: $udom, $tryserver);
7449: @listing_results = split(/:/,$listing);
7450: } else {
7451: @listing_results =
7452: map { &unescape($_); } split(/:/,$listing);
7453: }
7454: if ($listing_results[0] ne 'no_such_dir' &&
7455: $listing_results[0] ne 'empty' &&
7456: $listing_results[0] ne 'con_lost') {
7457: foreach my $line (@listing_results) {
7458: my ($entry) = split(/&/,$line,2);
7459: $allusers{$entry} = 1;
7460: }
7461: }
1.253 stredwic 7462: }
7463: my $alluserstr='';
1.800 albertel 7464: foreach my $user (sort(keys(%allusers))) {
7465: $alluserstr.=$user.'&user:';
1.253 stredwic 7466: }
7467: $alluserstr=~s/:$//;
7468: return split(/:/,$alluserstr);
7469: } else {
1.800 albertel 7470: return ('missing user name');
1.253 stredwic 7471: }
1.955 raeburn 7472: } elsif(!defined($getpropath)) {
1.841 albertel 7473: my @all_domains = sort(&all_domains());
1.955 raeburn 7474: foreach my $domain (@all_domains) {
7475: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7476: }
7477: return @all_domains;
7478: } else {
1.800 albertel 7479: return ('missing domain');
1.275 stredwic 7480: }
7481: }
7482:
7483: # --------------------------------------------- GetFileTimestamp
7484: # This function utilizes dirlist and returns the date stamp for
7485: # when it was last modified. It will also return an error of -1
7486: # if an error occurs
7487:
7488: sub GetFileTimestamp {
1.955 raeburn 7489: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7490: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7491: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7492: my ($fileStat) =
7493: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7494: undef,$getuserdir);
1.275 stredwic 7495: my @stats = split('&', $fileStat);
7496: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7497: # @stats contains first the filename, then the stat output
7498: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7499: } else {
7500: return -1;
1.253 stredwic 7501: }
1.26 www 7502: }
7503:
1.712 albertel 7504: sub stat_file {
7505: my ($uri) = @_;
1.787 albertel 7506: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7507:
1.955 raeburn 7508: my ($udom,$uname,$file);
1.712 albertel 7509: if ($uri =~ m-^/(uploaded|editupload)/-) {
7510: ($udom,$uname,$file) =
1.811 albertel 7511: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7512: $file = 'userfiles/'.$file;
7513: }
7514: if ($uri =~ m-^/res/-) {
7515: ($udom,$uname) =
1.807 albertel 7516: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7517: $file = $uri;
7518: }
7519:
7520: if (!$udom || !$uname || !$file) {
7521: # unable to handle the uri
7522: return ();
7523: }
1.956 raeburn 7524: my $getpropath;
7525: if ($file =~ /^userfiles\//) {
7526: $getpropath = 1;
7527: }
1.955 raeburn 7528: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7529: my @stats = split('&', $result);
1.721 banghart 7530:
1.712 albertel 7531: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7532: shift(@stats); #filename is first
7533: return @stats;
7534: }
7535: return ();
7536: }
7537:
1.26 www 7538: # -------------------------------------------------------- Value of a Condition
7539:
1.713 albertel 7540: # gets the value of a specific preevaluated condition
7541: # stored in the string $env{user.state.<cid>}
7542: # or looks up a condition reference in the bighash and if if hasn't
7543: # already been evaluated recurses into docondval to get the value of
7544: # the condition, then memoizing it to
7545: # $env{user.state.<cid>.<condition>}
1.40 www 7546: sub directcondval {
7547: my $number=shift;
1.620 albertel 7548: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7549: &Apache::lonuserstate::evalstate();
7550: }
1.713 albertel 7551: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7552: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7553: } elsif ($number =~ /^_/) {
7554: my $sub_condition;
7555: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7556: &GDBM_READER(),0640)) {
7557: $sub_condition=$bighash{'conditions'.$number};
7558: untie(%bighash);
7559: }
7560: my $value = &docondval($sub_condition);
1.949 raeburn 7561: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7562: return $value;
7563: }
1.620 albertel 7564: if ($env{'user.state.'.$env{'request.course.id'}}) {
7565: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7566: } else {
7567: return 2;
7568: }
7569: }
7570:
1.713 albertel 7571: # get the collection of conditions for this resource
1.26 www 7572: sub condval {
7573: my $condidx=shift;
1.54 www 7574: my $allpathcond='';
1.713 albertel 7575: foreach my $cond (split(/\|/,$condidx)) {
7576: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7577: $allpathcond.=
7578: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7579: }
1.191 harris41 7580: }
1.54 www 7581: $allpathcond=~s/\|$//;
1.713 albertel 7582: return &docondval($allpathcond);
7583: }
7584:
7585: #evaluates an expression of conditions
7586: sub docondval {
7587: my ($allpathcond) = @_;
7588: my $result=0;
7589: if ($env{'request.course.id'}
7590: && defined($allpathcond)) {
7591: my $operand='|';
7592: my @stack;
7593: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7594: if ($chunk eq '(') {
7595: push @stack,($operand,$result);
7596: } elsif ($chunk eq ')') {
7597: my $before=pop @stack;
7598: if (pop @stack eq '&') {
7599: $result=$result>$before?$before:$result;
7600: } else {
7601: $result=$result>$before?$result:$before;
7602: }
7603: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7604: $operand=$chunk;
7605: } else {
7606: my $new=directcondval($chunk);
7607: if ($operand eq '&') {
7608: $result=$result>$new?$new:$result;
7609: } else {
7610: $result=$result>$new?$result:$new;
7611: }
7612: }
7613: }
1.26 www 7614: }
7615: return $result;
1.421 albertel 7616: }
7617:
7618: # ---------------------------------------------------- Devalidate courseresdata
7619:
7620: sub devalidatecourseresdata {
7621: my ($coursenum,$coursedomain)=@_;
7622: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7623: &devalidate_cache_new('courseres',$hashid);
1.28 www 7624: }
7625:
1.763 www 7626:
1.200 www 7627: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7628: #
7629: # Parameters:
7630: # $coursenum - Number of the course.
7631: # $coursedomain - Domain at which the course was created.
7632: # Returns:
7633: # A hash of the course parameters along (I think) with timestamps
7634: # and version info.
1.877 foxr 7635:
1.624 albertel 7636: sub get_courseresdata {
7637: my ($coursenum,$coursedomain)=@_;
1.200 www 7638: my $coursehom=&homeserver($coursenum,$coursedomain);
7639: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7640: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7641: my %dumpreply;
1.417 albertel 7642: unless (defined($cached)) {
1.624 albertel 7643: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7644: $result=\%dumpreply;
1.251 albertel 7645: my ($tmp) = keys(%dumpreply);
7646: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7647: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7648: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7649: return $tmp;
1.416 albertel 7650: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7651: $result=undef;
1.599 albertel 7652: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7653: }
7654: }
1.624 albertel 7655: return $result;
7656: }
7657:
1.633 albertel 7658: sub devalidateuserresdata {
7659: my ($uname,$udom)=@_;
7660: my $hashid="$udom:$uname";
7661: &devalidate_cache_new('userres',$hashid);
7662: }
7663:
1.624 albertel 7664: sub get_userresdata {
7665: my ($uname,$udom)=@_;
7666: #most student don\'t have any data set, check if there is some data
7667: if (&EXT_cache_status($udom,$uname)) { return undef; }
7668:
7669: my $hashid="$udom:$uname";
7670: my ($result,$cached)=&is_cached_new('userres',$hashid);
7671: if (!defined($cached)) {
7672: my %resourcedata=&dump('resourcedata',$udom,$uname);
7673: $result=\%resourcedata;
7674: &do_cache_new('userres',$hashid,$result,600);
7675: }
7676: my ($tmp)=keys(%$result);
7677: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7678: return $result;
7679: }
7680: #error 2 occurs when the .db doesn't exist
7681: if ($tmp!~/error: 2 /) {
1.672 albertel 7682: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7683: " Trying to get resource data for ".
7684: $uname." at ".$udom.": ".
7685: $tmp."</font>");
7686: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7687: #&EXT_cache_set($udom,$uname);
7688: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7689: undef($tmp); # not really an error so don't send it back
1.624 albertel 7690: }
7691: return $tmp;
7692: }
1.879 foxr 7693: #----------------------------------------------- resdata - return resource data
7694: # Purpose:
7695: # Return resource data for either users or for a course.
7696: # Parameters:
7697: # $name - Course/user name.
7698: # $domain - Name of the domain the user/course is registered on.
7699: # $type - Type of thing $name is (must be 'course' or 'user'
7700: # @which - Array of names of resources desired.
7701: # Returns:
7702: # The value of the first reasource in @which that is found in the
7703: # resource hash.
7704: # Exceptional Conditions:
7705: # If the $type passed in is not valid (not the string 'course' or
7706: # 'user', an undefined reference is returned.
7707: # If none of the resources are found, an undef is returned
1.624 albertel 7708: sub resdata {
7709: my ($name,$domain,$type,@which)=@_;
7710: my $result;
7711: if ($type eq 'course') {
7712: $result=&get_courseresdata($name,$domain);
7713: } elsif ($type eq 'user') {
7714: $result=&get_userresdata($name,$domain);
7715: }
7716: if (!ref($result)) { return $result; }
1.251 albertel 7717: foreach my $item (@which) {
1.927 albertel 7718: if (defined($result->{$item->[0]})) {
7719: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7720: }
1.250 albertel 7721: }
1.291 albertel 7722: return undef;
1.200 www 7723: }
7724:
1.379 matthew 7725: #
7726: # EXT resource caching routines
7727: #
7728:
7729: sub clear_EXT_cache_status {
1.383 albertel 7730: &delenv('cache.EXT.');
1.379 matthew 7731: }
7732:
7733: sub EXT_cache_status {
7734: my ($target_domain,$target_user) = @_;
1.383 albertel 7735: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7736: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7737: # We know already the user has no data
7738: return 1;
7739: } else {
7740: return 0;
7741: }
7742: }
7743:
7744: sub EXT_cache_set {
7745: my ($target_domain,$target_user) = @_;
1.383 albertel 7746: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7747: #&appenv({$cachename => time});
1.379 matthew 7748: }
7749:
1.28 www 7750: # --------------------------------------------------------- Value of a Variable
1.58 www 7751: sub EXT {
1.715 albertel 7752:
1.395 albertel 7753: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7754: unless ($varname) { return ''; }
1.218 albertel 7755: #get real user name/domain, courseid and symb
7756: my $courseid;
1.359 albertel 7757: my $publicuser;
1.427 www 7758: if ($symbparm) {
7759: $symbparm=&get_symb_from_alias($symbparm);
7760: }
1.218 albertel 7761: if (!($uname && $udom)) {
1.790 albertel 7762: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7763: if (!$symbparm) { $symbparm=$cursymb; }
7764: } else {
1.620 albertel 7765: $courseid=$env{'request.course.id'};
1.218 albertel 7766: }
1.48 www 7767: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7768: my $rest;
1.320 albertel 7769: if (defined($therest[0])) {
1.48 www 7770: $rest=join('.',@therest);
7771: } else {
7772: $rest='';
7773: }
1.320 albertel 7774:
1.57 www 7775: my $qualifierrest=$qualifier;
7776: if ($rest) { $qualifierrest.='.'.$rest; }
7777: my $spacequalifierrest=$space;
7778: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7779: if ($realm eq 'user') {
1.48 www 7780: # --------------------------------------------------------------- user.resource
7781: if ($space eq 'resource') {
1.651 albertel 7782: if ( (defined($Apache::lonhomework::parsing_a_problem)
7783: || defined($Apache::lonhomework::parsing_a_task))
7784: &&
1.744 albertel 7785: ($symbparm eq &symbread()) ) {
7786: # if we are in the middle of processing the resource the
7787: # get the value we are planning on committing
7788: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7789: return $Apache::lonhomework::results{$qualifierrest};
7790: } else {
7791: return $Apache::lonhomework::history{$qualifierrest};
7792: }
1.335 albertel 7793: } else {
1.359 albertel 7794: my %restored;
1.620 albertel 7795: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 7796: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7797: } else {
7798: %restored=&restore($symbparm,$courseid,$udom,$uname);
7799: }
1.335 albertel 7800: return $restored{$qualifierrest};
7801: }
1.48 www 7802: # ----------------------------------------------------------------- user.access
7803: } elsif ($space eq 'access') {
1.218 albertel 7804: # FIXME - not supporting calls for a specific user
1.48 www 7805: return &allowed($qualifier,$rest);
7806: # ------------------------------------------ user.preferences, user.environment
7807: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7808: if (($uname eq $env{'user.name'}) &&
7809: ($udom eq $env{'user.domain'})) {
7810: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7811: } else {
1.359 albertel 7812: my %returnhash;
7813: if (!$publicuser) {
7814: %returnhash=&userenvironment($udom,$uname,
7815: $qualifierrest);
7816: }
1.218 albertel 7817: return $returnhash{$qualifierrest};
7818: }
1.48 www 7819: # ----------------------------------------------------------------- user.course
7820: } elsif ($space eq 'course') {
1.218 albertel 7821: # FIXME - not supporting calls for a specific user
1.620 albertel 7822: return $env{join('.',('request.course',$qualifier))};
1.48 www 7823: # ------------------------------------------------------------------- user.role
7824: } elsif ($space eq 'role') {
1.218 albertel 7825: # FIXME - not supporting calls for a specific user
1.620 albertel 7826: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7827: if ($qualifier eq 'value') {
7828: return $role;
7829: } elsif ($qualifier eq 'extent') {
7830: return $where;
7831: }
7832: # ----------------------------------------------------------------- user.domain
7833: } elsif ($space eq 'domain') {
1.218 albertel 7834: return $udom;
1.48 www 7835: # ------------------------------------------------------------------- user.name
7836: } elsif ($space eq 'name') {
1.218 albertel 7837: return $uname;
1.48 www 7838: # ---------------------------------------------------- Any other user namespace
1.29 www 7839: } else {
1.359 albertel 7840: my %reply;
7841: if (!$publicuser) {
7842: %reply=&get($space,[$qualifierrest],$udom,$uname);
7843: }
7844: return $reply{$qualifierrest};
1.48 www 7845: }
1.236 www 7846: } elsif ($realm eq 'query') {
7847: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7848: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7849: [$spacequalifierrest]);
1.620 albertel 7850: return $env{'form.'.$spacequalifierrest};
1.236 www 7851: } elsif ($realm eq 'request') {
1.48 www 7852: # ------------------------------------------------------------- request.browser
7853: if ($space eq 'browser') {
1.430 www 7854: if ($qualifier eq 'textremote') {
1.676 albertel 7855: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7856: return 1;
7857: } else {
7858: return 0;
7859: }
7860: } else {
1.620 albertel 7861: return $env{'browser.'.$qualifier};
1.430 www 7862: }
1.57 www 7863: # ------------------------------------------------------------ request.filename
7864: } else {
1.620 albertel 7865: return $env{'request.'.$spacequalifierrest};
1.29 www 7866: }
1.28 www 7867: } elsif ($realm eq 'course') {
1.48 www 7868: # ---------------------------------------------------------- course.description
1.620 albertel 7869: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7870: } elsif ($realm eq 'resource') {
1.165 www 7871:
1.620 albertel 7872: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7873: if (!$symbparm) { $symbparm=&symbread(); }
7874: }
1.693 albertel 7875:
7876: if ($space eq 'title') {
7877: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7878: return &gettitle($symbparm);
7879: }
7880:
7881: if ($space eq 'map') {
7882: my ($map) = &decode_symb($symbparm);
7883: return &symbread($map);
7884: }
1.905 albertel 7885: if ($space eq 'filename') {
7886: if ($symbparm) {
7887: return &clutter((&decode_symb($symbparm))[2]);
7888: }
7889: return &hreflocation('',$env{'request.filename'});
7890: }
1.693 albertel 7891:
7892: my ($section, $group, @groups);
1.593 albertel 7893: my ($courselevelm,$courselevel);
1.539 albertel 7894: if ($symbparm && defined($courseid) &&
1.620 albertel 7895: $courseid eq $env{'request.course.id'}) {
1.165 www 7896:
1.218 albertel 7897: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7898:
1.60 www 7899: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7900: my $symbp=$symbparm;
1.735 albertel 7901: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7902:
7903: my $symbparm=$symbp.'.'.$spacequalifierrest;
7904: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7905:
1.620 albertel 7906: if (($env{'user.name'} eq $uname) &&
7907: ($env{'user.domain'} eq $udom)) {
7908: $section=$env{'request.course.sec'};
1.733 raeburn 7909: @groups = split(/:/,$env{'request.course.groups'});
7910: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7911: } else {
1.539 albertel 7912: if (! defined($usection)) {
1.551 albertel 7913: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7914: } else {
7915: $section = $usection;
7916: }
1.733 raeburn 7917: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7918: }
7919:
7920: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7921: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7922: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7923:
1.593 albertel 7924: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7925: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7926: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7927:
1.60 www 7928: # ----------------------------------------------------------- first, check user
1.624 albertel 7929:
7930: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7931: ([$courselevelr,'resource'],
7932: [$courselevelm,'map' ],
7933: [$courselevel, 'course' ]));
1.931 albertel 7934: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7935:
1.594 albertel 7936: # ------------------------------------------------ second, check some of course
1.684 raeburn 7937: my $coursereply;
1.691 raeburn 7938: if (@groups > 0) {
7939: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7940: $mapparm,$spacequalifierrest);
1.927 albertel 7941: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7942: }
1.96 www 7943:
1.684 raeburn 7944: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7945: $env{'course.'.$courseid.'.domain'},
7946: 'course',
7947: ([$seclevelr, 'resource'],
7948: [$seclevelm, 'map' ],
7949: [$seclevel, 'course' ],
7950: [$courselevelr,'resource']));
7951: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7952:
1.60 www 7953: # ------------------------------------------------------ third, check map parms
1.218 albertel 7954: my %parmhash=();
7955: my $thisparm='';
7956: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7957: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7958: &GDBM_READER(),0640)) {
1.218 albertel 7959: $thisparm=$parmhash{$symbparm};
7960: untie(%parmhash);
7961: }
1.927 albertel 7962: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7963: }
1.594 albertel 7964: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7965:
1.218 albertel 7966: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7967: my $filename;
7968: if (!$symbparm) { $symbparm=&symbread(); }
7969: if ($symbparm) {
1.409 www 7970: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7971: } else {
1.620 albertel 7972: $filename=$env{'request.filename'};
1.282 albertel 7973: }
7974: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7975: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7976: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7977: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7978:
1.927 albertel 7979: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7980: if ($symbparm && defined($courseid) &&
1.620 albertel 7981: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7982: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7983: $env{'course.'.$courseid.'.domain'},
7984: 'course',
1.927 albertel 7985: ([$courselevelm,'map' ],
7986: [$courselevel, 'course']));
7987: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7988: }
1.145 www 7989: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7990: unless ($space eq '0') {
1.336 albertel 7991: my @parts=split(/_/,$space);
7992: my $id=pop(@parts);
7993: my $part=join('_',@parts);
7994: if ($part eq '') { $part='0'; }
1.927 albertel 7995: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7996: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7997: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7998: }
1.395 albertel 7999: if ($recurse) { return undef; }
8000: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8001: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8002: # ---------------------------------------------------- Any other user namespace
8003: } elsif ($realm eq 'environment') {
8004: # ----------------------------------------------------------------- environment
1.620 albertel 8005: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8006: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8007: } else {
1.770 albertel 8008: if ($uname eq 'anonymous' && $udom eq '') {
8009: return '';
8010: }
1.219 albertel 8011: my %returnhash=&userenvironment($udom,$uname,
8012: $spacequalifierrest);
8013: return $returnhash{$spacequalifierrest};
8014: }
1.28 www 8015: } elsif ($realm eq 'system') {
1.48 www 8016: # ----------------------------------------------------------------- system.time
8017: if ($space eq 'time') {
8018: return time;
8019: }
1.696 albertel 8020: } elsif ($realm eq 'server') {
8021: # ----------------------------------------------------------------- system.time
8022: if ($space eq 'name') {
8023: return $ENV{'SERVER_NAME'};
8024: }
1.28 www 8025: }
1.48 www 8026: return '';
1.61 www 8027: }
8028:
1.927 albertel 8029: sub get_reply {
8030: my ($reply_value) = @_;
1.940 raeburn 8031: if (ref($reply_value) eq 'ARRAY') {
8032: if (wantarray) {
8033: return @$reply_value;
8034: }
8035: return $reply_value->[0];
8036: } else {
8037: return $reply_value;
1.927 albertel 8038: }
8039: }
8040:
1.691 raeburn 8041: sub check_group_parms {
8042: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8043: my @groupitems = ();
8044: my $resultitem;
1.927 albertel 8045: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8046: foreach my $group (@{$groups}) {
8047: foreach my $level (@levels) {
1.927 albertel 8048: my $item = $courseid.'.['.$group.'].'.$level->[0];
8049: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8050: }
8051: }
8052: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8053: $env{'course.'.$courseid.'.domain'},
8054: 'course',@groupitems);
8055: return $coursereply;
8056: }
8057:
8058: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8059: my ($courseid,@groups) = @_;
8060: @groups = sort(@groups);
1.691 raeburn 8061: return @groups;
8062: }
8063:
1.395 albertel 8064: sub packages_tab_default {
8065: my ($uri,$varname)=@_;
8066: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8067:
8068: my (@extension,@specifics,$do_default);
8069: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8070: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8071: if ($pack_type eq 'default') {
8072: $do_default=1;
8073: } elsif ($pack_type eq 'extension') {
8074: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8075: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8076: # only look at packages defaults for packages that this id is
1.738 albertel 8077: push(@specifics,[$package,$pack_type,$pack_part]);
8078: }
8079: }
8080: # first look for a package that matches the requested part id
8081: foreach my $package (@specifics) {
8082: my (undef,$pack_type,$pack_part)=@{$package};
8083: next if ($pack_part ne $part);
8084: if (defined($packagetab{"$pack_type&$name&default"})) {
8085: return $packagetab{"$pack_type&$name&default"};
8086: }
8087: }
8088: # look for any possible matching non extension_ package
8089: foreach my $package (@specifics) {
8090: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8091: if (defined($packagetab{"$pack_type&$name&default"})) {
8092: return $packagetab{"$pack_type&$name&default"};
8093: }
1.585 albertel 8094: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8095: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8096: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8097: }
8098: }
1.738 albertel 8099: # look for any posible extension_ match
8100: foreach my $package (@extension) {
8101: my ($package,$pack_type)=@{$package};
8102: if (defined($packagetab{"$pack_type&$name&default"})) {
8103: return $packagetab{"$pack_type&$name&default"};
8104: }
8105: if (defined($packagetab{$package."&$name&default"})) {
8106: return $packagetab{$package."&$name&default"};
8107: }
8108: }
8109: # look for a global default setting
8110: if ($do_default && defined($packagetab{"default&$name&default"})) {
8111: return $packagetab{"default&$name&default"};
8112: }
1.395 albertel 8113: return undef;
8114: }
8115:
1.334 albertel 8116: sub add_prefix_and_part {
8117: my ($prefix,$part)=@_;
8118: my $keyroot;
8119: if (defined($prefix) && $prefix !~ /^__/) {
8120: # prefix that has a part already
8121: $keyroot=$prefix;
8122: } elsif (defined($prefix)) {
8123: # prefix that is missing a part
8124: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8125: } else {
8126: # no prefix at all
8127: if (defined($part)) { $keyroot='_'.$part; }
8128: }
8129: return $keyroot;
8130: }
8131:
1.71 www 8132: # ---------------------------------------------------------------- Get metadata
8133:
1.599 albertel 8134: my %metaentry;
1.1070 www 8135: my %importedpartids;
1.71 www 8136: sub metadata {
1.176 www 8137: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8138: $uri=&declutter($uri);
1.288 albertel 8139: # if it is a non metadata possible uri return quickly
1.529 albertel 8140: if (($uri eq '') ||
8141: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8142: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8143: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8144: return undef;
8145: }
8146: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8147: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8148: return undef;
1.288 albertel 8149: }
1.73 www 8150: my $filename=$uri;
8151: $uri=~s/\.meta$//;
1.172 www 8152: #
8153: # Is the metadata already cached?
1.177 www 8154: # Look at timestamp of caching
1.172 www 8155: # Everything is cached by the main uri, libraries are never directly cached
8156: #
1.428 albertel 8157: if (!defined($liburi)) {
1.599 albertel 8158: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8159: if (defined($cached)) { return $result->{':'.$what}; }
8160: }
8161: {
1.1069 www 8162: # Imported parts would go here
1.1070 www 8163: my %importedids=();
8164: my @origfileimportpartids=();
1.1069 www 8165: my $importedparts=0;
1.172 www 8166: #
8167: # Is this a recursive call for a library?
8168: #
1.599 albertel 8169: # if (! exists($metacache{$uri})) {
8170: # $metacache{$uri}={};
8171: # }
1.924 albertel 8172: my $cachetime = 60*60;
1.171 www 8173: if ($liburi) {
8174: $liburi=&declutter($liburi);
8175: $filename=$liburi;
1.401 bowersj2 8176: } else {
1.599 albertel 8177: &devalidate_cache_new('meta',$uri);
8178: undef(%metaentry);
1.401 bowersj2 8179: }
1.140 www 8180: my %metathesekeys=();
1.73 www 8181: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8182: my $metastring;
1.924 albertel 8183: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8184: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8185: $metastring =
1.929 albertel 8186: &Apache::lonnet::ssi_body($which,
1.924 albertel 8187: ('grade_target' => 'meta'));
8188: $cachetime = 1; # only want this cached in the child not long term
8189: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8190: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8191: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8192: $metastring=&getfile($file);
1.489 albertel 8193: }
1.208 albertel 8194: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8195: my $token;
1.140 www 8196: undef %metathesekeys;
1.71 www 8197: while ($token=$parser->get_token) {
1.339 albertel 8198: if ($token->[0] eq 'S') {
8199: if (defined($token->[2]->{'package'})) {
1.172 www 8200: #
8201: # This is a package - get package info
8202: #
1.339 albertel 8203: my $package=$token->[2]->{'package'};
8204: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8205: if (defined($token->[2]->{'id'})) {
8206: $keyroot.='_'.$token->[2]->{'id'};
8207: }
1.599 albertel 8208: if ($metaentry{':packages'}) {
8209: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8210: } else {
1.599 albertel 8211: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8212: }
1.736 albertel 8213: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8214: my $part=$keyroot;
8215: $part=~s/^\_//;
1.736 albertel 8216: if ($pack_entry=~/^\Q$package\E\&/ ||
8217: $pack_entry=~/^\Q$package\E_0\&/) {
8218: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8219: # ignore package.tab specified default values
8220: # here &package_tab_default() will fetch those
8221: if ($subp eq 'default') { next; }
1.736 albertel 8222: my $value=$packagetab{$pack_entry};
1.432 albertel 8223: my $unikey;
8224: if ($pack =~ /_0$/) {
8225: $unikey='parameter_0_'.$name;
8226: $part=0;
8227: } else {
8228: $unikey='parameter'.$keyroot.'_'.$name;
8229: }
1.339 albertel 8230: if ($subp eq 'display') {
8231: $value.=' [Part: '.$part.']';
8232: }
1.599 albertel 8233: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8234: $metathesekeys{$unikey}=1;
1.599 albertel 8235: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8236: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8237: }
1.599 albertel 8238: if (defined($metaentry{':'.$unikey.'.default'})) {
8239: $metaentry{':'.$unikey}=
8240: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8241: }
1.339 albertel 8242: }
8243: }
8244: } else {
1.172 www 8245: #
8246: # This is not a package - some other kind of start tag
1.339 albertel 8247: #
8248: my $entry=$token->[1];
1.1068 www 8249: my $unikey='';
1.175 www 8250:
1.339 albertel 8251: if ($entry eq 'import') {
1.175 www 8252: #
8253: # Importing a library here
1.339 albertel 8254: #
1.1067 www 8255: my $location=$parser->get_text('/import');
8256: my $dir=$filename;
8257: $dir=~s|[^/]*$||;
8258: $location=&filelocation($dir,$location);
1.1069 www 8259:
1.1068 www 8260: my $importmode=$token->[2]->{'importmode'};
8261: if ($importmode eq 'problem') {
1.1069 www 8262: # Import as problem/response
1.1068 www 8263: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8264: } elsif ($importmode eq 'part') {
8265: # Import as part(s)
1.1069 www 8266: $importedparts=1;
8267: # We need to get the original file and the imported file to get the part order correct
8268: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8269: # Load and inspect original file
1.1070 www 8270: if ($#origfileimportpartids<0) {
8271: undef(%importedpartids);
8272: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8273: my $origfile=&getfile($origfilelocation);
8274: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8275: }
8276:
1.1069 www 8277: # Load and inspect imported file
8278: my $impfile=&getfile($location);
8279: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8280: if ($#impfilepartids>=0) {
8281: # This problem had parts
1.1070 www 8282: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8283: } else {
8284: # Importing by turning a single problem into a problem part
8285: # It gets the import-tags ID as part-ID
8286: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8287: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8288: }
1.1068 www 8289: } else {
8290: # Normal import
8291: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8292: if (defined($token->[2]->{'id'})) {
8293: $unikey.='_'.$token->[2]->{'id'};
8294: }
1.1067 www 8295: }
8296:
1.339 albertel 8297: if ($depthcount<20) {
1.736 albertel 8298: my $metadata =
8299: &metadata($uri,'keys', $location,$unikey,
8300: $depthcount+1);
8301: foreach my $meta (split(',',$metadata)) {
8302: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8303: $metathesekeys{$meta}=1;
1.339 albertel 8304: }
1.1068 www 8305:
8306: }
1.1067 www 8307: } else {
8308: #
8309: # Not importing, some other kind of non-package, non-library start tag
8310: #
8311: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8312: if (defined($token->[2]->{'id'})) {
8313: $unikey.='_'.$token->[2]->{'id'};
8314: }
1.339 albertel 8315: if (defined($token->[2]->{'name'})) {
8316: $unikey.='_'.$token->[2]->{'name'};
8317: }
8318: $metathesekeys{$unikey}=1;
1.736 albertel 8319: foreach my $param (@{$token->[3]}) {
8320: $metaentry{':'.$unikey.'.'.$param} =
8321: $token->[2]->{$param};
1.339 albertel 8322: }
8323: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8324: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8325: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8326: # only ws inside the tag, and not in default, so use default
8327: # as value
1.599 albertel 8328: $metaentry{':'.$unikey}=$default;
1.908 albertel 8329: } elsif ( $internaltext =~ /\S/ ) {
8330: # something interesting inside the tag
8331: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8332: } else {
1.908 albertel 8333: # no interesting values, don't set a default
1.339 albertel 8334: }
1.172 www 8335: # end of not-a-package not-a-library import
1.339 albertel 8336: }
1.172 www 8337: # end of not-a-package start tag
1.339 albertel 8338: }
1.172 www 8339: # the next is the end of "start tag"
1.339 albertel 8340: }
8341: }
1.483 albertel 8342: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8343: $extension = lc($extension);
8344: if ($extension eq 'htm') { $extension='html'; }
8345:
1.737 albertel 8346: foreach my $key (keys(%packagetab)) {
1.483 albertel 8347: #no specific packages #how's our extension
8348: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8349: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8350: \%metathesekeys);
8351: }
1.883 albertel 8352:
8353: if (!exists($metaentry{':packages'})
8354: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8355: foreach my $key (keys(%packagetab)) {
1.483 albertel 8356: #no specific packages well let's get default then
8357: if ($key!~/^default&/) { next; }
1.488 albertel 8358: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8359: \%metathesekeys);
8360: }
8361: }
1.338 www 8362: # are there custom rights to evaluate
1.599 albertel 8363: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8364:
1.338 www 8365: #
8366: # Importing a rights file here
1.339 albertel 8367: #
8368: unless ($depthcount) {
1.599 albertel 8369: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8370: my $dir=$filename;
8371: $dir=~s|[^/]*$||;
8372: $location=&filelocation($dir,$location);
1.736 albertel 8373: my $rights_metadata =
8374: &metadata($uri,'keys',$location,'_rights',
8375: $depthcount+1);
8376: foreach my $rights (split(',',$rights_metadata)) {
8377: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8378: $metathesekeys{$rights}=1;
1.339 albertel 8379: }
8380: }
8381: }
1.737 albertel 8382: # uniqifiy package listing
8383: my %seen;
8384: my @uniq_packages =
8385: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8386: $metaentry{':packages'} = join(',',@uniq_packages);
8387:
1.1070 www 8388: if ($importedparts) {
8389: # We had imported parts and need to rebuild partorder
8390: $metaentry{':partorder'}='';
8391: $metathesekeys{'partorder'}=1;
8392: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8393: if ($origfileimportpartids[$index] eq 'part') {
8394: # original part, part of the problem
8395: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8396: } else {
8397: # we have imported parts at this position
8398: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8399: }
8400: }
8401: $metaentry{':partorder'}=~s/^\,//;
8402: }
8403:
1.737 albertel 8404: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8405: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8406: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8407: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8408: # this is the end of "was not already recently cached
1.71 www 8409: }
1.599 albertel 8410: return $metaentry{':'.$what};
1.261 albertel 8411: }
8412:
1.488 albertel 8413: sub metadata_create_package_def {
1.483 albertel 8414: my ($uri,$key,$package,$metathesekeys)=@_;
8415: my ($pack,$name,$subp)=split(/\&/,$key);
8416: if ($subp eq 'default') { next; }
8417:
1.599 albertel 8418: if (defined($metaentry{':packages'})) {
8419: $metaentry{':packages'}.=','.$package;
1.483 albertel 8420: } else {
1.599 albertel 8421: $metaentry{':packages'}=$package;
1.483 albertel 8422: }
8423: my $value=$packagetab{$key};
8424: my $unikey;
8425: $unikey='parameter_0_'.$name;
1.599 albertel 8426: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8427: $$metathesekeys{$unikey}=1;
1.599 albertel 8428: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8429: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8430: }
1.599 albertel 8431: if (defined($metaentry{':'.$unikey.'.default'})) {
8432: $metaentry{':'.$unikey}=
8433: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8434: }
8435: }
8436:
1.261 albertel 8437: sub metadata_generate_part0 {
8438: my ($metadata,$metacache,$uri) = @_;
8439: my %allnames;
1.737 albertel 8440: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8441: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8442: my $part=$$metacache{':'.$metakey.'.part'};
8443: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8444: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8445: $allnames{$name}=$part;
8446: }
8447: }
8448: }
8449: foreach my $name (keys(%allnames)) {
8450: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8451: my $key=":parameter_0_$name";
1.261 albertel 8452: $$metacache{"$key.part"}='0';
8453: $$metacache{"$key.name"}=$name;
1.428 albertel 8454: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8455: $allnames{$name}.'_'.$name.
8456: '.type'};
1.428 albertel 8457: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8458: '.display'};
1.644 www 8459: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8460: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8461: $$metacache{"$key.display"}=$olddis;
8462: }
1.71 www 8463: }
8464:
1.764 albertel 8465: # ------------------------------------------------------ Devalidate title cache
8466:
8467: sub devalidate_title_cache {
8468: my ($url)=@_;
8469: if (!$env{'request.course.id'}) { return; }
8470: my $symb=&symbread($url);
8471: if (!$symb) { return; }
8472: my $key=$env{'request.course.id'}."\0".$symb;
8473: &devalidate_cache_new('title',$key);
8474: }
8475:
1.1014 droeschl 8476: # ------------------------------------------------- Get the title of a course
8477:
8478: sub current_course_title {
8479: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8480: }
1.301 www 8481: # ------------------------------------------------- Get the title of a resource
8482:
8483: sub gettitle {
8484: my $urlsymb=shift;
8485: my $symb=&symbread($urlsymb);
1.534 albertel 8486: if ($symb) {
1.620 albertel 8487: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8488: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8489: if (defined($cached)) {
8490: return $result;
8491: }
1.534 albertel 8492: my ($map,$resid,$url)=&decode_symb($symb);
8493: my $title='';
1.907 albertel 8494: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8495: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8496: } else {
8497: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8498: &GDBM_READER(),0640)) {
8499: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8500: $title=$bighash{'title_'.$mapid.'.'.$resid};
8501: untie(%bighash);
8502: }
1.534 albertel 8503: }
8504: $title=~s/\&colon\;/\:/gs;
8505: if ($title) {
1.599 albertel 8506: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8507: }
8508: $urlsymb=$url;
8509: }
8510: my $title=&metadata($urlsymb,'title');
8511: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8512: return $title;
1.301 www 8513: }
1.613 albertel 8514:
1.614 albertel 8515: sub get_slot {
8516: my ($which,$cnum,$cdom)=@_;
8517: if (!$cnum || !$cdom) {
1.790 albertel 8518: (undef,my $courseid)=&whichuser();
1.620 albertel 8519: $cdom=$env{'course.'.$courseid.'.domain'};
8520: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8521: }
1.703 albertel 8522: my $key=join("\0",'slots',$cdom,$cnum,$which);
8523: my %slotinfo;
8524: if (exists($remembered{$key})) {
8525: $slotinfo{$which} = $remembered{$key};
8526: } else {
8527: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8528: &Apache::lonhomework::showhash(%slotinfo);
8529: my ($tmp)=keys(%slotinfo);
8530: if ($tmp=~/^error:/) { return (); }
8531: $remembered{$key} = $slotinfo{$which};
8532: }
1.616 albertel 8533: if (ref($slotinfo{$which}) eq 'HASH') {
8534: return %{$slotinfo{$which}};
8535: }
8536: return $slotinfo{$which};
1.614 albertel 8537: }
1.31 www 8538: # ------------------------------------------------- Update symbolic store links
8539:
8540: sub symblist {
8541: my ($mapname,%newhash)=@_;
1.438 www 8542: $mapname=&deversion(&declutter($mapname));
1.31 www 8543: my %hash;
1.620 albertel 8544: if (($env{'request.course.fn'}) && (%newhash)) {
8545: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8546: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8547: foreach my $url (keys(%newhash)) {
1.711 albertel 8548: next if ($url eq 'last_known'
8549: && $env{'form.no_update_last_known'});
8550: $hash{declutter($url)}=&encode_symb($mapname,
8551: $newhash{$url}->[1],
8552: $newhash{$url}->[0]);
1.191 harris41 8553: }
1.31 www 8554: if (untie(%hash)) {
8555: return 'ok';
8556: }
8557: }
8558: }
8559: return 'error';
1.212 www 8560: }
8561:
8562: # --------------------------------------------------------------- Verify a symb
8563:
8564: sub symbverify {
1.510 www 8565: my ($symb,$thisurl)=@_;
8566: my $thisfn=$thisurl;
1.439 www 8567: $thisfn=&declutter($thisfn);
1.215 www 8568: # direct jump to resource in page or to a sequence - will construct own symbs
8569: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8570: # check URL part
1.409 www 8571: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8572:
1.431 www 8573: unless ($url eq $thisfn) { return 0; }
1.213 www 8574:
1.216 www 8575: $symb=&symbclean($symb);
1.510 www 8576: $thisurl=&deversion($thisurl);
1.439 www 8577: $thisfn=&deversion($thisfn);
1.213 www 8578:
8579: my %bighash;
8580: my $okay=0;
1.431 www 8581:
1.620 albertel 8582: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8583: &GDBM_READER(),0640)) {
1.1032 raeburn 8584: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8585: $thisurl =~ s/\?.+$//;
8586: }
1.510 www 8587: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8588: unless ($ids) {
1.510 www 8589: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8590: }
8591: if ($ids) {
8592: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8593: foreach my $id (split(/\,/,$ids)) {
8594: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8595: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8596: $symb =~ s/\?.+$//;
8597: }
1.216 www 8598: if (
8599: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8600: eq $symb) {
1.620 albertel 8601: if (($env{'request.role.adv'}) ||
1.800 albertel 8602: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8603: $okay=1;
8604: }
8605: }
1.216 www 8606: }
8607: }
1.213 www 8608: untie(%bighash);
8609: }
8610: return $okay;
1.31 www 8611: }
8612:
1.210 www 8613: # --------------------------------------------------------------- Clean-up symb
8614:
8615: sub symbclean {
8616: my $symb=shift;
1.568 albertel 8617: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8618: # remove version from map
8619: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8620:
1.210 www 8621: # remove version from URL
8622: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8623:
1.507 www 8624: # remove wrapper
8625:
1.510 www 8626: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8627: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8628: return $symb;
1.409 www 8629: }
8630:
8631: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8632:
8633: sub encode_symb {
8634: my ($map,$resid,$url)=@_;
8635: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8636: }
1.409 www 8637:
8638: sub decode_symb {
1.568 albertel 8639: my $symb=shift;
8640: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8641: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8642: return (&fixversion($map),$resid,&fixversion($url));
8643: }
8644:
8645: sub fixversion {
8646: my $fn=shift;
1.609 banghart 8647: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8648: my %bighash;
8649: my $uri=&clutter($fn);
1.620 albertel 8650: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8651: # is this cached?
1.599 albertel 8652: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8653: if (defined($cached)) { return $result; }
8654: # unfortunately not cached, or expired
1.620 albertel 8655: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8656: &GDBM_READER(),0640)) {
8657: if ($bighash{'version_'.$uri}) {
8658: my $version=$bighash{'version_'.$uri};
1.444 www 8659: unless (($version eq 'mostrecent') ||
8660: ($version==&getversion($uri))) {
1.440 www 8661: $uri=~s/\.(\w+)$/\.$version\.$1/;
8662: }
8663: }
8664: untie %bighash;
1.413 www 8665: }
1.599 albertel 8666: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8667: }
8668:
8669: sub deversion {
8670: my $url=shift;
8671: $url=~s/\.\d+\.(\w+)$/\.$1/;
8672: return $url;
1.210 www 8673: }
8674:
1.31 www 8675: # ------------------------------------------------------ Return symb list entry
8676:
8677: sub symbread {
1.249 www 8678: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8679: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8680: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8681: # no filename provided? try from environment
1.44 www 8682: unless ($thisfn) {
1.620 albertel 8683: if ($env{'request.symb'}) {
8684: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8685: }
1.620 albertel 8686: $thisfn=$env{'request.filename'};
1.44 www 8687: }
1.569 albertel 8688: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8689: # is that filename actually a symb? Verify, clean, and return
8690: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8691: if (&symbverify($thisfn,$1)) {
1.620 albertel 8692: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8693: }
1.242 www 8694: }
1.44 www 8695: $thisfn=declutter($thisfn);
1.31 www 8696: my %hash;
1.37 www 8697: my %bighash;
8698: my $syval='';
1.620 albertel 8699: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8700: my $targetfn = $thisfn;
1.609 banghart 8701: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8702: $targetfn = 'adm/wrapper/'.$thisfn;
8703: }
1.687 albertel 8704: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8705: $targetfn=$1;
8706: }
1.620 albertel 8707: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8708: &GDBM_READER(),0640)) {
1.481 raeburn 8709: $syval=$hash{$targetfn};
1.37 www 8710: untie(%hash);
8711: }
8712: # ---------------------------------------------------------- There was an entry
8713: if ($syval) {
1.601 albertel 8714: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8715: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8716: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8717: #return $env{$cache_str}='';
1.601 albertel 8718: #}
8719: #$syval.=$1;
8720: #}
1.37 www 8721: } else {
8722: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8723: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8724: &GDBM_READER(),0640)) {
1.37 www 8725: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8726: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8727: unless ($ids) {
8728: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8729: }
8730: unless ($ids) {
8731: # alias?
8732: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8733: }
1.37 www 8734: if ($ids) {
8735: # ------------------------------------------------------------------- Has ID(s)
8736: my @possibilities=split(/\,/,$ids);
1.39 www 8737: if ($#possibilities==0) {
8738: # ----------------------------------------------- There is only one possibility
1.37 www 8739: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8740: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8741: $resid,$thisfn);
1.249 www 8742: } elsif (!$donotrecurse) {
1.39 www 8743: # ------------------------------------------ There is more than one possibility
8744: my $realpossible=0;
1.800 albertel 8745: foreach my $id (@possibilities) {
8746: my $file=$bighash{'src_'.$id};
1.39 www 8747: if (&allowed('bre',$file)) {
1.800 albertel 8748: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8749: if ($bighash{'map_type_'.$mapid} ne 'page') {
8750: $realpossible++;
1.626 albertel 8751: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8752: $resid,$thisfn);
1.39 www 8753: }
8754: }
1.191 harris41 8755: }
1.39 www 8756: if ($realpossible!=1) { $syval=''; }
1.249 www 8757: } else {
8758: $syval='';
1.37 www 8759: }
8760: }
8761: untie(%bighash)
1.481 raeburn 8762: }
1.31 www 8763: }
1.62 www 8764: if ($syval) {
1.620 albertel 8765: return $env{$cache_str}=$syval;
1.62 www 8766: }
1.31 www 8767: }
1.949 raeburn 8768: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8769: return $env{$cache_str}='';
1.31 www 8770: }
8771:
8772: # ---------------------------------------------------------- Return random seed
8773:
1.32 www 8774: sub numval {
8775: my $txt=shift;
8776: $txt=~tr/A-J/0-9/;
8777: $txt=~tr/a-j/0-9/;
8778: $txt=~tr/K-T/0-9/;
8779: $txt=~tr/k-t/0-9/;
8780: $txt=~tr/U-Z/0-5/;
8781: $txt=~tr/u-z/0-5/;
8782: $txt=~s/\D//g;
1.564 albertel 8783: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8784: return int($txt);
1.368 albertel 8785: }
8786:
1.484 albertel 8787: sub numval2 {
8788: my $txt=shift;
8789: $txt=~tr/A-J/0-9/;
8790: $txt=~tr/a-j/0-9/;
8791: $txt=~tr/K-T/0-9/;
8792: $txt=~tr/k-t/0-9/;
8793: $txt=~tr/U-Z/0-5/;
8794: $txt=~tr/u-z/0-5/;
8795: $txt=~s/\D//g;
8796: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8797: my $total;
8798: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8799: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 8800: return int($total);
8801: }
8802:
1.575 albertel 8803: sub numval3 {
8804: use integer;
8805: my $txt=shift;
8806: $txt=~tr/A-J/0-9/;
8807: $txt=~tr/a-j/0-9/;
8808: $txt=~tr/K-T/0-9/;
8809: $txt=~tr/k-t/0-9/;
8810: $txt=~tr/U-Z/0-5/;
8811: $txt=~tr/u-z/0-5/;
8812: $txt=~s/\D//g;
8813: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8814: my $total;
8815: foreach my $val (@txts) { $total+=$val; }
8816: if ($_64bit) { $total=(($total<<32)>>32); }
8817: return $total;
8818: }
8819:
1.675 albertel 8820: sub digest {
8821: my ($data)=@_;
8822: my $digest=&Digest::MD5::md5($data);
8823: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8824: my ($e,$f);
8825: {
8826: use integer;
8827: $e=($a+$b);
8828: $f=($c+$d);
8829: if ($_64bit) {
8830: $e=(($e<<32)>>32);
8831: $f=(($f<<32)>>32);
8832: }
8833: }
8834: if (wantarray) {
8835: return ($e,$f);
8836: } else {
8837: my $g;
8838: {
8839: use integer;
8840: $g=($e+$f);
8841: if ($_64bit) {
8842: $g=(($g<<32)>>32);
8843: }
8844: }
8845: return $g;
8846: }
8847: }
8848:
1.368 albertel 8849: sub latest_rnd_algorithm_id {
1.675 albertel 8850: return '64bit5';
1.366 albertel 8851: }
1.32 www 8852:
1.503 albertel 8853: sub get_rand_alg {
8854: my ($courseid)=@_;
1.790 albertel 8855: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 8856: if ($courseid) {
1.620 albertel 8857: return $env{"course.$courseid.rndseed"};
1.503 albertel 8858: }
8859: return &latest_rnd_algorithm_id();
8860: }
8861:
1.562 albertel 8862: sub validCODE {
8863: my ($CODE)=@_;
8864: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8865: return 0;
8866: }
8867:
1.491 albertel 8868: sub getCODE {
1.620 albertel 8869: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 8870: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8871: defined($Apache::lonhomework::parsing_a_task) ) &&
8872: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 8873: return $Apache::lonhomework::history{'resource.CODE'};
8874: }
8875: return undef;
8876: }
8877:
1.31 www 8878: sub rndseed {
1.155 albertel 8879: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8880: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8881: if (!defined($symb)) {
1.366 albertel 8882: unless ($symb=$wsymb) { return time; }
8883: }
8884: if (!$courseid) { $courseid=$wcourseid; }
8885: if (!$domain) { $domain=$wdomain; }
8886: if (!$username) { $username=$wusername }
1.503 albertel 8887: my $which=&get_rand_alg();
1.803 albertel 8888:
1.491 albertel 8889: if (defined(&getCODE())) {
1.675 albertel 8890: if ($which eq '64bit5') {
8891: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8892: } elsif ($which eq '64bit4') {
1.575 albertel 8893: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8894: } else {
8895: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8896: }
1.675 albertel 8897: } elsif ($which eq '64bit5') {
8898: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8899: } elsif ($which eq '64bit4') {
8900: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8901: } elsif ($which eq '64bit3') {
8902: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8903: } elsif ($which eq '64bit2') {
8904: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8905: } elsif ($which eq '64bit') {
8906: return &rndseed_64bit($symb,$courseid,$domain,$username);
8907: }
8908: return &rndseed_32bit($symb,$courseid,$domain,$username);
8909: }
8910:
8911: sub rndseed_32bit {
8912: my ($symb,$courseid,$domain,$username)=@_;
8913: {
8914: use integer;
8915: my $symbchck=unpack("%32C*",$symb) << 27;
8916: my $symbseed=numval($symb) << 22;
8917: my $namechck=unpack("%32C*",$username) << 17;
8918: my $nameseed=numval($username) << 12;
8919: my $domainseed=unpack("%32C*",$domain) << 7;
8920: my $courseseed=unpack("%32C*",$courseid);
8921: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8922: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8923: #&logthis("rndseed :$num:$symb");
1.564 albertel 8924: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8925: return $num;
8926: }
8927: }
8928:
8929: sub rndseed_64bit {
8930: my ($symb,$courseid,$domain,$username)=@_;
8931: {
8932: use integer;
8933: my $symbchck=unpack("%32S*",$symb) << 21;
8934: my $symbseed=numval($symb) << 10;
8935: my $namechck=unpack("%32S*",$username);
8936:
8937: my $nameseed=numval($username) << 21;
8938: my $domainseed=unpack("%32S*",$domain) << 10;
8939: my $courseseed=unpack("%32S*",$courseid);
8940:
8941: my $num1=$symbchck+$symbseed+$namechck;
8942: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8943: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8944: #&logthis("rndseed :$num:$symb");
1.564 albertel 8945: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8946: return "$num1,$num2";
1.155 albertel 8947: }
1.366 albertel 8948: }
8949:
1.443 albertel 8950: sub rndseed_64bit2 {
8951: my ($symb,$courseid,$domain,$username)=@_;
8952: {
8953: use integer;
8954: # strings need to be an even # of cahracters long, it it is odd the
8955: # last characters gets thrown away
8956: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8957: my $symbseed=numval($symb) << 10;
8958: my $namechck=unpack("%32S*",$username.' ');
8959:
8960: my $nameseed=numval($username) << 21;
1.501 albertel 8961: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8962: my $courseseed=unpack("%32S*",$courseid.' ');
8963:
8964: my $num1=$symbchck+$symbseed+$namechck;
8965: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8966: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8967: #&logthis("rndseed :$num:$symb");
1.803 albertel 8968: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8969: return "$num1,$num2";
8970: }
8971: }
8972:
8973: sub rndseed_64bit3 {
8974: my ($symb,$courseid,$domain,$username)=@_;
8975: {
8976: use integer;
8977: # strings need to be an even # of cahracters long, it it is odd the
8978: # last characters gets thrown away
8979: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8980: my $symbseed=numval2($symb) << 10;
8981: my $namechck=unpack("%32S*",$username.' ');
8982:
8983: my $nameseed=numval2($username) << 21;
1.443 albertel 8984: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8985: my $courseseed=unpack("%32S*",$courseid.' ');
8986:
8987: my $num1=$symbchck+$symbseed+$namechck;
8988: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8989: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8990: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8991: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8992:
1.503 albertel 8993: return "$num1:$num2";
1.443 albertel 8994: }
8995: }
8996:
1.575 albertel 8997: sub rndseed_64bit4 {
8998: my ($symb,$courseid,$domain,$username)=@_;
8999: {
9000: use integer;
9001: # strings need to be an even # of cahracters long, it it is odd the
9002: # last characters gets thrown away
9003: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9004: my $symbseed=numval3($symb) << 10;
9005: my $namechck=unpack("%32S*",$username.' ');
9006:
9007: my $nameseed=numval3($username) << 21;
9008: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9009: my $courseseed=unpack("%32S*",$courseid.' ');
9010:
9011: my $num1=$symbchck+$symbseed+$namechck;
9012: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9013: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9014: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9015: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9016:
9017: return "$num1:$num2";
9018: }
9019: }
9020:
1.675 albertel 9021: sub rndseed_64bit5 {
9022: my ($symb,$courseid,$domain,$username)=@_;
9023: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9024: return "$num1:$num2";
9025: }
9026:
1.366 albertel 9027: sub rndseed_CODE_64bit {
9028: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9029: {
1.366 albertel 9030: use integer;
1.443 albertel 9031: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9032: my $symbseed=numval2($symb);
1.491 albertel 9033: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9034: my $CODEseed=numval(&getCODE());
1.443 albertel 9035: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9036: my $num1=$symbseed+$CODEchck;
9037: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9038: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9039: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9040: if ($_64bit) { $num1=(($num1<<32)>>32); }
9041: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9042: return "$num1:$num2";
1.366 albertel 9043: }
9044: }
9045:
1.575 albertel 9046: sub rndseed_CODE_64bit4 {
9047: my ($symb,$courseid,$domain,$username)=@_;
9048: {
9049: use integer;
9050: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9051: my $symbseed=numval3($symb);
9052: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9053: my $CODEseed=numval3(&getCODE());
9054: my $courseseed=unpack("%32S*",$courseid.' ');
9055: my $num1=$symbseed+$CODEchck;
9056: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9057: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9058: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9059: if ($_64bit) { $num1=(($num1<<32)>>32); }
9060: if ($_64bit) { $num2=(($num2<<32)>>32); }
9061: return "$num1:$num2";
9062: }
9063: }
9064:
1.675 albertel 9065: sub rndseed_CODE_64bit5 {
9066: my ($symb,$courseid,$domain,$username)=@_;
9067: my $code = &getCODE();
9068: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9069: return "$num1:$num2";
9070: }
9071:
1.366 albertel 9072: sub setup_random_from_rndseed {
9073: my ($rndseed)=@_;
1.503 albertel 9074: if ($rndseed =~/([,:])/) {
9075: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9076: &Math::Random::random_set_seed(abs($num1),abs($num2));
9077: } else {
9078: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9079: }
1.36 albertel 9080: }
9081:
1.474 albertel 9082: sub latest_receipt_algorithm_id {
1.835 albertel 9083: return 'receipt3';
1.474 albertel 9084: }
9085:
1.480 www 9086: sub recunique {
9087: my $fucourseid=shift;
9088: my $unique;
1.835 albertel 9089: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9090: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9091: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9092: } else {
9093: $unique=$perlvar{'lonReceipt'};
9094: }
9095: return unpack("%32C*",$unique);
9096: }
9097:
9098: sub recprefix {
9099: my $fucourseid=shift;
9100: my $prefix;
1.835 albertel 9101: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9102: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9103: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9104: } else {
9105: $prefix=$perlvar{'lonHostID'};
9106: }
9107: return unpack("%32C*",$prefix);
9108: }
9109:
1.76 www 9110: sub ireceipt {
1.474 albertel 9111: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9112:
9113: my $return =&recprefix($fucourseid).'-';
9114:
9115: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9116: $env{'request.state'} eq 'construct') {
9117: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9118: return $return;
9119: }
9120:
1.76 www 9121: my $cuname=unpack("%32C*",$funame);
9122: my $cudom=unpack("%32C*",$fudom);
9123: my $cucourseid=unpack("%32C*",$fucourseid);
9124: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9125: my $cunique=&recunique($fucourseid);
1.474 albertel 9126: my $cpart=unpack("%32S*",$part);
1.835 albertel 9127: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9128:
1.790 albertel 9129: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9130:
9131: $return.= ($cunique%$cuname+
9132: $cunique%$cudom+
9133: $cusymb%$cuname+
9134: $cusymb%$cudom+
9135: $cucourseid%$cuname+
9136: $cucourseid%$cudom+
9137: $cpart%$cuname+
9138: $cpart%$cudom);
9139: } else {
9140: $return.= ($cunique%$cuname+
9141: $cunique%$cudom+
9142: $cusymb%$cuname+
9143: $cusymb%$cudom+
9144: $cucourseid%$cuname+
9145: $cucourseid%$cudom);
9146: }
9147: return $return;
1.76 www 9148: }
9149:
9150: sub receipt {
1.474 albertel 9151: my ($part)=@_;
1.790 albertel 9152: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9153: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9154: }
1.260 ng 9155:
1.790 albertel 9156: sub whichuser {
9157: my ($passedsymb)=@_;
9158: my ($symb,$courseid,$domain,$name,$publicuser);
9159: if (defined($env{'form.grade_symb'})) {
9160: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9161: my $allowed=&allowed('vgr',$tmp_courseid);
9162: if (!$allowed &&
9163: exists($env{'request.course.sec'}) &&
9164: $env{'request.course.sec'} !~ /^\s*$/) {
9165: $allowed=&allowed('vgr',$tmp_courseid.
9166: '/'.$env{'request.course.sec'});
9167: }
9168: if ($allowed) {
9169: ($symb)=&get_env_multiple('form.grade_symb');
9170: $courseid=$tmp_courseid;
9171: ($domain)=&get_env_multiple('form.grade_domain');
9172: ($name)=&get_env_multiple('form.grade_username');
9173: return ($symb,$courseid,$domain,$name,$publicuser);
9174: }
9175: }
9176: if (!$passedsymb) {
9177: $symb=&symbread();
9178: } else {
9179: $symb=$passedsymb;
9180: }
9181: $courseid=$env{'request.course.id'};
9182: $domain=$env{'user.domain'};
9183: $name=$env{'user.name'};
9184: if ($name eq 'public' && $domain eq 'public') {
9185: if (!defined($env{'form.username'})) {
9186: $env{'form.username'}.=time.rand(10000000);
9187: }
9188: $name.=$env{'form.username'};
9189: }
9190: return ($symb,$courseid,$domain,$name,$publicuser);
9191:
9192: }
9193:
1.36 albertel 9194: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9195: # returns either the contents of the file or
9196: # -1 if the file doesn't exist
1.481 raeburn 9197: #
9198: # if the target is a file that was uploaded via DOCS,
9199: # a check will be made to see if a current copy exists on the local server,
9200: # if it does this will be served, otherwise a copy will be retrieved from
9201: # the home server for the course and stored in /home/httpd/html/userfiles on
9202: # the local server.
1.472 albertel 9203:
1.36 albertel 9204: sub getfile {
1.538 albertel 9205: my ($file) = @_;
1.609 banghart 9206: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9207: &repcopy($file);
9208: return &readfile($file);
9209: }
9210:
9211: sub repcopy_userfile {
9212: my ($file)=@_;
1.609 banghart 9213: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9214: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9215: my ($cdom,$cnum,$filename) =
1.811 albertel 9216: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9217: my $uri="/uploaded/$cdom/$cnum/$filename";
9218: if (-e "$file") {
1.828 www 9219: # we already have a local copy, check it out
1.538 albertel 9220: my @fileinfo = stat($file);
1.828 www 9221: my $rtncode;
9222: my $info;
1.538 albertel 9223: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9224: if ($lwpresp ne 'ok') {
1.828 www 9225: # there is no such file anymore, even though we had a local copy
1.482 albertel 9226: if ($rtncode eq '404') {
1.538 albertel 9227: unlink($file);
1.482 albertel 9228: }
9229: return -1;
9230: }
9231: if ($info < $fileinfo[9]) {
1.828 www 9232: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9233: return 'ok';
1.828 www 9234: } else {
9235: # the file is outdated, get rid of it
9236: unlink($file);
1.482 albertel 9237: }
1.828 www 9238: }
9239: # one way or the other, at this point, we don't have the file
9240: # construct the correct path for the file
9241: my @parts = ($cdom,$cnum);
9242: if ($filename =~ m|^(.+)/[^/]+$|) {
9243: push @parts, split(/\//,$1);
9244: }
9245: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9246: foreach my $part (@parts) {
9247: $path .= '/'.$part;
9248: if (!-e $path) {
9249: mkdir($path,0770);
1.482 albertel 9250: }
9251: }
1.828 www 9252: # now the path exists for sure
9253: # get a user agent
9254: my $ua=new LWP::UserAgent;
9255: my $transferfile=$file.'.in.transfer';
9256: # FIXME: this should flock
9257: if (-e $transferfile) { return 'ok'; }
9258: my $request;
9259: $uri=~s/^\///;
1.980 raeburn 9260: my $homeserver = &homeserver($cnum,$cdom);
9261: my $protocol = $protocol{$homeserver};
9262: $protocol = 'http' if ($protocol ne 'https');
9263: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9264: my $response=$ua->request($request,$transferfile);
9265: # did it work?
9266: if ($response->is_error()) {
9267: unlink($transferfile);
9268: &logthis("Userfile repcopy failed for $uri");
9269: return -1;
9270: }
9271: # worked, rename the transfer file
9272: rename($transferfile,$file);
1.607 raeburn 9273: return 'ok';
1.481 raeburn 9274: }
9275:
1.517 albertel 9276: sub tokenwrapper {
9277: my $uri=shift;
1.980 raeburn 9278: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9279: $uri=~s|^/||;
1.620 albertel 9280: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9281: my $token=$1;
1.552 albertel 9282: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9283: if ($udom && $uname && $file) {
9284: $file=~s|(\?\.*)*$||;
1.949 raeburn 9285: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9286: my $homeserver = &homeserver($uname,$udom);
9287: my $protocol = $protocol{$homeserver};
9288: $protocol = 'http' if ($protocol ne 'https');
9289: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9290: (($uri=~/\?/)?'&':'?').'token='.$token.
9291: '&tokenissued='.$perlvar{'lonHostID'};
9292: } else {
9293: return '/adm/notfound.html';
9294: }
9295: }
9296:
1.828 www 9297: # call with reqtype HEAD: get last modification time
9298: # call with reqtype GET: get the file contents
9299: # Do not call this with reqtype GET for large files! It loads everything into memory
9300: #
1.481 raeburn 9301: sub getuploaded {
9302: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9303: $uri=~s/^\///;
1.980 raeburn 9304: my $homeserver = &homeserver($cnum,$cdom);
9305: my $protocol = $protocol{$homeserver};
9306: $protocol = 'http' if ($protocol ne 'https');
9307: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9308: my $ua=new LWP::UserAgent;
9309: my $request=new HTTP::Request($reqtype,$uri);
9310: my $response=$ua->request($request);
9311: $$rtncode = $response->code;
1.482 albertel 9312: if (! $response->is_success()) {
9313: return 'failed';
9314: }
9315: if ($reqtype eq 'HEAD') {
1.486 www 9316: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9317: } elsif ($reqtype eq 'GET') {
9318: $$info = $response->content;
1.472 albertel 9319: }
1.482 albertel 9320: return 'ok';
1.36 albertel 9321: }
9322:
1.481 raeburn 9323: sub readfile {
9324: my $file = shift;
9325: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9326: my $fh;
9327: open($fh,"<$file");
9328: my $a='';
1.800 albertel 9329: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9330: return $a;
9331: }
9332:
1.36 albertel 9333: sub filelocation {
1.590 banghart 9334: my ($dir,$file) = @_;
9335: my $location;
9336: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9337:
9338: if ($file =~ m-^/adm/-) {
9339: $file=~s-^/adm/wrapper/-/-;
9340: $file=~s-^/adm/coursedocs/showdoc/-/-;
9341: }
1.882 albertel 9342:
1.590 banghart 9343: if ($file=~m:^/~:) { # is a contruction space reference
9344: $location = $file;
9345: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9346: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9347: # is a correct contruction space reference
9348: $location = $file;
1.956 raeburn 9349: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9350: $location = $file;
1.609 banghart 9351: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9352: my ($udom,$uname,$filename)=
1.811 albertel 9353: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9354: my $home=&homeserver($uname,$udom);
9355: my $is_me=0;
9356: my @ids=¤t_machine_ids();
9357: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9358: if ($is_me) {
1.955 raeburn 9359: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9360: } else {
9361: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9362: $udom.'/'.$uname.'/'.$filename;
9363: }
1.882 albertel 9364: } elsif ($file =~ m-^/adm/-) {
9365: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9366: } else {
9367: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9368: $file=~s:^/res/:/:;
9369: if ( !( $file =~ m:^/:) ) {
9370: $location = $dir. '/'.$file;
9371: } else {
9372: $location = '/home/httpd/html/res'.$file;
9373: }
1.59 albertel 9374: }
1.590 banghart 9375: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9376: while ($location=~m{/\.\./}) {
9377: if ($location =~ m{/[^/]+/\.\./}) {
9378: $location=~ s{/[^/]+/\.\./}{/}g;
9379: } else {
9380: $location=~ s{/\.\./}{/}g;
9381: }
9382: } #remove dir/..
1.590 banghart 9383: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9384: return $location;
1.46 www 9385: }
1.36 albertel 9386:
1.46 www 9387: sub hreflocation {
9388: my ($dir,$file)=@_;
1.980 raeburn 9389: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9390: $file=filelocation($dir,$file);
1.700 albertel 9391: } elsif ($file=~m-^/adm/-) {
9392: $file=~s-^/adm/wrapper/-/-;
9393: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9394: }
9395: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9396: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9397: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9398: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9399: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9400: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9401: -/uploaded/$1/$2/-x;
1.46 www 9402: }
1.913 albertel 9403: if ($file=~ m{^/userfiles/}) {
9404: $file =~ s{^/userfiles/}{/uploaded/};
9405: }
1.462 albertel 9406: return $file;
1.465 albertel 9407: }
9408:
9409: sub current_machine_domains {
1.853 albertel 9410: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9411: }
9412:
9413: sub machine_domains {
9414: my ($hostname) = @_;
1.465 albertel 9415: my @domains;
1.838 albertel 9416: my %hostname = &all_hostnames();
1.465 albertel 9417: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9418: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9419: if ($hostname eq $name) {
1.844 albertel 9420: push(@domains,&host_domain($id));
1.465 albertel 9421: }
9422: }
9423: return @domains;
9424: }
9425:
9426: sub current_machine_ids {
1.853 albertel 9427: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9428: }
9429:
9430: sub machine_ids {
9431: my ($hostname) = @_;
9432: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9433: my @ids;
1.888 albertel 9434: my %name_to_host = &all_names();
1.889 albertel 9435: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9436: return @{ $name_to_host{$hostname} };
9437: }
9438: return;
1.31 www 9439: }
9440:
1.824 raeburn 9441: sub additional_machine_domains {
9442: my @domains;
9443: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9444: while( my $line = <$fh>) {
9445: $line =~ s/\s//g;
9446: push(@domains,$line);
9447: }
9448: return @domains;
9449: }
9450:
9451: sub default_login_domain {
9452: my $domain = $perlvar{'lonDefDomain'};
9453: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9454: foreach my $posdom (¤t_machine_domains(),
9455: &additional_machine_domains()) {
9456: if (lc($posdom) eq lc($testdomain)) {
9457: $domain=$posdom;
9458: last;
9459: }
9460: }
9461: return $domain;
9462: }
9463:
1.31 www 9464: # ------------------------------------------------------------- Declutters URLs
9465:
9466: sub declutter {
9467: my $thisfn=shift;
1.569 albertel 9468: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9469: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9470: $thisfn=~s/^\///;
1.697 albertel 9471: $thisfn=~s|^adm/wrapper/||;
9472: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9473: $thisfn=~s/^res\///;
1.1032 raeburn 9474: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9475: $thisfn=~s/\?.+$//;
9476: }
1.268 www 9477: return $thisfn;
9478: }
9479:
9480: # ------------------------------------------------------------- Clutter up URLs
9481:
9482: sub clutter {
9483: my $thisfn='/'.&declutter(shift);
1.887 albertel 9484: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9485: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9486: $thisfn='/res'.$thisfn;
9487: }
1.1031 raeburn 9488: if ($thisfn !~m|^/adm|) {
9489: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9490: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9491: } else {
9492: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9493: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9494: if ($embstyle eq 'ssi'
9495: || ($embstyle eq 'hdn')
9496: || ($embstyle eq 'rat')
9497: || ($embstyle eq 'prv')
9498: || ($embstyle eq 'ign')) {
9499: #do nothing with these
9500: } elsif (($embstyle eq 'img')
1.695 albertel 9501: || ($embstyle eq 'emb')
9502: || ($embstyle eq 'wrp')) {
9503: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9504: } elsif ($embstyle eq 'unk'
9505: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9506: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9507: } else {
1.718 www 9508: # &logthis("Got a blank emb style");
1.695 albertel 9509: }
1.694 albertel 9510: }
9511: }
1.31 www 9512: return $thisfn;
1.12 www 9513: }
9514:
1.787 albertel 9515: sub clutter_with_no_wrapper {
9516: my $uri = &clutter(shift);
9517: if ($uri =~ m-^/adm/-) {
9518: $uri =~ s-^/adm/wrapper/-/-;
9519: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9520: }
9521: return $uri;
9522: }
9523:
1.557 albertel 9524: sub freeze_escape {
9525: my ($value)=@_;
9526: if (ref($value)) {
9527: $value=&nfreeze($value);
9528: return '__FROZEN__'.&escape($value);
9529: }
9530: return &escape($value);
9531: }
9532:
1.11 www 9533:
1.557 albertel 9534: sub thaw_unescape {
9535: my ($value)=@_;
9536: if ($value =~ /^__FROZEN__/) {
9537: substr($value,0,10,undef);
9538: $value=&unescape($value);
9539: return &thaw($value);
9540: }
9541: return &unescape($value);
9542: }
9543:
1.436 albertel 9544: sub correct_line_ends {
9545: my ($result)=@_;
9546: $$result =~s/\r\n/\n/mg;
9547: $$result =~s/\r/\n/mg;
1.415 albertel 9548: }
1.1 albertel 9549: # ================================================================ Main Program
9550:
1.184 www 9551: sub goodbye {
1.204 albertel 9552: &logthis("Starting Shut down");
1.443 albertel 9553: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9554: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9555: #converted
1.599 albertel 9556: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9557: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9558: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9559: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9560: #1.1 only
1.870 albertel 9561: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9562: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9563: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9564: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9565: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9566: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9567: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9568: &flushcourselogs();
9569: &logthis("Shutting down");
9570: }
9571:
1.852 albertel 9572: sub get_dns {
1.869 albertel 9573: my ($url,$func,$ignore_cache) = @_;
9574: if (!$ignore_cache) {
9575: my ($content,$cached)=
9576: &Apache::lonnet::is_cached_new('dns',$url);
9577: if ($cached) {
9578: &$func($content);
9579: return;
9580: }
9581: }
9582:
9583: my %alldns;
1.852 albertel 9584: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9585: foreach my $dns (<$config>) {
9586: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9587: my $line = $1;
9588: my ($host,$protocol) = split(/:/,$line);
9589: if ($protocol ne 'https') {
9590: $protocol = 'http';
9591: }
9592: $alldns{$host} = $protocol;
1.869 albertel 9593: }
9594: while (%alldns) {
9595: my ($dns) = keys(%alldns);
1.852 albertel 9596: my $ua=new LWP::UserAgent;
1.979 raeburn 9597: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9598: my $response=$ua->request($request);
1.979 raeburn 9599: delete($alldns{$dns});
1.852 albertel 9600: next if ($response->is_error());
9601: my @content = split("\n",$response->content);
1.869 albertel 9602: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9603: &$func(\@content);
1.869 albertel 9604: return;
1.852 albertel 9605: }
9606: close($config);
1.871 albertel 9607: my $which = (split('/',$url))[3];
9608: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9609: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9610: my @content = <$config>;
9611: &$func(\@content);
9612: return;
1.852 albertel 9613: }
1.327 albertel 9614: # ------------------------------------------------------------ Read domain file
9615: {
1.852 albertel 9616: my $loaded;
1.846 albertel 9617: my %domain;
9618:
1.852 albertel 9619: sub parse_domain_tab {
9620: my ($lines) = @_;
9621: foreach my $line (@$lines) {
9622: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9623:
1.846 albertel 9624: chomp($line);
1.852 albertel 9625: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9626: my %this_domain;
9627: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9628: 'lang_def', 'city', 'longi', 'lati',
9629: 'primary') {
9630: $this_domain{$field} = shift(@elements);
9631: }
9632: $domain{$name} = \%this_domain;
1.852 albertel 9633: }
9634: }
1.864 albertel 9635:
9636: sub reset_domain_info {
9637: undef($loaded);
9638: undef(%domain);
9639: }
9640:
1.852 albertel 9641: sub load_domain_tab {
1.869 albertel 9642: my ($ignore_cache) = @_;
9643: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9644: my $fh;
9645: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9646: my @lines = <$fh>;
9647: &parse_domain_tab(\@lines);
1.448 albertel 9648: }
1.852 albertel 9649: close($fh);
9650: $loaded = 1;
1.327 albertel 9651: }
1.846 albertel 9652:
9653: sub domain {
1.852 albertel 9654: &load_domain_tab() if (!$loaded);
9655:
1.846 albertel 9656: my ($name,$what) = @_;
9657: return if ( !exists($domain{$name}) );
9658:
9659: if (!$what) {
9660: return $domain{$name}{'description'};
9661: }
9662: return $domain{$name}{$what};
9663: }
1.974 raeburn 9664:
9665: sub domain_info {
9666: &load_domain_tab() if (!$loaded);
9667: return %domain;
9668: }
9669:
1.327 albertel 9670: }
9671:
9672:
1.1 albertel 9673: # ------------------------------------------------------------- Read hosts file
9674: {
1.838 albertel 9675: my %hostname;
1.844 albertel 9676: my %hostdom;
1.845 albertel 9677: my %libserv;
1.852 albertel 9678: my $loaded;
1.888 albertel 9679: my %name_to_host;
1.852 albertel 9680:
9681: sub parse_hosts_tab {
9682: my ($file) = @_;
9683: foreach my $configline (@$file) {
9684: next if ($configline =~ /^(\#|\s*$ )/x);
9685: next if ($configline =~ /^\^/);
9686: chomp($configline);
1.968 raeburn 9687: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 9688: $name=~s/\s//g;
9689: if ($id && $domain && $role && $name) {
9690: $hostname{$id}=$name;
1.888 albertel 9691: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9692: $hostdom{$id}=$domain;
9693: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9694: if (defined($protocol)) {
9695: if ($protocol eq 'https') {
9696: $protocol{$id} = $protocol;
9697: } else {
9698: $protocol{$id} = 'http';
9699: }
1.968 raeburn 9700: } else {
1.969 raeburn 9701: $protocol{$id} = 'http';
1.968 raeburn 9702: }
1.852 albertel 9703: }
9704: }
9705: }
1.864 albertel 9706:
9707: sub reset_hosts_info {
1.897 albertel 9708: &purge_remembered();
1.864 albertel 9709: &reset_domain_info();
9710: &reset_hosts_ip_info();
1.892 albertel 9711: undef(%name_to_host);
1.864 albertel 9712: undef(%hostname);
9713: undef(%hostdom);
9714: undef(%libserv);
9715: undef($loaded);
9716: }
1.1 albertel 9717:
1.852 albertel 9718: sub load_hosts_tab {
1.869 albertel 9719: my ($ignore_cache) = @_;
9720: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9721: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9722: my @config = <$config>;
9723: &parse_hosts_tab(\@config);
9724: close($config);
9725: $loaded=1;
1.1 albertel 9726: }
1.852 albertel 9727:
1.838 albertel 9728: sub hostname {
1.852 albertel 9729: &load_hosts_tab() if (!$loaded);
9730:
1.838 albertel 9731: my ($lonid) = @_;
9732: return $hostname{$lonid};
9733: }
1.845 albertel 9734:
1.838 albertel 9735: sub all_hostnames {
1.852 albertel 9736: &load_hosts_tab() if (!$loaded);
9737:
1.838 albertel 9738: return %hostname;
9739: }
1.845 albertel 9740:
1.888 albertel 9741: sub all_names {
9742: &load_hosts_tab() if (!$loaded);
9743:
9744: return %name_to_host;
9745: }
9746:
1.974 raeburn 9747: sub all_host_domain {
9748: &load_hosts_tab() if (!$loaded);
9749: return %hostdom;
9750: }
9751:
1.845 albertel 9752: sub is_library {
1.852 albertel 9753: &load_hosts_tab() if (!$loaded);
9754:
1.845 albertel 9755: return exists($libserv{$_[0]});
9756: }
9757:
9758: sub all_library {
1.852 albertel 9759: &load_hosts_tab() if (!$loaded);
9760:
1.845 albertel 9761: return %libserv;
9762: }
9763:
1.1062 droeschl 9764: sub unique_library {
9765: #2x reverse removes all hostnames that appear more than once
9766: my %unique = reverse &all_library();
9767: return reverse %unique;
9768: }
9769:
1.841 albertel 9770: sub get_servers {
1.852 albertel 9771: &load_hosts_tab() if (!$loaded);
9772:
1.841 albertel 9773: my ($domain,$type) = @_;
9774: my %possible_hosts = ($type eq 'library') ? %libserv
9775: : %hostname;
9776: my %result;
1.842 albertel 9777: if (ref($domain) eq 'ARRAY') {
9778: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9779: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9780: $result{$host} = $hostname;
9781: }
9782: }
9783: } else {
9784: while ( my ($host,$hostname) = each(%possible_hosts)) {
9785: if ($hostdom{$host} eq $domain) {
9786: $result{$host} = $hostname;
9787: }
1.841 albertel 9788: }
9789: }
9790: return %result;
9791: }
1.845 albertel 9792:
1.1062 droeschl 9793: sub get_unique_servers {
9794: my %unique = reverse &get_servers(@_);
9795: return reverse %unique;
9796: }
9797:
1.844 albertel 9798: sub host_domain {
1.852 albertel 9799: &load_hosts_tab() if (!$loaded);
9800:
1.844 albertel 9801: my ($lonid) = @_;
9802: return $hostdom{$lonid};
9803: }
9804:
1.841 albertel 9805: sub all_domains {
1.852 albertel 9806: &load_hosts_tab() if (!$loaded);
9807:
1.841 albertel 9808: my %seen;
9809: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9810: return @uniq;
9811: }
1.1 albertel 9812: }
9813:
1.847 albertel 9814: {
9815: my %iphost;
1.856 albertel 9816: my %name_to_ip;
9817: my %lonid_to_ip;
1.869 albertel 9818:
1.847 albertel 9819: sub get_hosts_from_ip {
9820: my ($ip) = @_;
9821: my %iphosts = &get_iphost();
9822: if (ref($iphosts{$ip})) {
9823: return @{$iphosts{$ip}};
9824: }
9825: return;
1.839 albertel 9826: }
1.864 albertel 9827:
9828: sub reset_hosts_ip_info {
9829: undef(%iphost);
9830: undef(%name_to_ip);
9831: undef(%lonid_to_ip);
9832: }
1.856 albertel 9833:
9834: sub get_host_ip {
9835: my ($lonid) = @_;
9836: if (exists($lonid_to_ip{$lonid})) {
9837: return $lonid_to_ip{$lonid};
9838: }
9839: my $name=&hostname($lonid);
9840: my $ip = gethostbyname($name);
9841: return if (!$ip || length($ip) ne 4);
9842: $ip=inet_ntoa($ip);
9843: $name_to_ip{$name} = $ip;
9844: $lonid_to_ip{$lonid} = $ip;
9845: return $ip;
9846: }
1.847 albertel 9847:
9848: sub get_iphost {
1.869 albertel 9849: my ($ignore_cache) = @_;
1.894 albertel 9850:
1.869 albertel 9851: if (!$ignore_cache) {
9852: if (%iphost) {
9853: return %iphost;
9854: }
9855: my ($ip_info,$cached)=
9856: &Apache::lonnet::is_cached_new('iphost','iphost');
9857: if ($cached) {
9858: %iphost = %{$ip_info->[0]};
9859: %name_to_ip = %{$ip_info->[1]};
9860: %lonid_to_ip = %{$ip_info->[2]};
9861: return %iphost;
9862: }
9863: }
1.894 albertel 9864:
9865: # get yesterday's info for fallback
9866: my %old_name_to_ip;
9867: my ($ip_info,$cached)=
9868: &Apache::lonnet::is_cached_new('iphost','iphost');
9869: if ($cached) {
9870: %old_name_to_ip = %{$ip_info->[1]};
9871: }
9872:
1.888 albertel 9873: my %name_to_host = &all_names();
9874: foreach my $name (keys(%name_to_host)) {
1.847 albertel 9875: my $ip;
9876: if (!exists($name_to_ip{$name})) {
9877: $ip = gethostbyname($name);
9878: if (!$ip || length($ip) ne 4) {
1.894 albertel 9879: if (defined($old_name_to_ip{$name})) {
9880: $ip = $old_name_to_ip{$name};
9881: &logthis("Can't find $name defaulting to old $ip");
9882: } else {
9883: &logthis("Name $name no IP found");
9884: next;
9885: }
9886: } else {
9887: $ip=inet_ntoa($ip);
1.847 albertel 9888: }
9889: $name_to_ip{$name} = $ip;
9890: } else {
9891: $ip = $name_to_ip{$name};
1.653 albertel 9892: }
1.888 albertel 9893: foreach my $id (@{ $name_to_host{$name} }) {
9894: $lonid_to_ip{$id} = $ip;
9895: }
9896: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9897: }
1.869 albertel 9898: &Apache::lonnet::do_cache_new('iphost','iphost',
9899: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9900: 48*60*60);
1.869 albertel 9901:
1.847 albertel 9902: return %iphost;
1.598 albertel 9903: }
9904:
1.992 raeburn 9905: #
9906: # Given a DNS returns the loncapa host name for that DNS
9907: #
9908: sub host_from_dns {
9909: my ($dns) = @_;
9910: my @hosts;
9911: my $ip;
9912:
1.993 raeburn 9913: if (exists($name_to_ip{$dns})) {
1.992 raeburn 9914: $ip = $name_to_ip{$dns};
9915: }
9916: if (!$ip) {
9917: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9918: if (length($ip) == 4) {
9919: $ip = &IO::Socket::inet_ntoa($ip);
9920: }
9921: }
9922: if ($ip) {
9923: @hosts = get_hosts_from_ip($ip);
9924: return $hosts[0];
9925: }
9926: return undef;
1.986 foxr 9927: }
1.992 raeburn 9928:
1.986 foxr 9929: }
9930:
1.862 albertel 9931: BEGIN {
9932:
9933: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9934: unless ($readit) {
9935: {
9936: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9937: %perlvar = (%perlvar,%{$configvars});
9938: }
9939:
9940:
1.1 albertel 9941: # ------------------------------------------------------ Read spare server file
9942: {
1.448 albertel 9943: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9944:
9945: while (my $configline=<$config>) {
9946: chomp($configline);
1.284 matthew 9947: if ($configline) {
1.784 albertel 9948: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9949: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9950: push(@{ $spareid{$type} }, $host);
1.1 albertel 9951: }
9952: }
1.448 albertel 9953: close($config);
1.1 albertel 9954: }
1.11 www 9955: # ------------------------------------------------------------ Read permissions
9956: {
1.448 albertel 9957: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9958:
9959: while (my $configline=<$config>) {
1.448 albertel 9960: chomp($configline);
9961: if ($configline) {
9962: my ($role,$perm)=split(/ /,$configline);
9963: if ($perm ne '') { $pr{$role}=$perm; }
9964: }
1.11 www 9965: }
1.448 albertel 9966: close($config);
1.11 www 9967: }
9968:
9969: # -------------------------------------------- Read plain texts for permissions
9970: {
1.448 albertel 9971: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9972:
9973: while (my $configline=<$config>) {
1.448 albertel 9974: chomp($configline);
9975: if ($configline) {
1.742 raeburn 9976: my ($short,@plain)=split(/:/,$configline);
9977: %{$prp{$short}} = ();
9978: if (@plain > 0) {
9979: $prp{$short}{'std'} = $plain[0];
9980: for (my $i=1; $i<@plain; $i++) {
9981: $prp{$short}{'alt'.$i} = $plain[$i];
9982: }
9983: }
1.448 albertel 9984: }
1.135 www 9985: }
1.448 albertel 9986: close($config);
1.135 www 9987: }
9988:
9989: # ---------------------------------------------------------- Read package table
9990: {
1.448 albertel 9991: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9992:
9993: while (my $configline=<$config>) {
1.483 albertel 9994: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9995: chomp($configline);
9996: my ($short,$plain)=split(/:/,$configline);
9997: my ($pack,$name)=split(/\&/,$short);
9998: if ($plain ne '') {
9999: $packagetab{$pack.'&'.$name.'&name'}=$name;
10000: $packagetab{$short}=$plain;
10001: }
1.11 www 10002: }
1.448 albertel 10003: close($config);
1.329 matthew 10004: }
10005:
10006: # ------------- set up temporary directory
10007: {
10008: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10009:
1.11 www 10010: }
10011:
1.794 albertel 10012: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10013: 'compress_threshold'=> 20_000,
10014: });
1.185 www 10015:
1.281 www 10016: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10017: $dumpcount=0;
1.958 www 10018: $locknum=0;
1.22 www 10019:
1.163 harris41 10020: &logtouch();
1.672 albertel 10021: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10022: $readit=1;
1.564 albertel 10023: {
10024: use integer;
10025: my $test=(2**32)+1;
1.568 albertel 10026: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10027: &logthis(" Detected 64bit platform ($_64bit)");
10028: }
1.195 www 10029: }
1.1 albertel 10030: }
1.179 www 10031:
1.1 albertel 10032: 1;
1.191 harris41 10033: __END__
10034:
1.243 albertel 10035: =pod
10036:
1.191 harris41 10037: =head1 NAME
10038:
1.243 albertel 10039: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10040:
10041: =head1 SYNOPSIS
10042:
1.243 albertel 10043: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10044:
10045: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10046:
1.243 albertel 10047: Common parameters:
10048:
10049: =over 4
10050:
10051: =item *
10052:
10053: $uname : an internal username (if $cname expecting a course Id specifically)
10054:
10055: =item *
10056:
10057: $udom : a domain (if $cdom expecting a course's domain specifically)
10058:
10059: =item *
10060:
10061: $symb : a resource instance identifier
10062:
10063: =item *
10064:
10065: $namespace : the name of a .db file that contains the data needed or
10066: being set.
10067:
10068: =back
10069:
1.394 bowersj2 10070: =head1 OVERVIEW
1.191 harris41 10071:
1.394 bowersj2 10072: lonnet provides subroutines which interact with the
10073: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10074: about classes, users, and resources.
1.243 albertel 10075:
10076: For many of these objects you can also use this to store data about
10077: them or modify them in various ways.
1.191 harris41 10078:
1.394 bowersj2 10079: =head2 Symbs
1.191 harris41 10080:
1.394 bowersj2 10081: To identify a specific instance of a resource, LON-CAPA uses symbols
10082: or "symbs"X<symb>. These identifiers are built from the URL of the
10083: map, the resource number of the resource in the map, and the URL of
10084: the resource itself. The latter is somewhat redundant, but might help
10085: if maps change.
10086:
10087: An example is
10088:
10089: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10090:
10091: The respective map entry is
10092:
10093: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10094: title="Problem 2">
10095: </resource>
10096:
10097: Symbs are used by the random number generator, as well as to store and
10098: restore data specific to a certain instance of for example a problem.
10099:
10100: =head2 Storing And Retrieving Data
10101:
10102: X<store()>X<cstore()>X<restore()>Three of the most important functions
10103: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10104: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10105: is is the non-critical message twin of cstore. These functions are for
10106: handlers to store a perl hash to a user's permanent data space in an
10107: easy manner, and to retrieve it again on another call. It is expected
10108: that a handler would use this once at the beginning to retrieve data,
10109: and then again once at the end to send only the new data back.
10110:
10111: The data is stored in the user's data directory on the user's
10112: homeserver under the ID of the course.
10113:
10114: The hash that is returned by restore will have all of the previous
10115: value for all of the elements of the hash.
10116:
10117: Example:
10118:
10119: #creating a hash
10120: my %hash;
10121: $hash{'foo'}='bar';
10122:
10123: #storing it
10124: &Apache::lonnet::cstore(\%hash);
10125:
10126: #changing a value
10127: $hash{'foo'}='notbar';
10128:
10129: #adding a new value
10130: $hash{'bar'}='foo';
10131: &Apache::lonnet::cstore(\%hash);
10132:
10133: #retrieving the hash
10134: my %history=&Apache::lonnet::restore();
10135:
10136: #print the hash
10137: foreach my $key (sort(keys(%history))) {
10138: print("\%history{$key} = $history{$key}");
10139: }
10140:
10141: Will print out:
1.191 harris41 10142:
1.394 bowersj2 10143: %history{1:foo} = bar
10144: %history{1:keys} = foo:timestamp
10145: %history{1:timestamp} = 990455579
10146: %history{2:bar} = foo
10147: %history{2:foo} = notbar
10148: %history{2:keys} = foo:bar:timestamp
10149: %history{2:timestamp} = 990455580
10150: %history{bar} = foo
10151: %history{foo} = notbar
10152: %history{timestamp} = 990455580
10153: %history{version} = 2
10154:
10155: Note that the special hash entries C<keys>, C<version> and
10156: C<timestamp> were added to the hash. C<version> will be equal to the
10157: total number of versions of the data that have been stored. The
10158: C<timestamp> attribute will be the UNIX time the hash was
10159: stored. C<keys> is available in every historical section to list which
10160: keys were added or changed at a specific historical revision of a
10161: hash.
10162:
10163: B<Warning>: do not store the hash that restore returns directly. This
10164: will cause a mess since it will restore the historical keys as if the
10165: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10166:
1.394 bowersj2 10167: Calling convention:
1.191 harris41 10168:
1.394 bowersj2 10169: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10170: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10171:
1.394 bowersj2 10172: For more detailed information, see lonnet specific documentation.
1.191 harris41 10173:
1.394 bowersj2 10174: =head1 RETURN MESSAGES
1.191 harris41 10175:
1.394 bowersj2 10176: =over 4
1.191 harris41 10177:
1.394 bowersj2 10178: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10179:
1.394 bowersj2 10180: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10181: when the connection is brought back up
1.191 harris41 10182:
1.394 bowersj2 10183: =item * B<con_failed>: unable to contact remote host and unable to save message
10184: for later delivery
1.191 harris41 10185:
1.967 bisitz 10186: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10187:
1.394 bowersj2 10188: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10189: that was requested
1.191 harris41 10190:
1.243 albertel 10191: =back
1.191 harris41 10192:
1.243 albertel 10193: =head1 PUBLIC SUBROUTINES
1.191 harris41 10194:
1.243 albertel 10195: =head2 Session Environment Functions
1.191 harris41 10196:
1.243 albertel 10197: =over 4
1.191 harris41 10198:
1.394 bowersj2 10199: =item *
10200: X<appenv()>
1.949 raeburn 10201: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10202: the user envirnoment file, and will be restored for each access this
1.620 albertel 10203: user makes during this session, also modifies the %env for the current
1.949 raeburn 10204: process. Optional rolesarrayref - if defined contains a reference to an array
10205: of roles which are exempt from the restriction on modifying user.role entries
10206: in the user's environment.db and in %env.
1.191 harris41 10207:
10208: =item *
1.394 bowersj2 10209: X<delenv()>
1.987 raeburn 10210: B<delenv($delthis,$regexp)>: removes all items from the session
10211: environment file that begin with $delthis. If the
10212: optional second arg - $regexp - is true, $delthis is treated as a
10213: regular expression, otherwise \Q$delthis\E is used.
10214: The values are also deleted from the current processes %env.
1.191 harris41 10215:
1.795 albertel 10216: =item * get_env_multiple($name)
10217:
10218: gets $name from the %env hash, it seemlessly handles the cases where multiple
10219: values may be defined and end up as an array ref.
10220:
10221: returns an array of values
10222:
1.243 albertel 10223: =back
10224:
10225: =head2 User Information
1.191 harris41 10226:
1.243 albertel 10227: =over 4
1.191 harris41 10228:
10229: =item *
1.394 bowersj2 10230: X<queryauthenticate()>
10231: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10232: authentication scheme
10233:
10234: =item *
1.394 bowersj2 10235: X<authenticate()>
10236: B<authenticate($uname,$upass,$udom)>: try to
10237: authenticate user from domain's lib servers (first use the current
10238: one). C<$upass> should be the users password.
1.191 harris41 10239:
10240: =item *
1.394 bowersj2 10241: X<homeserver()>
10242: B<homeserver($uname,$udom)>: find the server which has
10243: the user's directory and files (there must be only one), this caches
10244: the answer, and also caches if there is a borken connection.
1.191 harris41 10245:
10246: =item *
1.394 bowersj2 10247: X<idget()>
10248: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10249: (IDs are a unique resource in a domain, there must be only 1 ID per
10250: username, and only 1 username per ID in a specific domain) (returns
10251: hash: id=>name,id=>name)
1.191 harris41 10252:
10253: =item *
1.394 bowersj2 10254: X<idrget()>
10255: B<idrget($udom,@unames)>: find the IDs behind a list of
10256: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10257:
10258: =item *
1.394 bowersj2 10259: X<idput()>
10260: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10261:
10262: =item *
1.394 bowersj2 10263: X<rolesinit()>
10264: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10265:
10266: =item *
1.551 albertel 10267: X<getsection()>
10268: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10269: course $cname, return section name/number or '' for "not in course"
10270: and '-1' for "no section"
10271:
10272: =item *
1.394 bowersj2 10273: X<userenvironment()>
10274: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10275: passed in @what from the requested user's environment, returns a hash
10276:
1.858 raeburn 10277: =item *
10278: X<userlog_query()>
1.859 albertel 10279: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10280: activity.log file. %filters defines filters applied when parsing the
10281: log file. These can be start or end timestamps, or the type of action
10282: - log to look for Login or Logout events, check for Checkin or
10283: Checkout, role for role selection. The response is in the form
10284: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10285: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10286:
1.243 albertel 10287: =back
10288:
10289: =head2 User Roles
10290:
10291: =over 4
10292:
10293: =item *
10294:
1.810 raeburn 10295: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10296: F: full access
10297: U,I,K: authentication modes (cxx only)
10298: '': forbidden
10299: 1: user needs to choose course
10300: 2: browse allowed
1.766 albertel 10301: A: passphrase authentication needed
1.243 albertel 10302:
10303: =item *
10304:
10305: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10306: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10307: and course level
10308:
10309: =item *
10310:
1.988 raeburn 10311: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10312: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10313: $type is Course (default) or Community.
1.988 raeburn 10314: If $forcedefault evaluates to true, text returned will be default
10315: text for $type. Otherwise, if this is a course, the text returned
10316: will be a custom name for the role (if defined in the course's
10317: environment). If no custom name is defined the default is returned.
10318:
1.832 raeburn 10319: =item *
10320:
1.935 raeburn 10321: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10322: All arguments are optional. Returns a hash of a roles, either for
10323: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10324: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10325: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10326: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10327: For each key, value is set to colon-separated start and end times for
10328: the role. If no username and domain are specified, will default to
1.934 raeburn 10329: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10330: of role statuses (active, future or previous), roles
10331: (e.g., cc,in, st etc.) and domains of the roles which can be used
10332: to restrict the list of roles reported. If no array ref is
10333: provided for types, will default to return only active roles.
1.834 albertel 10334:
1.243 albertel 10335: =back
10336:
10337: =head2 User Modification
10338:
10339: =over 4
10340:
10341: =item *
10342:
1.957 raeburn 10343: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10344: user for the level given by URL. Optional start and end dates (leave empty
10345: string or zero for "no date")
1.191 harris41 10346:
10347: =item *
10348:
1.243 albertel 10349: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10350: change a users, password, possible return values are: ok,
10351: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10352: refused
1.191 harris41 10353:
10354: =item *
10355:
1.243 albertel 10356: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10357:
10358: =item *
10359:
1.1058 raeburn 10360: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10361: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10362:
10363: will update user information (firstname,middlename,lastname,generation,
10364: permanentemail), and if forceid is true, student/employee ID also.
10365: A user's institutional affiliation(s) can also be updated.
10366: User information fields will not be overwritten with empty entries
10367: unless the field is included in the $candelete array reference.
10368: This array is included when a single user is modified via "Manage Users",
10369: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10370:
10371: =item *
10372:
1.286 matthew 10373: modifystudent
10374:
1.957 raeburn 10375: modify a student's enrollment and identification information.
1.286 matthew 10376: The course id is resolved based on the current users environment.
10377: This means the envoking user must be a course coordinator or otherwise
10378: associated with a course.
10379:
1.297 matthew 10380: This call is essentially a wrapper for lonnet::modifyuser and
10381: lonnet::modify_student_enrollment
1.286 matthew 10382:
10383: Inputs:
10384:
10385: =over 4
10386:
1.957 raeburn 10387: =item B<$udom> Student's loncapa domain
1.286 matthew 10388:
1.957 raeburn 10389: =item B<$uname> Student's loncapa login name
1.286 matthew 10390:
1.964 bisitz 10391: =item B<$uid> Student/Employee ID
1.286 matthew 10392:
1.957 raeburn 10393: =item B<$umode> Student's authentication mode
1.286 matthew 10394:
1.957 raeburn 10395: =item B<$upass> Student's password
1.286 matthew 10396:
1.957 raeburn 10397: =item B<$first> Student's first name
1.286 matthew 10398:
1.957 raeburn 10399: =item B<$middle> Student's middle name
1.286 matthew 10400:
1.957 raeburn 10401: =item B<$last> Student's last name
1.286 matthew 10402:
1.957 raeburn 10403: =item B<$gene> Student's generation
1.286 matthew 10404:
1.957 raeburn 10405: =item B<$usec> Student's section in course
1.286 matthew 10406:
10407: =item B<$end> Unix time of the roles expiration
10408:
10409: =item B<$start> Unix time of the roles start date
10410:
10411: =item B<$forceid> If defined, allow $uid to be changed
10412:
10413: =item B<$desiredhome> server to use as home server for student
10414:
1.957 raeburn 10415: =item B<$email> Student's permanent e-mail address
10416:
10417: =item B<$type> Type of enrollment (auto or manual)
10418:
1.963 raeburn 10419: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10420:
10421: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10422:
1.963 raeburn 10423: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10424:
1.963 raeburn 10425: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10426:
1.963 raeburn 10427: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10428:
1.286 matthew 10429: =back
1.297 matthew 10430:
10431: =item *
10432:
10433: modify_student_enrollment
10434:
10435: Change a students enrollment status in a class. The environment variable
10436: 'role.request.course' must be defined for this function to proceed.
10437:
10438: Inputs:
10439:
10440: =over 4
10441:
10442: =item $udom, students domain
10443:
10444: =item $uname, students name
10445:
10446: =item $uid, students user id
10447:
10448: =item $first, students first name
10449:
10450: =item $middle
10451:
10452: =item $last
10453:
10454: =item $gene
10455:
10456: =item $usec
10457:
10458: =item $end
10459:
10460: =item $start
10461:
1.957 raeburn 10462: =item $type
10463:
10464: =item $locktype
10465:
10466: =item $cid
10467:
10468: =item $selfenroll
10469:
10470: =item $context
10471:
1.297 matthew 10472: =back
10473:
1.191 harris41 10474:
10475: =item *
10476:
1.243 albertel 10477: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10478: custom role; give a custom role to a user for the level given by URL. Specify
10479: name and domain of role author, and role name
1.191 harris41 10480:
10481: =item *
10482:
1.243 albertel 10483: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10484:
10485: =item *
10486:
1.243 albertel 10487: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10488:
10489: =back
10490:
10491: =head2 Course Infomation
10492:
10493: =over 4
1.191 harris41 10494:
10495: =item *
10496:
1.631 albertel 10497: coursedescription($courseid) : returns a hash of information about the
10498: specified course id, including all environment settings for the
10499: course, the description of the course will be in the hash under the
10500: key 'description'
1.191 harris41 10501:
10502: =item *
10503:
1.624 albertel 10504: resdata($name,$domain,$type,@which) : request for current parameter
10505: setting for a specific $type, where $type is either 'course' or 'user',
10506: @what should be a list of parameters to ask about. This routine caches
10507: answers for 5 minutes.
1.243 albertel 10508:
1.877 foxr 10509: =item *
10510:
10511: get_courseresdata($courseid, $domain) : dump the entire course resource
10512: data base, returning a hash that is keyed by the resource name and has
10513: values that are the resource value. I believe that the timestamps and
10514: versions are also returned.
10515:
10516:
1.243 albertel 10517: =back
10518:
10519: =head2 Course Modification
10520:
10521: =over 4
1.191 harris41 10522:
10523: =item *
10524:
1.243 albertel 10525: writecoursepref($courseid,%prefs) : write preferences (environment
10526: database) for a course
1.191 harris41 10527:
10528: =item *
10529:
1.1011 raeburn 10530: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10531:
10532: =item *
10533:
1.1038 raeburn 10534: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10535:
10536: =back
10537:
10538: =head2 Resource Subroutines
10539:
10540: =over 4
1.191 harris41 10541:
10542: =item *
10543:
1.243 albertel 10544: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10545:
10546: =item *
10547:
1.243 albertel 10548: repcopy($filename) : subscribes to the requested file, and attempts to
10549: replicate from the owning library server, Might return
1.607 raeburn 10550: 'unavailable', 'not_found', 'forbidden', 'ok', or
10551: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10552: resource. Expects the local filesystem pathname
10553: (/home/httpd/html/res/....)
10554:
10555: =back
10556:
10557: =head2 Resource Information
10558:
10559: =over 4
1.191 harris41 10560:
10561: =item *
10562:
1.243 albertel 10563: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10564: a vairety of different possible values, $varname should be a request
10565: string, and the other parameters can be used to specify who and what
10566: one is asking about.
10567:
10568: Possible values for $varname are environment.lastname (or other item
10569: from the envirnment hash), user.name (or someother aspect about the
10570: user), resource.0.maxtries (or some other part and parameter of a
10571: resource)
1.204 albertel 10572:
10573: =item *
10574:
1.243 albertel 10575: directcondval($number) : get current value of a condition; reads from a state
10576: string
1.204 albertel 10577:
10578: =item *
10579:
1.243 albertel 10580: condval($condidx) : value of condition index based on state
1.204 albertel 10581:
10582: =item *
10583:
1.243 albertel 10584: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10585: resource's metadata, $what should be either a specific key, or either
10586: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10587: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10588:
10589: this function automatically caches all requests
1.191 harris41 10590:
10591: =item *
10592:
1.243 albertel 10593: metadata_query($query,$custom,$customshow) : make a metadata query against the
10594: network of library servers; returns file handle of where SQL and regex results
10595: will be stored for query
1.191 harris41 10596:
10597: =item *
10598:
1.243 albertel 10599: symbread($filename) : return symbolic list entry (filename argument optional);
10600: returns the data handle
1.191 harris41 10601:
10602: =item *
10603:
1.243 albertel 10604: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10605: a possible symb for the URL in $thisfn, and if is an encryypted
10606: resource that the user accessed using /enc/ returns a 1 on success, 0
10607: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10608: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10609:
1.191 harris41 10610:
10611: =item *
10612:
1.243 albertel 10613: symbclean($symb) : removes versions numbers from a symb, returns the
10614: cleaned symb
1.191 harris41 10615:
10616: =item *
10617:
1.243 albertel 10618: is_on_map($uri) : checks if the $uri is somewhere on the current
10619: course map, user must be in a course for it to work.
1.191 harris41 10620:
10621: =item *
10622:
1.243 albertel 10623: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10624:
10625: =item *
10626:
1.243 albertel 10627: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10628: a random seed, all arguments are optional, if they aren't sent it uses the
10629: environment to derive them. Note: if symb isn't sent and it can't get one
10630: from &symbread it will use the current time as its return value
1.191 harris41 10631:
10632: =item *
10633:
1.243 albertel 10634: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10635: unfakeable, receipt
1.191 harris41 10636:
10637: =item *
10638:
1.620 albertel 10639: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10640:
10641: =item *
10642:
1.243 albertel 10643: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10644:
10645: =item *
10646:
1.243 albertel 10647: 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 10648:
10649: =item *
10650:
1.243 albertel 10651: 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 10652:
10653: =item *
10654:
1.243 albertel 10655: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10656:
10657: =item *
10658:
1.243 albertel 10659: devalidate($symb) : devalidate temporary spreadsheet calculations,
10660: forcing spreadsheet to reevaluate the resource scores next time.
10661:
10662: =back
10663:
10664: =head2 Storing/Retreiving Data
10665:
10666: =over 4
1.191 harris41 10667:
10668: =item *
10669:
1.243 albertel 10670: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10671: for this url; hashref needs to be given and should be a \%hashname; the
10672: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10673: be derived from the env
1.191 harris41 10674:
10675: =item *
10676:
1.243 albertel 10677: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10678: uses critical subroutine
1.191 harris41 10679:
10680: =item *
10681:
1.243 albertel 10682: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10683: all args are optional
1.191 harris41 10684:
10685: =item *
10686:
1.717 albertel 10687: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10688: dumps the complete (or key matching regexp) namespace into a hash
10689: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10690: normally &store()ed into
10691:
10692: $range should be either an integer '100' (give me the first 100
10693: matching records)
10694: or be two integers sperated by a - with no spaces
10695: '30-50' (give me the 30th through the 50th matching
10696: records)
10697:
10698:
10699: =item *
10700:
10701: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10702: replaces a &store() version of data with a replacement set of data
10703: for a particular resource in a namespace passed in the $storehash hash
10704: reference
10705:
10706: =item *
10707:
1.243 albertel 10708: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10709: works very similar to store/cstore, but all data is stored in a
10710: temporary location and can be reset using tmpreset, $storehash should
10711: be a hash reference, returns nothing on success
1.191 harris41 10712:
10713: =item *
10714:
1.243 albertel 10715: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10716: similar to restore, but all data is stored in a temporary location and
10717: can be reset using tmpreset. Returns a hash of values on success,
10718: error string otherwise.
1.191 harris41 10719:
10720: =item *
10721:
1.243 albertel 10722: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10723: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 10724:
10725: =item *
10726:
1.243 albertel 10727: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10728: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 10729:
10730: =item *
10731:
1.243 albertel 10732: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10733: namesp ($udom and $uname are optional)
1.191 harris41 10734:
10735: =item *
10736:
1.702 albertel 10737: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 10738: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 10739: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 10740:
1.702 albertel 10741: $range should be either an integer '100' (give me the first 100
10742: matching records)
10743: or be two integers sperated by a - with no spaces
10744: '30-50' (give me the 30th through the 50th matching
10745: records)
1.449 matthew 10746: =item *
10747:
10748: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10749: $store can be a scalar, an array reference, or if the amount to be
10750: incremented is > 1, a hash reference.
10751:
10752: ($udom and $uname are optional)
1.191 harris41 10753:
10754: =item *
10755:
1.243 albertel 10756: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10757: ($udom and $uname are optional)
1.191 harris41 10758:
10759: =item *
10760:
1.243 albertel 10761: cput($namespace,$storehash,$udom,$uname) : critical put
10762: ($udom and $uname are optional)
1.191 harris41 10763:
10764: =item *
10765:
1.748 albertel 10766: newput($namespace,$storehash,$udom,$uname) :
10767:
10768: Attempts to store the items in the $storehash, but only if they don't
10769: currently exist, if this succeeds you can be certain that you have
10770: successfully created a new key value pair in the $namespace db.
10771:
10772:
10773: Args:
10774: $namespace: name of database to store values to
10775: $storehash: hashref to store to the db
10776: $udom: (optional) domain of user containing the db
10777: $uname: (optional) name of user caontaining the db
10778:
10779: Returns:
10780: 'ok' -> succeeded in storing all keys of $storehash
10781: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10782: least <key> already existed in the db (other
10783: requested keys may also already exist)
1.967 bisitz 10784: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 10785: 'con_lost' -> unable to contact request server
10786: 'refused' -> action was not allowed by remote machine
10787:
10788:
10789: =item *
10790:
1.243 albertel 10791: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10792: reference filled in from namesp (encrypts the return communication)
10793: ($udom and $uname are optional)
1.191 harris41 10794:
10795: =item *
10796:
1.243 albertel 10797: log($udom,$name,$home,$message) : write to permanent log for user; use
10798: critical subroutine
10799:
1.806 raeburn 10800: =item *
10801:
1.860 raeburn 10802: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10803: array reference filled in from namespace found in domain level on either
10804: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 10805:
10806: =item *
10807:
1.860 raeburn 10808: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10809: domain level either on specified domain server ($uhome) or primary domain
10810: server ($udom and $uhome are optional)
1.806 raeburn 10811:
1.943 raeburn 10812: =item *
10813:
10814: get_domain_defaults($target_domain) : returns hash with defaults for
10815: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10816: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10817: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10818: Values are retrieved from cache (if current), or from domain's configuration.db
10819: (if available), or lastly from values in lonTabs/dns_domain,tab,
10820: or lonTabs/domain.tab.
10821:
10822: %domdefaults = &get_auth_defaults($target_domain);
10823:
1.243 albertel 10824: =back
10825:
10826: =head2 Network Status Functions
10827:
10828: =over 4
1.191 harris41 10829:
10830: =item *
10831:
10832: dirlist($uri) : return directory list based on URI
10833:
10834: =item *
10835:
1.243 albertel 10836: spareserver() : find server with least workload from spare.tab
10837:
1.986 foxr 10838:
10839: =item *
10840:
10841: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10842: if there is no corresponding loncapa host.
10843:
1.243 albertel 10844: =back
10845:
1.986 foxr 10846:
1.243 albertel 10847: =head2 Apache Request
10848:
10849: =over 4
1.191 harris41 10850:
10851: =item *
10852:
1.243 albertel 10853: ssi($url,%hash) : server side include, does a complete request cycle on url to
10854: localhost, posts hash
10855:
10856: =back
10857:
10858: =head2 Data to String to Data
10859:
10860: =over 4
1.191 harris41 10861:
10862: =item *
10863:
1.243 albertel 10864: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10865: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 10866:
10867: =item *
10868:
1.243 albertel 10869: hashref2str($hashref) : convert a hashref into a string complete with
10870: escaping and '=' and '&' separators, supports elements that are
10871: arrayrefs and hashrefs
1.191 harris41 10872:
10873: =item *
10874:
1.243 albertel 10875: arrayref2str($arrayref) : convert an arrayref into a string complete
10876: with escaping and '&' separators, supports elements that are arrayrefs
10877: and hashrefs
1.191 harris41 10878:
10879: =item *
10880:
1.243 albertel 10881: str2hash($string) : convert string to hash using unescaping and
10882: splitting on '=' and '&', supports elements that are arrayrefs and
10883: hashrefs
1.191 harris41 10884:
10885: =item *
10886:
1.243 albertel 10887: str2array($string) : convert string to hash using unescaping and
10888: splitting on '&', supports elements that are arrayrefs and hashrefs
10889:
10890: =back
10891:
10892: =head2 Logging Routines
10893:
10894: =over 4
10895:
10896: These routines allow one to make log messages in the lonnet.log and
10897: lonnet.perm logfiles.
1.191 harris41 10898:
10899: =item *
10900:
1.243 albertel 10901: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 10902:
10903: =item *
10904:
1.243 albertel 10905: logthis() : append message to the normal lonnet.log file, it gets
10906: preiodically rolled over and deleted.
1.191 harris41 10907:
10908: =item *
10909:
1.243 albertel 10910: logperm() : append a permanent message to lonnet.perm.log, this log
10911: file never gets deleted by any automated portion of the system, only
10912: messages of critical importance should go in here.
10913:
10914: =back
10915:
10916: =head2 General File Helper Routines
10917:
10918: =over 4
1.191 harris41 10919:
10920: =item *
10921:
1.481 raeburn 10922: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10923: (a) files in /uploaded
10924: (i) If a local copy of the file exists -
10925: compares modification date of local copy with last-modified date for
10926: definitive version stored on home server for course. If local copy is
10927: stale, requests a new version from the home server and stores it.
10928: If the original has been removed from the home server, then local copy
10929: is unlinked.
10930: (ii) If local copy does not exist -
10931: requests the file from the home server and stores it.
10932:
10933: If $caller is 'uploadrep':
10934: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10935: for request for files originally uploaded via DOCS.
10936: - returns 'ok' if fresh local copy now available, -1 otherwise.
10937:
10938: Otherwise:
10939: This indicates a call from the content generation phase of the request.
10940: - returns the entire contents of the file or -1.
10941:
10942: (b) files in /res
10943: - returns the entire contents of a file or -1;
10944: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 10945:
1.712 albertel 10946:
10947: =item *
10948:
10949: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10950: reference
10951:
10952: returns either a stat() list of data about the file or an empty list
10953: if the file doesn't exist or couldn't find out about it (connection
10954: problems or user unknown)
10955:
1.191 harris41 10956: =item *
10957:
1.243 albertel 10958: filelocation($dir,$file) : returns file system location of a file
10959: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10960: directory that relative $file lookups are to looked in ($dir of /a/dir
10961: and a file of ../bob will become /a/bob)
1.191 harris41 10962:
10963: =item *
10964:
10965: hreflocation($dir,$file) : returns file system location or a URL; same as
10966: filelocation except for hrefs
10967:
10968: =item *
10969:
10970: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10971:
1.243 albertel 10972: =back
10973:
1.608 albertel 10974: =head2 Usererfile file routines (/uploaded*)
10975:
10976: =over 4
10977:
10978: =item *
10979:
10980: userfileupload(): main rotine for putting a file in a user or course's
10981: filespace, arguments are,
10982:
1.620 albertel 10983: formname - required - this is the name of the element in $env where the
1.608 albertel 10984: filename, and the contents of the file to create/modifed exist
1.620 albertel 10985: the filename is in $env{'form.'.$formname.'.filename'} and the
10986: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10987: coursedoc - if true, store the file in the course of the active role
10988: of the current user
10989: subdir - required - subdirectory to put the file in under ../userfiles/
10990: if undefined, it will be placed in "unknown"
10991:
10992: (This routine calls clean_filename() to remove any dangerous
10993: characters from the filename, and then calls finuserfileupload() to
10994: complete the transaction)
10995:
10996: returns either the url of the uploaded file (/uploaded/....) if successful
10997: and /adm/notfound.html if unsuccessful
10998:
10999: =item *
11000:
11001: clean_filename(): routine for cleaing a filename up for storage in
11002: userfile space, argument is:
11003:
11004: filename - proposed filename
11005:
11006: returns: the new clean filename
11007:
11008: =item *
11009:
11010: finishuserfileupload(): routine that creaes and sends the file to
11011: userspace, probably shouldn't be called directly
11012:
11013: docuname: username or courseid of destination for the file
11014: docudom: domain of user/course of destination for the file
11015: formname: same as for userfileupload()
11016: fname: filename (inculding subdirectories) for the file
11017:
11018: returns either the url of the uploaded file (/uploaded/....) if successful
11019: and /adm/notfound.html if unsuccessful
11020:
11021: =item *
11022:
11023: renameuserfile(): renames an existing userfile to a new name
11024:
11025: Args:
11026: docuname: username or courseid of destination for the file
11027: docudom: domain of user/course of destination for the file
11028: old: current file name (including any subdirs under userfiles)
11029: new: desired file name (including any subdirs under userfiles)
11030:
11031: =item *
11032:
11033: mkdiruserfile(): creates a directory is a userfiles dir
11034:
11035: Args:
11036: docuname: username or courseid of destination for the file
11037: docudom: domain of user/course of destination for the file
11038: dir: dir to create (including any subdirs under userfiles)
11039:
11040: =item *
11041:
11042: removeuserfile(): removes a file that exists in userfiles
11043:
11044: Args:
11045: docuname: username or courseid of destination for the file
11046: docudom: domain of user/course of destination for the file
11047: fname: filname to delete (including any subdirs under userfiles)
11048:
11049: =item *
11050:
11051: removeuploadedurl(): convience function for removeuserfile()
11052:
11053: Args:
11054: url: a full /uploaded/... url to delete
11055:
1.747 albertel 11056: =item *
11057:
11058: get_portfile_permissions():
11059: Args:
11060: domain: domain of user or course contain the portfolio files
11061: user: name of user or num of course contain the portfolio files
11062: Returns:
11063: hashref of a dump of the proper file_permissions.db
11064:
11065:
11066: =item *
11067:
11068: get_access_controls():
11069:
11070: Args:
11071: current_permissions: the hash ref returned from get_portfile_permissions()
11072: group: (optional) the group you want the files associated with
11073: file: (optional) the file you want access info on
11074:
11075: Returns:
1.749 raeburn 11076: a hash (keys are file names) of hashes containing
11077: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11078: values are XML containing access control settings (see below)
1.747 albertel 11079:
11080: Internal notes:
11081:
1.749 raeburn 11082: access controls are stored in file_permissions.db as key=value pairs.
11083: key -> path to file/file_name\0uniqueID:scope_end_start
11084: where scope -> public,guest,course,group,domains or users.
11085: end -> UNIX time for end of access (0 -> no end date)
11086: start -> UNIX time for start of access
11087:
11088: value -> XML description of access control
11089: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11090: <start></start>
11091: <end></end>
11092:
11093: <password></password> for scope type = guest
11094:
11095: <domain></domain> for scope type = course or group
11096: <number></number>
11097: <roles id="">
11098: <role></role>
11099: <access></access>
11100: <section></section>
11101: <group></group>
11102: </roles>
11103:
11104: <dom></dom> for scope type = domains
11105:
11106: <users> for scope type = users
11107: <user>
11108: <uname></uname>
11109: <udom></udom>
11110: </user>
11111: </users>
11112: </scope>
11113:
11114: Access data is also aggregated for each file in an additional key=value pair:
11115: key -> path to file/file_name\0accesscontrol
11116: value -> reference to hash
11117: hash contains key = value pairs
11118: where key = uniqueID:scope_end_start
11119: value = UNIX time record was last updated
11120:
11121: Used to improve speed of look-ups of access controls for each file.
11122:
11123: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11124:
11125: modify_access_controls():
11126:
11127: Modifies access controls for a portfolio file
11128: Args
11129: 1. file name
11130: 2. reference to hash of required changes,
11131: 3. domain
11132: 4. username
11133: where domain,username are the domain of the portfolio owner
11134: (either a user or a course)
11135:
11136: Returns:
11137: 1. result of additions or updates ('ok' or 'error', with error message).
11138: 2. result of deletions ('ok' or 'error', with error message).
11139: 3. reference to hash of any new or updated access controls.
11140: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11141: key = integer (inbound ID)
11142: value = uniqueID
1.747 albertel 11143:
1.608 albertel 11144: =back
11145:
1.243 albertel 11146: =head2 HTTP Helper Routines
11147:
11148: =over 4
11149:
1.191 harris41 11150: =item *
11151:
11152: escape() : unpack non-word characters into CGI-compatible hex codes
11153:
11154: =item *
11155:
11156: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11157:
1.243 albertel 11158: =back
11159:
11160: =head1 PRIVATE SUBROUTINES
11161:
11162: =head2 Underlying communication routines (Shouldn't call)
11163:
11164: =over 4
11165:
11166: =item *
11167:
11168: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11169:
11170: =item *
11171:
11172: reply() : uses subreply to send a message to remote machine, logs all failures
11173:
11174: =item *
11175:
11176: critical() : passes a critical message to another server; if cannot
11177: get through then place message in connection buffer directory and
11178: returns con_delayed, if incapable of saving message, returns
11179: con_failed
11180:
11181: =item *
11182:
11183: reconlonc() : tries to reconnect lonc client processes.
11184:
11185: =back
11186:
11187: =head2 Resource Access Logging
11188:
11189: =over 4
11190:
11191: =item *
11192:
11193: flushcourselogs() : flush (save) buffer logs and access logs
11194:
11195: =item *
11196:
11197: courselog($what) : save message for course in hash
11198:
11199: =item *
11200:
11201: courseacclog($what) : save message for course using &courselog(). Perform
11202: special processing for specific resource types (problems, exams, quizzes, etc).
11203:
1.191 harris41 11204: =item *
11205:
11206: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11207: as a PerlChildExitHandler
1.243 albertel 11208:
11209: =back
11210:
11211: =head2 Other
11212:
11213: =over 4
11214:
11215: =item *
11216:
11217: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11218:
11219: =back
11220:
11221: =cut
1.877 foxr 11222:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>