Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1060
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1060 ! raeburn 4: # $Id: lonnet.pm,v 1.1059 2010/03/24 03:29:11 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968 raeburn 79: $_64bit %env %protocol);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.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:
668: # ------------------------------------------ Fight off request when overloaded
669:
670: sub overloaderror {
671: my ($r,$checkserver)=@_;
672: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
673: my $loadavg;
674: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 675: open(my $loadfile,'/proc/loadavg');
1.283 www 676: $loadavg=<$loadfile>;
677: $loadavg =~ s/\s.*//g;
1.285 matthew 678: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 679: close($loadfile);
1.283 www 680: } else {
681: $loadavg=&reply('load',$checkserver);
682: }
1.285 matthew 683: my $overload=$loadavg-100;
1.283 www 684: if ($overload>0) {
1.285 matthew 685: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 686: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 687: return 413;
1.283 www 688: }
689: return '';
1.5 www 690: }
1.1 albertel 691:
692: # ------------------------------ Find server with least workload from spare.tab
1.11 www 693:
1.1 albertel 694: sub spareserver {
1.670 albertel 695: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 696: my $spare_server;
1.370 albertel 697: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 698: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
699: : $userloadpercent;
700:
701: foreach my $try_server (@{ $spareid{'primary'} }) {
702: ($spare_server, $lowest_load) =
703: &compare_server_load($try_server, $spare_server, $lowest_load);
704: }
705:
706: my $found_server = ($spare_server ne '' && $lowest_load < 100);
707:
708: if (!$found_server) {
709: foreach my $try_server (@{ $spareid{'default'} }) {
710: ($spare_server, $lowest_load) =
711: &compare_server_load($try_server, $spare_server, $lowest_load);
712: }
713: }
714:
715: if (!$want_server_name) {
1.968 raeburn 716: my $protocol = 'http';
717: if ($protocol{$spare_server} eq 'https') {
718: $protocol = $protocol{$spare_server};
719: }
1.1001 raeburn 720: if (defined($spare_server)) {
721: my $hostname = &hostname($spare_server);
722: if (defined($hostname)) {
723: $spare_server = $protocol.'://'.$hostname;
724: }
725: }
1.784 albertel 726: }
727: return $spare_server;
728: }
729:
730: sub compare_server_load {
731: my ($try_server, $spare_server, $lowest_load) = @_;
732:
733: my $loadans = &reply('load', $try_server);
734: my $userloadans = &reply('userload',$try_server);
735:
736: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
737: next; #didn't get a number from the server
738: }
739:
740: my $load;
741: if ($loadans =~ /\d/) {
742: if ($userloadans =~ /\d/) {
743: #both are numbers, pick the bigger one
744: $load = ($loadans > $userloadans) ? $loadans
745: : $userloadans;
1.411 albertel 746: } else {
1.784 albertel 747: $load = $loadans;
1.411 albertel 748: }
1.784 albertel 749: } else {
750: $load = $userloadans;
751: }
752:
753: if (($load =~ /\d/) && ($load < $lowest_load)) {
754: $spare_server = $try_server;
755: $lowest_load = $load;
1.370 albertel 756: }
1.784 albertel 757: return ($spare_server,$lowest_load);
1.202 matthew 758: }
1.914 albertel 759:
760: # --------------------------- ask offload servers if user already has a session
761: sub find_existing_session {
762: my ($udom,$uname) = @_;
763: foreach my $try_server (@{ $spareid{'primary'} },
764: @{ $spareid{'default'} }) {
765: return $try_server if (&has_user_session($try_server, $udom, $uname));
766: }
767: return;
768: }
769:
770: # -------------------------------- ask if server already has a session for user
771: sub has_user_session {
772: my ($lonid,$udom,$uname) = @_;
773: my $result = &reply(join(':','userhassession',
774: map {&escape($_)} ($udom,$uname)),$lonid);
775: return 1 if ($result eq 'ok');
776:
777: return 0;
778: }
779:
1.202 matthew 780: # --------------------------------------------- Try to change a user's password
781:
782: sub changepass {
1.799 raeburn 783: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 784: $currentpass = &escape($currentpass);
785: $newpass = &escape($newpass);
1.1030 raeburn 786: my $lonhost = $perlvar{'lonHostID'};
787: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 788: $server);
789: if (! $answer) {
790: &logthis("No reply on password change request to $server ".
791: "by $uname in domain $udom.");
792: } elsif ($answer =~ "^ok") {
793: &logthis("$uname in $udom successfully changed their password ".
794: "on $server.");
795: } elsif ($answer =~ "^pwchange_failure") {
796: &logthis("$uname in $udom was unable to change their password ".
797: "on $server. The action was blocked by either lcpasswd ".
798: "or pwchange");
799: } elsif ($answer =~ "^non_authorized") {
800: &logthis("$uname in $udom did not get their password correct when ".
801: "attempting to change it on $server.");
802: } elsif ($answer =~ "^auth_mode_error") {
803: &logthis("$uname in $udom attempted to change their password despite ".
804: "not being locally or internally authenticated on $server.");
805: } elsif ($answer =~ "^unknown_user") {
806: &logthis("$uname in $udom attempted to change their password ".
807: "on $server but were unable to because $server is not ".
808: "their home server.");
809: } elsif ($answer =~ "^refused") {
810: &logthis("$server refused to change $uname in $udom password because ".
811: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 812: } elsif ($answer =~ "invalid_client") {
813: &logthis("$server refused to change $uname in $udom password because ".
814: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 815: }
816: return $answer;
1.1 albertel 817: }
818:
1.169 harris41 819: # ----------------------- Try to determine user's current authentication scheme
820:
821: sub queryauthenticate {
822: my ($uname,$udom)=@_;
1.456 albertel 823: my $uhome=&homeserver($uname,$udom);
824: if (!$uhome) {
825: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
826: return 'no_host';
827: }
828: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
829: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
830: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 831: }
1.456 albertel 832: return $answer;
1.169 harris41 833: }
834:
1.1 albertel 835: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 836:
1.1 albertel 837: sub authenticate {
1.952 raeburn 838: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 839: $upass=&escape($upass);
840: $uname= &LONCAPA::clean_username($uname);
1.836 www 841: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 842: my $newhome;
1.836 www 843: if ((!$uhome) || ($uhome eq 'no_host')) {
844: # Maybe the machine was offline and only re-appeared again recently?
845: &reconlonc();
846: # One more
1.952 raeburn 847: $uhome=&homeserver($uname,$udom,1);
848: if (($uhome eq 'no_host') && $checkdefauth) {
849: if (defined(&domain($udom,'primary'))) {
850: $newhome=&domain($udom,'primary');
851: }
852: if ($newhome ne '') {
853: $uhome = $newhome;
854: }
855: }
1.836 www 856: if ((!$uhome) || ($uhome eq 'no_host')) {
857: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 858: return 'no_host';
859: }
1.1 albertel 860: }
1.952 raeburn 861: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 862: if ($answer eq 'authorized') {
1.952 raeburn 863: if ($newhome) {
864: &logthis("User $uname at $udom authorized by $uhome, but needs account");
865: return 'no_account_on_host';
866: } else {
867: &logthis("User $uname at $udom authorized by $uhome");
868: return $uhome;
869: }
1.471 albertel 870: }
871: if ($answer eq 'non_authorized') {
872: &logthis("User $uname at $udom rejected by $uhome");
873: return 'no_host';
1.9 www 874: }
1.471 albertel 875: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 876: return 'no_host';
877: }
878:
879: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 880:
1.599 albertel 881: my %homecache;
1.1 albertel 882: sub homeserver {
1.230 stredwic 883: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 884: my $index="$uname:$udom";
1.426 albertel 885:
1.599 albertel 886: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 887:
888: my %servers = &get_servers($udom,'library');
889: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 890: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 891: exists($badServerCache{$tryserver}));
1.841 albertel 892:
893: my $answer=reply("home:$udom:$uname",$tryserver);
894: if ($answer eq 'found') {
895: delete($badServerCache{$tryserver});
896: return $homecache{$index}=$tryserver;
897: } elsif ($answer eq 'no_host') {
898: $badServerCache{$tryserver}=1;
899: }
1.1 albertel 900: }
901: return 'no_host';
1.70 www 902: }
903:
904: # ------------------------------------- Find the usernames behind a list of IDs
905:
906: sub idget {
907: my ($udom,@ids)=@_;
908: my %returnhash=();
909:
1.841 albertel 910: my %servers = &get_servers($udom,'library');
911: foreach my $tryserver (keys(%servers)) {
912: my $idlist=join('&',@ids);
913: $idlist=~tr/A-Z/a-z/;
914: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
915: my @answer=();
916: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
917: @answer=split(/\&/,$reply);
918: } ;
919: my $i;
920: for ($i=0;$i<=$#ids;$i++) {
921: if ($answer[$i]) {
922: $returnhash{$ids[$i]}=$answer[$i];
923: }
924: }
925: }
1.70 www 926: return %returnhash;
927: }
928:
929: # ------------------------------------- Find the IDs behind a list of usernames
930:
931: sub idrget {
932: my ($udom,@unames)=@_;
933: my %returnhash=();
1.800 albertel 934: foreach my $uname (@unames) {
935: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 936: }
1.70 www 937: return %returnhash;
938: }
939:
940: # ------------------------------- Store away a list of names and associated IDs
941:
942: sub idput {
943: my ($udom,%ids)=@_;
944: my %servers=();
1.800 albertel 945: foreach my $uname (keys(%ids)) {
946: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
947: my $uhom=&homeserver($uname,$udom);
1.70 www 948: if ($uhom ne 'no_host') {
1.800 albertel 949: my $id=&escape($ids{$uname});
1.70 www 950: $id=~tr/A-Z/a-z/;
1.800 albertel 951: my $esc_unam=&escape($uname);
1.70 www 952: if ($servers{$uhom}) {
1.800 albertel 953: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 954: } else {
1.800 albertel 955: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 956: }
957: }
1.191 harris41 958: }
1.800 albertel 959: foreach my $server (keys(%servers)) {
960: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 961: }
1.344 www 962: }
963:
1.1023 raeburn 964: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 965: sub dump_dom {
1.1023 raeburn 966: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 967: if (!$udom) {
968: $udom=$env{'user.domain'};
969: }
970: my %returnhash;
1.1023 raeburn 971: if ($udom) {
972: my $uname = &get_domainconfiguser($udom);
973: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 974: }
975: return %returnhash;
976: }
977:
1.1023 raeburn 978: # ------------------------------------------ get items from domain db files
1.806 raeburn 979:
980: sub get_dom {
1.860 raeburn 981: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 982: my $items='';
983: foreach my $item (@$storearr) {
984: $items.=&escape($item).'&';
985: }
986: $items=~s/\&$//;
1.860 raeburn 987: if (!$udom) {
988: $udom=$env{'user.domain'};
989: if (defined(&domain($udom,'primary'))) {
990: $uhome=&domain($udom,'primary');
991: } else {
1.874 albertel 992: undef($uhome);
1.860 raeburn 993: }
994: } else {
995: if (!$uhome) {
996: if (defined(&domain($udom,'primary'))) {
997: $uhome=&domain($udom,'primary');
998: }
999: }
1000: }
1001: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1002: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1003: my %returnhash;
1.875 albertel 1004: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1005: return %returnhash;
1006: }
1.806 raeburn 1007: my @pairs=split(/\&/,$rep);
1008: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1009: return @pairs;
1010: }
1011: my $i=0;
1012: foreach my $item (@$storearr) {
1013: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1014: $i++;
1015: }
1016: return %returnhash;
1017: } else {
1.880 banghart 1018: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1019: }
1020: }
1021:
1022: # -------------------------------------------- put items in domain db files
1023:
1024: sub put_dom {
1.860 raeburn 1025: my ($namespace,$storehash,$udom,$uhome)=@_;
1026: if (!$udom) {
1027: $udom=$env{'user.domain'};
1028: if (defined(&domain($udom,'primary'))) {
1029: $uhome=&domain($udom,'primary');
1030: } else {
1.874 albertel 1031: undef($uhome);
1.860 raeburn 1032: }
1033: } else {
1034: if (!$uhome) {
1035: if (defined(&domain($udom,'primary'))) {
1036: $uhome=&domain($udom,'primary');
1037: }
1038: }
1039: }
1040: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1041: my $items='';
1042: foreach my $item (keys(%$storehash)) {
1043: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1044: }
1045: $items=~s/\&$//;
1046: return &reply("putdom:$udom:$namespace:$items",$uhome);
1047: } else {
1.860 raeburn 1048: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1049: }
1050: }
1051:
1.1023 raeburn 1052: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1053: sub newput_dom {
1.1023 raeburn 1054: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1055: my $result;
1056: if (!$udom) {
1057: $udom=$env{'user.domain'};
1058: }
1.1023 raeburn 1059: if ($udom) {
1060: my $uname = &get_domainconfiguser($udom);
1061: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1062: }
1063: return $result;
1064: }
1065:
1.1023 raeburn 1066: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1067: sub del_dom {
1.1023 raeburn 1068: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1069: if (ref($storearr) eq 'ARRAY') {
1070: if (!$udom) {
1071: $udom=$env{'user.domain'};
1072: }
1.1023 raeburn 1073: if ($udom) {
1074: my $uname = &get_domainconfiguser($udom);
1075: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1076: }
1077: }
1078: }
1079:
1.1023 raeburn 1080: # ----------------------------------construct domainconfig user for a domain
1081: sub get_domainconfiguser {
1082: my ($udom) = @_;
1083: return $udom.'-domainconfig';
1084: }
1085:
1.837 raeburn 1086: sub retrieve_inst_usertypes {
1087: my ($udom) = @_;
1088: my (%returnhash,@order);
1.989 raeburn 1089: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1090: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1091: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1092: %returnhash = %{$domdefs{'inststatustypes'}};
1093: @order = @{$domdefs{'inststatusorder'}};
1094: } else {
1095: if (defined(&domain($udom,'primary'))) {
1096: my $uhome=&domain($udom,'primary');
1097: my $rep=&reply("inst_usertypes:$udom",$uhome);
1098: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1099: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1100: return (\%returnhash,\@order);
1101: }
1102: my ($hashitems,$orderitems) = split(/:/,$rep);
1103: my @pairs=split(/\&/,$hashitems);
1104: foreach my $item (@pairs) {
1105: my ($key,$value)=split(/=/,$item,2);
1106: $key = &unescape($key);
1107: next if ($key =~ /^error: 2 /);
1108: $returnhash{$key}=&thaw_unescape($value);
1109: }
1110: my @esc_order = split(/\&/,$orderitems);
1111: foreach my $item (@esc_order) {
1112: push(@order,&unescape($item));
1113: }
1114: } else {
1115: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1116: }
1117: }
1118: return (\%returnhash,\@order);
1119: }
1120:
1.868 raeburn 1121: sub is_domainimage {
1122: my ($url) = @_;
1123: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1124: if (&domain($1) ne '') {
1125: return '1';
1126: }
1127: }
1128: return;
1129: }
1130:
1.899 raeburn 1131: sub inst_directory_query {
1132: my ($srch) = @_;
1133: my $udom = $srch->{'srchdomain'};
1134: my %results;
1135: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1136: my $outcome;
1.899 raeburn 1137: if ($homeserver ne '') {
1.904 albertel 1138: my $queryid=&reply("querysend:instdirsearch:".
1139: &escape($srch->{'srchby'}).':'.
1140: &escape($srch->{'srchterm'}).':'.
1141: &escape($srch->{'srchtype'}),$homeserver);
1142: my $host=&hostname($homeserver);
1143: if ($queryid !~/^\Q$host\E\_/) {
1144: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1145: return;
1146: }
1147: my $response = &get_query_reply($queryid);
1148: my $maxtries = 5;
1149: my $tries = 1;
1150: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1151: $response = &get_query_reply($queryid);
1152: $tries ++;
1153: }
1154:
1155: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1156: if ($response eq 'unavailable') {
1157: $outcome = $response;
1158: } else {
1159: $outcome = 'ok';
1160: my @matches = split(/\n/,$response);
1161: foreach my $match (@matches) {
1162: my ($key,$value) = split(/=/,$match);
1163: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1164: }
1.899 raeburn 1165: }
1166: }
1167: }
1.909 raeburn 1168: return ($outcome,%results);
1.899 raeburn 1169: }
1170:
1171: sub usersearch {
1172: my ($srch) = @_;
1173: my $dom = $srch->{'srchdomain'};
1174: my %results;
1175: my %libserv = &all_library();
1176: my $query = 'usersearch';
1177: foreach my $tryserver (keys(%libserv)) {
1178: if (&host_domain($tryserver) eq $dom) {
1179: my $host=&hostname($tryserver);
1180: my $queryid=
1.911 raeburn 1181: &reply("querysend:".&escape($query).':'.
1182: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1183: &escape($srch->{'srchtype'}).':'.
1184: &escape($srch->{'srchterm'}),$tryserver);
1185: if ($queryid !~/^\Q$host\E\_/) {
1186: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1187: next;
1.899 raeburn 1188: }
1189: my $reply = &get_query_reply($queryid);
1190: my $maxtries = 1;
1191: my $tries = 1;
1192: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1193: $reply = &get_query_reply($queryid);
1194: $tries ++;
1195: }
1196: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1197: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1198: } else {
1.911 raeburn 1199: my @matches;
1200: if ($reply =~ /\n/) {
1201: @matches = split(/\n/,$reply);
1202: } else {
1203: @matches = split(/\&/,$reply);
1204: }
1.899 raeburn 1205: foreach my $match (@matches) {
1206: my ($uname,$udom,%userhash);
1.911 raeburn 1207: foreach my $entry (split(/:/,$match)) {
1208: my ($key,$value) =
1209: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1210: $userhash{$key} = $value;
1211: if ($key eq 'username') {
1212: $uname = $value;
1213: } elsif ($key eq 'domain') {
1214: $udom = $value;
1.911 raeburn 1215: }
1.899 raeburn 1216: }
1217: $results{$uname.':'.$udom} = \%userhash;
1218: }
1219: }
1220: }
1221: }
1222: return %results;
1223: }
1224:
1.912 raeburn 1225: sub get_instuser {
1226: my ($udom,$uname,$id) = @_;
1227: my $homeserver = &domain($udom,'primary');
1228: my ($outcome,%results);
1229: if ($homeserver ne '') {
1230: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1231: &escape($id).':'.&escape($udom),$homeserver);
1232: my $host=&hostname($homeserver);
1233: if ($queryid !~/^\Q$host\E\_/) {
1234: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1235: return;
1236: }
1237: my $response = &get_query_reply($queryid);
1238: my $maxtries = 5;
1239: my $tries = 1;
1240: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1241: $response = &get_query_reply($queryid);
1242: $tries ++;
1243: }
1244: if (!&error($response) && $response ne 'refused') {
1245: if ($response eq 'unavailable') {
1246: $outcome = $response;
1247: } else {
1248: $outcome = 'ok';
1249: my @matches = split(/\n/,$response);
1250: foreach my $match (@matches) {
1251: my ($key,$value) = split(/=/,$match);
1252: $results{&unescape($key)} = &thaw_unescape($value);
1253: }
1254: }
1255: }
1256: }
1257: my %userinfo;
1258: if (ref($results{$uname}) eq 'HASH') {
1259: %userinfo = %{$results{$uname}};
1260: }
1261: return ($outcome,%userinfo);
1262: }
1263:
1264: sub inst_rulecheck {
1.923 raeburn 1265: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1266: my %returnhash;
1267: if ($udom ne '') {
1268: if (ref($rules) eq 'ARRAY') {
1269: @{$rules} = map {&escape($_);} (@{$rules});
1270: my $rulestr = join(':',@{$rules});
1271: my $homeserver=&domain($udom,'primary');
1272: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1273: my $response;
1274: if ($item eq 'username') {
1275: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1276: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1277: $homeserver));
1.923 raeburn 1278: } elsif ($item eq 'id') {
1279: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1280: ':'.&escape($id).':'.$rulestr,
1281: $homeserver));
1.945 raeburn 1282: } elsif ($item eq 'selfcreate') {
1283: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1284: &escape($udom).':'.&escape($uname).
1285: ':'.$rulestr,$homeserver));
1.923 raeburn 1286: }
1.912 raeburn 1287: if ($response ne 'refused') {
1288: my @pairs=split(/\&/,$response);
1289: foreach my $item (@pairs) {
1290: my ($key,$value)=split(/=/,$item,2);
1291: $key = &unescape($key);
1292: next if ($key =~ /^error: 2 /);
1293: $returnhash{$key}=&thaw_unescape($value);
1294: }
1295: }
1296: }
1297: }
1298: }
1299: return %returnhash;
1300: }
1301:
1302: sub inst_userrules {
1.923 raeburn 1303: my ($udom,$check) = @_;
1.912 raeburn 1304: my (%ruleshash,@ruleorder);
1305: if ($udom ne '') {
1306: my $homeserver=&domain($udom,'primary');
1307: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1308: my $response;
1309: if ($check eq 'id') {
1310: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1311: $homeserver);
1.943 raeburn 1312: } elsif ($check eq 'email') {
1313: $response=&reply('instemailrules:'.&escape($udom),
1314: $homeserver);
1.923 raeburn 1315: } else {
1316: $response=&reply('instuserrules:'.&escape($udom),
1317: $homeserver);
1318: }
1.912 raeburn 1319: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1320: ($response ne 'unknown_cmd') &&
1.912 raeburn 1321: ($response ne 'no_such_host')) {
1322: my ($hashitems,$orderitems) = split(/:/,$response);
1323: my @pairs=split(/\&/,$hashitems);
1324: foreach my $item (@pairs) {
1325: my ($key,$value)=split(/=/,$item,2);
1326: $key = &unescape($key);
1327: next if ($key =~ /^error: 2 /);
1328: $ruleshash{$key}=&thaw_unescape($value);
1329: }
1330: my @esc_order = split(/\&/,$orderitems);
1331: foreach my $item (@esc_order) {
1332: push(@ruleorder,&unescape($item));
1333: }
1334: }
1335: }
1336: }
1337: return (\%ruleshash,\@ruleorder);
1338: }
1339:
1.976 raeburn 1340: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1341:
1342: sub get_domain_defaults {
1343: my ($domain) = @_;
1344: my $cachetime = 60*60*24;
1345: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1346: if (defined($cached)) {
1347: if (ref($result) eq 'HASH') {
1348: return %{$result};
1349: }
1350: }
1351: my %domdefaults;
1352: my %domconfig =
1.989 raeburn 1353: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1354: 'requestcourses','inststatus',
1355: 'coursedefaults'],$domain);
1.943 raeburn 1356: if (ref($domconfig{'defaults'}) eq 'HASH') {
1357: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1358: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1359: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1360: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1361: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1362: } else {
1363: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1364: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1365: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1366: }
1.976 raeburn 1367: if (ref($domconfig{'quotas'}) eq 'HASH') {
1368: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1369: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1370: } else {
1371: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1372: }
1373: my @usertools = ('aboutme','blog','portfolio');
1374: foreach my $item (@usertools) {
1375: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1376: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1377: }
1378: }
1379: }
1.985 raeburn 1380: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1381: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1382: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1383: }
1384: }
1.989 raeburn 1385: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1386: foreach my $item ('inststatustypes','inststatusorder') {
1387: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1388: }
1389: }
1.1047 raeburn 1390: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1391: foreach my $item ('canuse_pdfforms') {
1392: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1393: }
1394: }
1.943 raeburn 1395: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1396: $cachetime);
1397: return %domdefaults;
1398: }
1399:
1.344 www 1400: # --------------------------------------------------- Assign a key to a student
1401:
1402: sub assign_access_key {
1.364 www 1403: #
1404: # a valid key looks like uname:udom#comments
1405: # comments are being appended
1406: #
1.498 www 1407: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1408: $kdom=
1.620 albertel 1409: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1410: $knum=
1.620 albertel 1411: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1412: $cdom=
1.620 albertel 1413: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1414: $cnum=
1.620 albertel 1415: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1416: $udom=$env{'user.name'} unless (defined($udom));
1417: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1418: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1419: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1420: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1421: # assigned to this person
1422: # - this should not happen,
1.345 www 1423: # unless something went wrong
1424: # the first time around
1425: # ready to assign
1.364 www 1426: $logentry=$1.'; '.$logentry;
1.496 www 1427: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1428: $kdom,$knum) eq 'ok') {
1.345 www 1429: # key now belongs to user
1.346 www 1430: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1431: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1432: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1433: return 'ok';
1434: } else {
1435: return
1436: 'error: Count not permanently assign key, will need to be re-entered later.';
1437: }
1438: } else {
1439: return 'error: Could not assign key, try again later.';
1440: }
1.364 www 1441: } elsif (!$existing{$ckey}) {
1.345 www 1442: # the key does not exist
1443: return 'error: The key does not exist';
1444: } else {
1445: # the key is somebody else's
1446: return 'error: The key is already in use';
1447: }
1.344 www 1448: }
1449:
1.364 www 1450: # ------------------------------------------ put an additional comment on a key
1451:
1452: sub comment_access_key {
1453: #
1454: # a valid key looks like uname:udom#comments
1455: # comments are being appended
1456: #
1457: my ($ckey,$cdom,$cnum,$logentry)=@_;
1458: $cdom=
1.620 albertel 1459: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1460: $cnum=
1.620 albertel 1461: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1462: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1463: if ($existing{$ckey}) {
1464: $existing{$ckey}.='; '.$logentry;
1465: # ready to assign
1.367 www 1466: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1467: $cdom,$cnum) eq 'ok') {
1468: return 'ok';
1469: } else {
1470: return 'error: Count not store comment.';
1471: }
1472: } else {
1473: # the key does not exist
1474: return 'error: The key does not exist';
1475: }
1476: }
1477:
1.344 www 1478: # ------------------------------------------------------ Generate a set of keys
1479:
1480: sub generate_access_keys {
1.364 www 1481: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1482: $cdom=
1.620 albertel 1483: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1484: $cnum=
1.620 albertel 1485: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1486: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1487: unless (($cdom) && ($cnum)) { return 0; }
1488: if ($number>10000) { return 0; }
1489: sleep(2); # make sure don't get same seed twice
1490: srand(time()^($$+($$<<15))); # from "Programming Perl"
1491: my $total=0;
1492: for (my $i=1;$i<=$number;$i++) {
1493: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1494: sprintf("%lx",int(100000*rand)).'-'.
1495: sprintf("%lx",int(100000*rand));
1496: $newkey=~s/1/g/g; # folks mix up 1 and l
1497: $newkey=~s/0/h/g; # and also 0 and O
1498: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1499: if ($existing{$newkey}) {
1500: $i--;
1501: } else {
1.364 www 1502: if (&put('accesskeys',
1503: { $newkey => '# generated '.localtime().
1.620 albertel 1504: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1505: '; '.$logentry },
1506: $cdom,$cnum) eq 'ok') {
1.344 www 1507: $total++;
1508: }
1509: }
1510: }
1.620 albertel 1511: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1512: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1513: return $total;
1514: }
1515:
1516: # ------------------------------------------------------- Validate an accesskey
1517:
1518: sub validate_access_key {
1519: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1520: $cdom=
1.620 albertel 1521: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1522: $cnum=
1.620 albertel 1523: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1524: $udom=$env{'user.domain'} unless (defined($udom));
1525: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1526: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1527: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1528: }
1529:
1530: # ------------------------------------- Find the section of student in a course
1.652 albertel 1531: sub devalidate_getsection_cache {
1532: my ($udom,$unam,$courseid)=@_;
1533: my $hashid="$udom:$unam:$courseid";
1534: &devalidate_cache_new('getsection',$hashid);
1535: }
1.298 matthew 1536:
1.815 albertel 1537: sub courseid_to_courseurl {
1538: my ($courseid) = @_;
1539: #already url style courseid
1540: return $courseid if ($courseid =~ m{^/});
1541:
1542: if (exists($env{'course.'.$courseid.'.num'})) {
1543: my $cnum = $env{'course.'.$courseid.'.num'};
1544: my $cdom = $env{'course.'.$courseid.'.domain'};
1545: return "/$cdom/$cnum";
1546: }
1547:
1548: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1549: if (exists($courseinfo{'num'})) {
1550: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1551: }
1552:
1553: return undef;
1554: }
1555:
1.298 matthew 1556: sub getsection {
1557: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1558: my $cachetime=1800;
1.551 albertel 1559:
1560: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1561: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1562: if (defined($cached)) { return $result; }
1563:
1.298 matthew 1564: my %Pending;
1565: my %Expired;
1566: #
1567: # Each role can either have not started yet (pending), be active,
1568: # or have expired.
1569: #
1570: # If there is an active role, we are done.
1571: #
1572: # If there is more than one role which has not started yet,
1573: # choose the one which will start sooner
1574: # If there is one role which has not started yet, return it.
1575: #
1576: # If there is more than one expired role, choose the one which ended last.
1577: # If there is a role which has expired, return it.
1578: #
1.815 albertel 1579: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1580: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1581: foreach my $key (keys(%roleshash)) {
1.479 albertel 1582: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1583: my $section=$1;
1584: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1585: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1586: my $now=time;
1.548 albertel 1587: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1588: $Expired{$end}=$section;
1589: next;
1590: }
1.548 albertel 1591: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1592: $Pending{$start}=$section;
1593: next;
1594: }
1.599 albertel 1595: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1596: }
1597: #
1598: # Presumedly there will be few matching roles from the above
1599: # loop and the sorting time will be negligible.
1600: if (scalar(keys(%Pending))) {
1601: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1602: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1603: }
1604: if (scalar(keys(%Expired))) {
1605: my @sorted = sort {$a <=> $b} keys(%Expired);
1606: my $time = pop(@sorted);
1.599 albertel 1607: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1608: }
1.599 albertel 1609: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1610: }
1.70 www 1611:
1.599 albertel 1612: sub save_cache {
1613: &purge_remembered();
1.722 albertel 1614: #&Apache::loncommon::validate_page();
1.620 albertel 1615: undef(%env);
1.780 albertel 1616: undef($env_loaded);
1.599 albertel 1617: }
1.452 albertel 1618:
1.599 albertel 1619: my $to_remember=-1;
1620: my %remembered;
1621: my %accessed;
1622: my $kicks=0;
1623: my $hits=0;
1.849 albertel 1624: sub make_key {
1625: my ($name,$id) = @_;
1.872 albertel 1626: if (length($id) > 65
1627: && length(&escape($id)) > 200) {
1628: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1629: }
1.849 albertel 1630: return &escape($name.':'.$id);
1631: }
1632:
1.599 albertel 1633: sub devalidate_cache_new {
1634: my ($name,$id,$debug) = @_;
1635: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1636: $id=&make_key($name,$id);
1.599 albertel 1637: $memcache->delete($id);
1638: delete($remembered{$id});
1639: delete($accessed{$id});
1640: }
1641:
1642: sub is_cached_new {
1643: my ($name,$id,$debug) = @_;
1.849 albertel 1644: $id=&make_key($name,$id);
1.599 albertel 1645: if (exists($remembered{$id})) {
1646: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1647: $accessed{$id}=[&gettimeofday()];
1648: $hits++;
1649: return ($remembered{$id},1);
1650: }
1651: my $value = $memcache->get($id);
1652: if (!(defined($value))) {
1653: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1654: return (undef,undef);
1.416 albertel 1655: }
1.599 albertel 1656: if ($value eq '__undef__') {
1657: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1658: $value=undef;
1659: }
1660: &make_room($id,$value,$debug);
1661: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1662: return ($value,1);
1663: }
1664:
1665: sub do_cache_new {
1666: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1667: $id=&make_key($name,$id);
1.599 albertel 1668: my $setvalue=$value;
1669: if (!defined($setvalue)) {
1670: $setvalue='__undef__';
1671: }
1.623 albertel 1672: if (!defined($time) ) {
1673: $time=600;
1674: }
1.599 albertel 1675: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1676: my $result = $memcache->set($id,$setvalue,$time);
1677: if (! $result) {
1.872 albertel 1678: &logthis("caching of id -> $id failed");
1.910 albertel 1679: $memcache->disconnect_all();
1.872 albertel 1680: }
1.600 albertel 1681: # need to make a copy of $value
1.919 albertel 1682: &make_room($id,$value,$debug);
1.599 albertel 1683: return $value;
1684: }
1685:
1686: sub make_room {
1687: my ($id,$value,$debug)=@_;
1.919 albertel 1688:
1689: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1690: : $value;
1.599 albertel 1691: if ($to_remember<0) { return; }
1692: $accessed{$id}=[&gettimeofday()];
1693: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1694: my $to_kick;
1695: my $max_time=0;
1696: foreach my $other (keys(%accessed)) {
1697: if (&tv_interval($accessed{$other}) > $max_time) {
1698: $to_kick=$other;
1699: $max_time=&tv_interval($accessed{$other});
1700: }
1701: }
1702: delete($remembered{$to_kick});
1703: delete($accessed{$to_kick});
1704: $kicks++;
1705: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1706: return;
1707: }
1708:
1.599 albertel 1709: sub purge_remembered {
1.604 albertel 1710: #&logthis("Tossing ".scalar(keys(%remembered)));
1711: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1712: undef(%remembered);
1713: undef(%accessed);
1.428 albertel 1714: }
1.70 www 1715: # ------------------------------------- Read an entry from a user's environment
1716:
1717: sub userenvironment {
1718: my ($udom,$unam,@what)=@_;
1.976 raeburn 1719: my $items;
1720: foreach my $item (@what) {
1721: $items.=&escape($item).'&';
1722: }
1723: $items=~s/\&$//;
1.70 www 1724: my %returnhash=();
1.1009 raeburn 1725: my $uhome = &homeserver($unam,$udom);
1726: unless ($uhome eq 'no_host') {
1727: my @answer=split(/\&/,
1728: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1729: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1730: return %returnhash;
1731: }
1.1009 raeburn 1732: my $i;
1733: for ($i=0;$i<=$#what;$i++) {
1734: $returnhash{$what[$i]}=&unescape($answer[$i]);
1735: }
1.70 www 1736: }
1737: return %returnhash;
1.1 albertel 1738: }
1739:
1.617 albertel 1740: # ---------------------------------------------------------- Get a studentphoto
1741: sub studentphoto {
1742: my ($udom,$unam,$ext) = @_;
1743: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1744: if (defined($env{'request.course.id'})) {
1.708 raeburn 1745: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1746: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1747: return(&retrievestudentphoto($udom,$unam,$ext));
1748: } else {
1749: my ($result,$perm_reqd)=
1.707 albertel 1750: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1751: if ($result eq 'ok') {
1752: if (!($perm_reqd eq 'yes')) {
1753: return(&retrievestudentphoto($udom,$unam,$ext));
1754: }
1755: }
1756: }
1757: }
1758: } else {
1759: my ($result,$perm_reqd) =
1.707 albertel 1760: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1761: if ($result eq 'ok') {
1762: if (!($perm_reqd eq 'yes')) {
1763: return(&retrievestudentphoto($udom,$unam,$ext));
1764: }
1765: }
1766: }
1767: return '/adm/lonKaputt/lonlogo_broken.gif';
1768: }
1769:
1770: sub retrievestudentphoto {
1771: my ($udom,$unam,$ext,$type) = @_;
1772: my $home=&Apache::lonnet::homeserver($unam,$udom);
1773: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1774: if ($ret eq 'ok') {
1775: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1776: if ($type eq 'thumbnail') {
1777: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1778: }
1779: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1780: return $tokenurl;
1781: } else {
1782: if ($type eq 'thumbnail') {
1783: return '/adm/lonKaputt/genericstudent_tn.gif';
1784: } else {
1785: return '/adm/lonKaputt/lonlogo_broken.gif';
1786: }
1.617 albertel 1787: }
1788: }
1789:
1.263 www 1790: # -------------------------------------------------------------------- New chat
1791:
1792: sub chatsend {
1.724 raeburn 1793: my ($newentry,$anon,$group)=@_;
1.620 albertel 1794: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1795: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1796: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1797: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1798: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1799: &escape($newentry)).':'.$group,$chome);
1.292 www 1800: }
1801:
1802: # ------------------------------------------ Find current version of a resource
1803:
1804: sub getversion {
1805: my $fname=&clutter(shift);
1806: unless ($fname=~/^\/res\//) { return -1; }
1807: return ¤tversion(&filelocation('',$fname));
1808: }
1809:
1810: sub currentversion {
1811: my $fname=shift;
1.599 albertel 1812: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1813: if (defined($cached)) { return $result; }
1.292 www 1814: my $author=$fname;
1815: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1816: my ($udom,$uname)=split(/\//,$author);
1817: my $home=homeserver($uname,$udom);
1818: if ($home eq 'no_host') {
1819: return -1;
1820: }
1821: my $answer=reply("currentversion:$fname",$home);
1822: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1823: return -1;
1824: }
1.599 albertel 1825: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1826: }
1827:
1.1 albertel 1828: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1829:
1.1 albertel 1830: sub subscribe {
1831: my $fname=shift;
1.761 raeburn 1832: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1833: $fname=~s/[\n\r]//g;
1.1 albertel 1834: my $author=$fname;
1835: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1836: my ($udom,$uname)=split(/\//,$author);
1837: my $home=homeserver($uname,$udom);
1.335 albertel 1838: if ($home eq 'no_host') {
1839: return 'not_found';
1.1 albertel 1840: }
1841: my $answer=reply("sub:$fname",$home);
1.64 www 1842: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1843: $answer.=' by '.$home;
1844: }
1.1 albertel 1845: return $answer;
1846: }
1847:
1.8 www 1848: # -------------------------------------------------------------- Replicate file
1849:
1850: sub repcopy {
1851: my $filename=shift;
1.23 www 1852: $filename=~s/\/+/\//g;
1.607 raeburn 1853: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1854: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1855: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1856: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1857: return &repcopy_userfile($filename);
1858: }
1.532 albertel 1859: $filename=~s/[\n\r]//g;
1.8 www 1860: my $transname="$filename.in.transfer";
1.828 www 1861: # FIXME: this should flock
1.607 raeburn 1862: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1863: my $remoteurl=subscribe($filename);
1.64 www 1864: if ($remoteurl =~ /^con_lost by/) {
1865: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1866: return 'unavailable';
1.8 www 1867: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1868: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1869: return 'not_found';
1.64 www 1870: } elsif ($remoteurl =~ /^rejected by/) {
1871: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1872: return 'forbidden';
1.20 www 1873: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1874: return 'ok';
1.8 www 1875: } else {
1.290 www 1876: my $author=$filename;
1877: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1878: my ($udom,$uname)=split(/\//,$author);
1879: my $home=homeserver($uname,$udom);
1880: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1881: my @parts=split(/\//,$filename);
1882: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1883: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1884: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1885: return 'bad_request';
1.8 www 1886: }
1887: my $count;
1888: for ($count=5;$count<$#parts;$count++) {
1889: $path.="/$parts[$count]";
1890: if ((-e $path)!=1) {
1891: mkdir($path,0777);
1892: }
1893: }
1894: my $ua=new LWP::UserAgent;
1895: my $request=new HTTP::Request('GET',"$remoteurl");
1896: my $response=$ua->request($request,$transname);
1897: if ($response->is_error()) {
1898: unlink($transname);
1899: my $message=$response->status_line;
1.672 albertel 1900: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1901: ." LWP get: $message: $filename</font>");
1.607 raeburn 1902: return 'unavailable';
1.8 www 1903: } else {
1.16 www 1904: if ($remoteurl!~/\.meta$/) {
1905: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1906: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1907: if ($mresponse->is_error()) {
1908: unlink($filename.'.meta');
1909: &logthis(
1.672 albertel 1910: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1911: }
1912: }
1.8 www 1913: rename($transname,$filename);
1.607 raeburn 1914: return 'ok';
1.8 www 1915: }
1.290 www 1916: }
1.8 www 1917: }
1.330 www 1918: }
1919:
1920: # ------------------------------------------------ Get server side include body
1921: sub ssi_body {
1.381 albertel 1922: my ($filelink,%form)=@_;
1.606 matthew 1923: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1924: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1925: }
1.953 www 1926: my $output='';
1927: my $response;
1.980 raeburn 1928: if ($filelink=~/^https?\:/) {
1.954 raeburn 1929: ($output,$response)=&externalssi($filelink);
1.953 www 1930: } else {
1.1004 droeschl 1931: $filelink .= $filelink=~/\?/ ? '&' : '?';
1932: $filelink .= 'inhibitmenu=yes';
1.953 www 1933: ($output,$response)=&ssi($filelink,%form);
1934: }
1.778 albertel 1935: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1936: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1937: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1938: if (wantarray) {
1939: return ($output, $response);
1940: } else {
1941: return $output;
1942: }
1.8 www 1943: }
1944:
1.15 www 1945: # --------------------------------------------------------- Server Side Include
1946:
1.782 albertel 1947: sub absolute_url {
1948: my ($host_name) = @_;
1949: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1950: if ($host_name eq '') {
1951: $host_name = $ENV{'SERVER_NAME'};
1952: }
1953: return $protocol.$host_name;
1954: }
1955:
1.942 foxr 1956: #
1957: # Server side include.
1958: # Parameters:
1959: # fn Possibly encrypted resource name/id.
1960: # form Hash that describes how the rendering should be done
1961: # and other things.
1.944 foxr 1962: # Returns:
1.950 raeburn 1963: # Scalar context: The content of the response.
1964: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1965: #
1.15 www 1966: sub ssi {
1967:
1.944 foxr 1968: my ($fn,%form)=@_;
1.15 www 1969: my $ua=new LWP::UserAgent;
1.23 www 1970: my $request;
1.711 albertel 1971:
1972: $form{'no_update_last_known'}=1;
1.895 albertel 1973: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1974: if (%form) {
1.782 albertel 1975: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 1976: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 1977: } else {
1.782 albertel 1978: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1979: }
1980:
1.15 www 1981: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1982: my $response=$ua->request($request);
1983:
1.944 foxr 1984: if (wantarray) {
1985: return ($response->content, $response);
1986: } else {
1987: return $response->content;
1.942 foxr 1988: }
1.324 www 1989: }
1990:
1991: sub externalssi {
1992: my ($url)=@_;
1993: my $ua=new LWP::UserAgent;
1994: my $request=new HTTP::Request('GET',$url);
1995: my $response=$ua->request($request);
1.954 raeburn 1996: if (wantarray) {
1997: return ($response->content, $response);
1998: } else {
1999: return $response->content;
2000: }
1.15 www 2001: }
1.254 www 2002:
1.492 albertel 2003: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2004:
2005: sub allowuploaded {
2006: my ($srcurl,$url)=@_;
2007: $url=&clutter(&declutter($url));
2008: my $dir=$url;
2009: $dir=~s/\/[^\/]+$//;
2010: my %httpref=();
2011: my $httpurl=&hreflocation('',$url);
2012: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2013: &Apache::lonnet::appenv(\%httpref);
1.254 www 2014: }
1.477 raeburn 2015:
1.478 albertel 2016: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2017: # input: action, courseID, current domain, intended
1.637 raeburn 2018: # path to file, source of file, instruction to parse file for objects,
2019: # ref to hash for embedded objects,
2020: # ref to hash for codebase of java objects.
2021: #
1.485 raeburn 2022: # output: url to file (if action was uploaddoc),
2023: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2024: #
1.478 albertel 2025: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2026: # course.
1.477 raeburn 2027: #
1.478 albertel 2028: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2029: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2030: # course's home server.
1.477 raeburn 2031: #
1.478 albertel 2032: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2033: # be copied from $source (current location) to
2034: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2035: # and will then be copied to
2036: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2037: # course's home server.
1.485 raeburn 2038: #
1.481 raeburn 2039: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2040: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2041: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2042: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2043: # in course's home server.
1.637 raeburn 2044: #
1.477 raeburn 2045:
2046: sub process_coursefile {
1.638 albertel 2047: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2048: my $fetchresult;
1.638 albertel 2049: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2050: if ($action eq 'propagate') {
1.638 albertel 2051: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2052: $home);
1.481 raeburn 2053: } else {
1.477 raeburn 2054: my $fpath = '';
2055: my $fname = $file;
1.478 albertel 2056: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2057: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2058: my $filepath = &build_filepath($fpath);
1.481 raeburn 2059: if ($action eq 'copy') {
2060: if ($source eq '') {
2061: $fetchresult = 'no source file';
2062: return $fetchresult;
2063: } else {
2064: my $destination = $filepath.'/'.$fname;
2065: rename($source,$destination);
2066: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2067: $home);
1.481 raeburn 2068: }
2069: } elsif ($action eq 'uploaddoc') {
2070: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2071: print $fh $env{'form.'.$source};
1.481 raeburn 2072: close($fh);
1.637 raeburn 2073: if ($parser eq 'parse') {
1.1024 raeburn 2074: my $mm = new File::MMagic;
2075: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2076: if ($mime_type eq 'text/html') {
2077: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2078: unless ($parse_result eq 'ok') {
2079: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2080: }
1.637 raeburn 2081: }
2082: }
1.477 raeburn 2083: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2084: $home);
1.481 raeburn 2085: if ($fetchresult eq 'ok') {
2086: return '/uploaded/'.$fpath.'/'.$fname;
2087: } else {
2088: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2089: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2090: return '/adm/notfound.html';
2091: }
1.477 raeburn 2092: }
2093: }
1.485 raeburn 2094: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2095: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2096: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2097: }
2098: return $fetchresult;
2099: }
2100:
1.637 raeburn 2101: sub build_filepath {
2102: my ($fpath) = @_;
2103: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2104: unless ($fpath eq '') {
2105: my @parts=split('/',$fpath);
2106: foreach my $part (@parts) {
2107: $filepath.= '/'.$part;
2108: if ((-e $filepath)!=1) {
2109: mkdir($filepath,0777);
2110: }
2111: }
2112: }
2113: return $filepath;
2114: }
2115:
2116: sub store_edited_file {
1.638 albertel 2117: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2118: my $file = $primary_url;
2119: $file =~ s#^/uploaded/$docudom/$docuname/##;
2120: my $fpath = '';
2121: my $fname = $file;
2122: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2123: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2124: my $filepath = &build_filepath($fpath);
2125: open(my $fh,'>'.$filepath.'/'.$fname);
2126: print $fh $content;
2127: close($fh);
1.638 albertel 2128: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2129: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2130: $home);
1.637 raeburn 2131: if ($$fetchresult eq 'ok') {
2132: return '/uploaded/'.$fpath.'/'.$fname;
2133: } else {
1.638 albertel 2134: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2135: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2136: return '/adm/notfound.html';
2137: }
2138: }
2139:
1.531 albertel 2140: sub clean_filename {
1.831 albertel 2141: my ($fname,$args)=@_;
1.315 www 2142: # Replace Windows backslashes by forward slashes
1.257 www 2143: $fname=~s/\\/\//g;
1.831 albertel 2144: if (!$args->{'keep_path'}) {
2145: # Get rid of everything but the actual filename
2146: $fname=~s/^.*\/([^\/]+)$/$1/;
2147: }
1.315 www 2148: # Replace spaces by underscores
2149: $fname=~s/\s+/\_/g;
2150: # Replace all other weird characters by nothing
1.831 albertel 2151: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2152: # Replace all .\d. sequences with _\d. so they no longer look like version
2153: # numbers
2154: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2155: return $fname;
2156: }
1.1051 raeburn 2157: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2158: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2159: # image with the same aspect ratio as the original, but with dimensions which do
2160: # not exceed $resizewidth and $resizeheight.
2161:
1.984 neumanie 2162: sub resizeImage {
1.1051 raeburn 2163: my ($img_path,$resizewidth,$resizeheight) = @_;
2164: my $ima = Image::Magick->new;
2165: my $resized;
2166: if (-e $img_path) {
2167: $ima->Read($img_path);
2168: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2169: my $width = $ima->Get('width');
2170: my $height = $ima->Get('height');
2171: if ($width > $resizewidth) {
2172: my $factor = $width/$resizewidth;
2173: my $newheight = $height/$factor;
2174: $ima->Scale(width=>$resizewidth,height=>$newheight);
2175: $resized = 1;
2176: }
2177: }
2178: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2179: my $width = $ima->Get('width');
2180: my $height = $ima->Get('height');
2181: if ($height > $resizeheight) {
2182: my $factor = $height/$resizeheight;
2183: my $newwidth = $width/$factor;
2184: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2185: $resized = 1;
2186: }
2187: }
2188: if ($resized) {
2189: $ima->Write($img_path);
2190: }
2191: }
2192: return;
1.977 amueller 2193: }
2194:
1.608 albertel 2195: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2196: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2197: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2198: # $coursedoc - if true up to the current course
2199: # if false
2200: # $subdir - directory in userfile to store the file into
1.858 raeburn 2201: # $parser - instruction to parse file for objects ($parser = parse)
2202: # $allfiles - reference to hash for embedded objects
2203: # $codebase - reference to hash for codebase of java objects
2204: # $desuname - username for permanent storage of uploaded file
2205: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2206: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2207: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2208: # $resizewidth - width (pixels) to which to resize uploaded image
2209: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2210: #
1.686 albertel 2211: # output: url of file in userspace, or error: <message>
2212: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2213:
1.531 albertel 2214: sub userfileupload {
1.860 raeburn 2215: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2216: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2217: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2218: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2219: $fname=&clean_filename($fname);
1.315 www 2220: # See if there is anything left
1.257 www 2221: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2222: chop($env{'form.'.$formname});
1.523 raeburn 2223: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2224: my $now = time;
2225: my $filepath = 'tmp/helprequests/'.$now;
2226: my @parts=split(/\//,$filepath);
2227: my $fullpath = $perlvar{'lonDaemons'};
2228: for (my $i=0;$i<@parts;$i++) {
2229: $fullpath .= '/'.$parts[$i];
2230: if ((-e $fullpath)!=1) {
2231: mkdir($fullpath,0777);
2232: }
2233: }
2234: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2235: print $fh $env{'form.'.$formname};
1.523 raeburn 2236: close($fh);
1.741 raeburn 2237: return $fullpath.'/'.$fname;
2238: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2239: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2240: '_'.$env{'user.domain'}.'/pending';
2241: my @parts=split(/\//,$filepath);
2242: my $fullpath = $perlvar{'lonDaemons'};
2243: for (my $i=0;$i<@parts;$i++) {
2244: $fullpath .= '/'.$parts[$i];
2245: if ((-e $fullpath)!=1) {
2246: mkdir($fullpath,0777);
2247: }
2248: }
2249: open(my $fh,'>'.$fullpath.'/'.$fname);
2250: print $fh $env{'form.'.$formname};
2251: close($fh);
2252: return $fullpath.'/'.$fname;
1.523 raeburn 2253: }
1.995 raeburn 2254: if ($subdir eq 'scantron') {
2255: $fname = 'scantron_orig_'.$fname;
2256: } else {
1.258 www 2257: # Create the directory if not present
1.995 raeburn 2258: $fname="$subdir/$fname";
2259: }
1.259 www 2260: if ($coursedoc) {
1.638 albertel 2261: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2262: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2263: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2264: return &finishuserfileupload($docuname,$docudom,
2265: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2266: $codebase,$thumbwidth,$thumbheight,
2267: $resizewidth,$resizeheight);
1.481 raeburn 2268: } else {
1.620 albertel 2269: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2270: return &process_coursefile('uploaddoc',$docuname,$docudom,
2271: $fname,$formname,$parser,
2272: $allfiles,$codebase);
1.481 raeburn 2273: }
1.719 banghart 2274: } elsif (defined($destuname)) {
2275: my $docuname=$destuname;
2276: my $docudom=$destudom;
1.860 raeburn 2277: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2278: $parser,$allfiles,$codebase,
1.1051 raeburn 2279: $thumbwidth,$thumbheight,
2280: $resizewidth,$resizeheight);
1.719 banghart 2281:
1.259 www 2282: } else {
1.638 albertel 2283: my $docuname=$env{'user.name'};
2284: my $docudom=$env{'user.domain'};
1.714 raeburn 2285: if (exists($env{'form.group'})) {
2286: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2287: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2288: }
1.860 raeburn 2289: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2290: $parser,$allfiles,$codebase,
1.1051 raeburn 2291: $thumbwidth,$thumbheight,
2292: $resizewidth,$resizeheight);
1.259 www 2293: }
1.271 www 2294: }
2295:
2296: sub finishuserfileupload {
1.860 raeburn 2297: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2298: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2299: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2300: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2301:
1.860 raeburn 2302: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2303: $file=$fname;
2304: if ($fname=~m|/|) {
2305: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2306: $path.=$fnamepath.'/';
2307: }
1.259 www 2308: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2309: my $count;
2310: for ($count=4;$count<=$#parts;$count++) {
2311: $filepath.="/$parts[$count]";
2312: if ((-e $filepath)!=1) {
2313: mkdir($filepath,0777);
2314: }
2315: }
1.984 neumanie 2316:
1.258 www 2317: # Save the file
2318: {
1.701 albertel 2319: if (!open(FH,'>'.$filepath.'/'.$file)) {
2320: &logthis('Failed to create '.$filepath.'/'.$file);
2321: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2322: return '/adm/notfound.html';
2323: }
2324: if (!print FH ($env{'form.'.$formname})) {
2325: &logthis('Failed to write to '.$filepath.'/'.$file);
2326: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2327: return '/adm/notfound.html';
2328: }
1.570 albertel 2329: close(FH);
1.1051 raeburn 2330: if ($resizewidth && $resizeheight) {
2331: my $mm = new File::MMagic;
2332: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2333: if ($mime_type =~ m{^image/}) {
2334: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2335: }
1.977 amueller 2336: }
1.258 www 2337: }
1.637 raeburn 2338: if ($parser eq 'parse') {
1.1024 raeburn 2339: my $mm = new File::MMagic;
2340: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2341: if ($mime_type eq 'text/html') {
2342: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2343: $allfiles,$codebase);
2344: unless ($parse_result eq 'ok') {
2345: &logthis('Failed to parse '.$filepath.$file.
2346: ' for embedded media: '.$parse_result);
2347: }
1.637 raeburn 2348: }
2349: }
1.860 raeburn 2350: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2351: my $input = $filepath.'/'.$file;
2352: my $output = $filepath.'/'.'tn-'.$file;
2353: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2354: system("convert -sample $thumbsize $input $output");
2355: if (-e $filepath.'/'.'tn-'.$file) {
2356: $fetchthumb = 1;
2357: }
2358: }
1.858 raeburn 2359:
1.259 www 2360: # Notify homeserver to grep it
2361: #
1.984 neumanie 2362: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2363: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2364: if ($fetchresult eq 'ok') {
1.860 raeburn 2365: if ($fetchthumb) {
2366: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2367: if ($thumbresult ne 'ok') {
2368: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2369: $docuhome.': '.$thumbresult);
2370: }
2371: }
1.259 www 2372: #
1.258 www 2373: # Return the URL to it
1.494 albertel 2374: return '/uploaded/'.$path.$file;
1.263 www 2375: } else {
1.494 albertel 2376: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2377: ': '.$fetchresult);
1.263 www 2378: return '/adm/notfound.html';
1.858 raeburn 2379: }
1.493 albertel 2380: }
2381:
1.637 raeburn 2382: sub extract_embedded_items {
1.961 raeburn 2383: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2384: my @state = ();
2385: my %javafiles = (
2386: codebase => '',
2387: code => '',
2388: archive => ''
2389: );
2390: my %mediafiles = (
2391: src => '',
2392: movie => '',
2393: );
1.648 raeburn 2394: my $p;
2395: if ($content) {
2396: $p = HTML::LCParser->new($content);
2397: } else {
1.961 raeburn 2398: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2399: }
1.641 albertel 2400: while (my $t=$p->get_token()) {
1.640 albertel 2401: if ($t->[0] eq 'S') {
2402: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2403: push(@state, $tagname);
1.648 raeburn 2404: if (lc($tagname) eq 'allow') {
2405: &add_filetype($allfiles,$attr->{'src'},'src');
2406: }
1.640 albertel 2407: if (lc($tagname) eq 'img') {
2408: &add_filetype($allfiles,$attr->{'src'},'src');
2409: }
1.886 albertel 2410: if (lc($tagname) eq 'a') {
2411: &add_filetype($allfiles,$attr->{'href'},'href');
2412: }
1.645 raeburn 2413: if (lc($tagname) eq 'script') {
2414: if ($attr->{'archive'} =~ /\.jar$/i) {
2415: &add_filetype($allfiles,$attr->{'archive'},'archive');
2416: } else {
2417: &add_filetype($allfiles,$attr->{'src'},'src');
2418: }
2419: }
2420: if (lc($tagname) eq 'link') {
2421: if (lc($attr->{'rel'}) eq 'stylesheet') {
2422: &add_filetype($allfiles,$attr->{'href'},'href');
2423: }
2424: }
1.640 albertel 2425: if (lc($tagname) eq 'object' ||
2426: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2427: foreach my $item (keys(%javafiles)) {
2428: $javafiles{$item} = '';
2429: }
2430: }
2431: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2432: my $name = lc($attr->{'name'});
2433: foreach my $item (keys(%javafiles)) {
2434: if ($name eq $item) {
2435: $javafiles{$item} = $attr->{'value'};
2436: last;
2437: }
2438: }
2439: foreach my $item (keys(%mediafiles)) {
2440: if ($name eq $item) {
2441: &add_filetype($allfiles, $attr->{'value'}, 'value');
2442: last;
2443: }
2444: }
2445: }
2446: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2447: foreach my $item (keys(%javafiles)) {
2448: if ($attr->{$item}) {
2449: $javafiles{$item} = $attr->{$item};
2450: last;
2451: }
2452: }
2453: foreach my $item (keys(%mediafiles)) {
2454: if ($attr->{$item}) {
2455: &add_filetype($allfiles,$attr->{$item},$item);
2456: last;
2457: }
2458: }
2459: }
2460: } elsif ($t->[0] eq 'E') {
2461: my ($tagname) = ($t->[1]);
2462: if ($javafiles{'codebase'} ne '') {
2463: $javafiles{'codebase'} .= '/';
2464: }
2465: if (lc($tagname) eq 'applet' ||
2466: lc($tagname) eq 'object' ||
2467: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2468: ) {
2469: foreach my $item (keys(%javafiles)) {
2470: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2471: my $file=$javafiles{'codebase'}.$javafiles{$item};
2472: &add_filetype($allfiles,$file,$item);
2473: }
2474: }
2475: }
2476: pop @state;
2477: }
2478: }
1.637 raeburn 2479: return 'ok';
2480: }
2481:
1.639 albertel 2482: sub add_filetype {
2483: my ($allfiles,$file,$type)=@_;
2484: if (exists($allfiles->{$file})) {
2485: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2486: push(@{$allfiles->{$file}}, &escape($type));
2487: }
2488: } else {
2489: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2490: }
2491: }
2492:
1.493 albertel 2493: sub removeuploadedurl {
1.984 neumanie 2494: my ($url)=@_;
2495: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2496: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2497: }
2498:
2499: sub removeuserfile {
2500: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2501: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2502: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2503: if ($result eq 'ok') {
1.798 raeburn 2504: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2505: my $metafile = $fname.'.meta';
2506: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2507: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2508: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2509: my $sqlresult =
1.823 albertel 2510: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2511: 'portfolio_metadata',$group,
2512: 'delete');
1.798 raeburn 2513: }
2514: }
2515: return $result;
1.257 www 2516: }
1.15 www 2517:
1.530 albertel 2518: sub mkdiruserfile {
2519: my ($docuname,$docudom,$dir)=@_;
2520: my $home=&homeserver($docuname,$docudom);
2521: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2522: }
2523:
1.531 albertel 2524: sub renameuserfile {
2525: my ($docuname,$docudom,$old,$new)=@_;
2526: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2527: my $result = &reply("renameuserfile:$docudom:$docuname:".
2528: &escape("$old").':'.&escape("$new"),$home);
2529: if ($result eq 'ok') {
2530: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2531: my $oldmeta = $old.'.meta';
2532: my $newmeta = $new.'.meta';
2533: my $metaresult =
2534: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2535: my $url = "/uploaded/$docudom/$docuname/$old";
2536: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2537: my $sqlresult =
1.823 albertel 2538: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2539: 'portfolio_metadata',$group,
2540: 'delete');
1.798 raeburn 2541: }
2542: }
2543: return $result;
1.531 albertel 2544: }
2545:
1.14 www 2546: # ------------------------------------------------------------------------- Log
2547:
2548: sub log {
2549: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2550: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2551: }
2552:
2553: # ------------------------------------------------------------------ Course Log
1.352 www 2554: #
2555: # This routine flushes several buffers of non-mission-critical nature
2556: #
1.157 www 2557:
2558: sub flushcourselogs {
1.352 www 2559: &logthis('Flushing log buffers');
2560: #
2561: # course logs
2562: # This is a log of all transactions in a course, which can be used
2563: # for data mining purposes
2564: #
2565: # It also collects the courseid database, which lists last transaction
2566: # times and course titles for all courseids
2567: #
2568: my %courseidbuffer=();
1.921 raeburn 2569: foreach my $crsid (keys(%courselogs)) {
1.352 www 2570: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2571: &escape($courselogs{$crsid}),
2572: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2573: delete $courselogs{$crsid};
2574: } else {
2575: &logthis('Failed to flush log buffer for '.$crsid);
2576: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2577: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2578: " exceeded maximum size, deleting.</font>");
2579: delete $courselogs{$crsid};
2580: }
1.352 www 2581: }
1.920 raeburn 2582: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2583: 'description' => $coursedescrbuf{$crsid},
2584: 'inst_code' => $courseinstcodebuf{$crsid},
2585: 'type' => $coursetypebuf{$crsid},
2586: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2587: };
1.191 harris41 2588: }
1.352 www 2589: #
2590: # Write course id database (reverse lookup) to homeserver of courses
2591: # Is used in pickcourse
2592: #
1.840 albertel 2593: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2594: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2595: $courseidbuffer{$crs_home},
2596: $crs_home,'timeonly');
1.352 www 2597: }
2598: #
2599: # File accesses
2600: # Writes to the dynamic metadata of resources to get hit counts, etc.
2601: #
1.449 matthew 2602: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2603: if ($entry =~ /___count$/) {
2604: my ($dom,$name);
1.807 albertel 2605: ($dom,$name,undef)=
1.811 albertel 2606: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2607: if (! defined($dom) || $dom eq '' ||
2608: ! defined($name) || $name eq '') {
1.620 albertel 2609: my $cid = $env{'request.course.id'};
2610: $dom = $env{'request.'.$cid.'.domain'};
2611: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2612: }
1.450 matthew 2613: my $value = $accesshash{$entry};
2614: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2615: my %temphash=($url => $value);
1.449 matthew 2616: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2617: if ($result eq 'ok') {
2618: delete $accesshash{$entry};
2619: } elsif ($result eq 'unknown_cmd') {
2620: # Target server has old code running on it.
1.450 matthew 2621: my %temphash=($entry => $value);
1.449 matthew 2622: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2623: delete $accesshash{$entry};
2624: }
2625: }
2626: } else {
1.811 albertel 2627: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2628: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2629: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2630: delete $accesshash{$entry};
2631: }
1.185 www 2632: }
1.191 harris41 2633: }
1.352 www 2634: #
2635: # Roles
2636: # Reverse lookup of user roles for course faculty/staff and co-authorship
2637: #
1.800 albertel 2638: foreach my $entry (keys(%userrolehash)) {
1.351 www 2639: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2640: split(/\:/,$entry);
2641: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2642: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2643: $rudom,$runame) eq 'ok') {
2644: delete $userrolehash{$entry};
2645: }
2646: }
1.662 raeburn 2647: #
2648: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2649: #
2650: my %domrolebuffer = ();
1.1000 raeburn 2651: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2652: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2653: if ($domrolebuffer{$rudom}) {
2654: $domrolebuffer{$rudom}.='&'.&escape($entry).
2655: '='.&escape($domainrolehash{$entry});
2656: } else {
2657: $domrolebuffer{$rudom}.=&escape($entry).
2658: '='.&escape($domainrolehash{$entry});
2659: }
2660: delete $domainrolehash{$entry};
2661: }
2662: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2663: my %servers = &get_servers($dom,'library');
2664: foreach my $tryserver (keys(%servers)) {
2665: unless (&reply('domroleput:'.$dom.':'.
2666: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2667: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2668: }
1.662 raeburn 2669: }
2670: }
1.186 www 2671: $dumpcount++;
1.157 www 2672: }
2673:
2674: sub courselog {
2675: my $what=shift;
1.158 www 2676: $what=time.':'.$what;
1.620 albertel 2677: unless ($env{'request.course.id'}) { return ''; }
2678: $coursedombuf{$env{'request.course.id'}}=
2679: $env{'course.'.$env{'request.course.id'}.'.domain'};
2680: $coursenumbuf{$env{'request.course.id'}}=
2681: $env{'course.'.$env{'request.course.id'}.'.num'};
2682: $coursehombuf{$env{'request.course.id'}}=
2683: $env{'course.'.$env{'request.course.id'}.'.home'};
2684: $coursedescrbuf{$env{'request.course.id'}}=
2685: $env{'course.'.$env{'request.course.id'}.'.description'};
2686: $courseinstcodebuf{$env{'request.course.id'}}=
2687: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2688: $courseownerbuf{$env{'request.course.id'}}=
2689: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2690: $coursetypebuf{$env{'request.course.id'}}=
2691: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2692: if (defined $courselogs{$env{'request.course.id'}}) {
2693: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2694: } else {
1.620 albertel 2695: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2696: }
1.620 albertel 2697: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2698: &flushcourselogs();
2699: }
1.158 www 2700: }
2701:
2702: sub courseacclog {
2703: my $fnsymb=shift;
1.620 albertel 2704: unless ($env{'request.course.id'}) { return ''; }
2705: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2706: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2707: $what.=':POST';
1.583 matthew 2708: # FIXME: Probably ought to escape things....
1.800 albertel 2709: foreach my $key (keys(%env)) {
2710: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2711: my $formitem = $1;
2712: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2713: $what.=':'.$formitem.'='.$env{$key};
2714: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2715: $what.=':'.$formitem.'='.$env{$key};
2716: }
1.158 www 2717: }
1.191 harris41 2718: }
1.583 matthew 2719: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2720: # FIXME: We should not be depending on a form parameter that someone
2721: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2722: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2723: $what.= ':POST';
2724: # FIXME: Probably ought to escape things....
2725: foreach my $element ('courseexp','crsfulltext','crsrelated',
2726: 'crsdiscuss') {
1.620 albertel 2727: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2728: }
2729: }
1.158 www 2730: }
2731: &courselog($what);
1.149 www 2732: }
2733:
1.185 www 2734: sub countacc {
2735: my $url=&declutter(shift);
1.458 matthew 2736: return if (! defined($url) || $url eq '');
1.620 albertel 2737: unless ($env{'request.course.id'}) { return ''; }
2738: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2739: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2740: $accesshash{$key}++;
1.185 www 2741: }
1.349 www 2742:
1.361 www 2743: sub linklog {
2744: my ($from,$to)=@_;
2745: $from=&declutter($from);
2746: $to=&declutter($to);
2747: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2748: $accesshash{$to.'___'.$from.'___goto'}=1;
2749: }
2750:
1.349 www 2751: sub userrolelog {
2752: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2753: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2754: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2755: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2756: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2757: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2758: $userrolehash
2759: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2760: =$tend.':'.$tstart;
1.662 raeburn 2761: }
1.898 albertel 2762: if (($env{'request.role'} =~ /dc\./) &&
2763: (($trole=~/^au/) || ($trole=~/^in/) ||
2764: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2765: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2766: ($trole=~/^co/))) {
1.898 albertel 2767: $userrolehash
2768: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2769: =$tend.':'.$tstart;
2770: }
1.662 raeburn 2771: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2772: ($trole=~/^li/) || ($trole=~/^li/) ||
2773: ($trole=~/^au/) || ($trole=~/^dg/) ||
2774: ($trole=~/^sc/)) {
2775: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2776: $domainrolehash
2777: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2778: = $tend.':'.$tstart;
2779: }
1.351 www 2780: }
2781:
1.957 raeburn 2782: sub courserolelog {
2783: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2784: if (($trole eq 'cc') || ($trole eq 'in') ||
2785: ($trole eq 'ep') || ($trole eq 'ad') ||
2786: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2787: ($trole=~/^cr/) || ($trole eq 'gr') ||
2788: ($trole eq 'co')) {
1.957 raeburn 2789: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2790: my $cdom = $1;
2791: my $cnum = $2;
2792: my $sec = $3;
2793: my $namespace = 'rolelog';
2794: my %storehash = (
2795: role => $trole,
2796: start => $tstart,
2797: end => $tend,
2798: selfenroll => $selfenroll,
2799: context => $context,
2800: );
2801: if ($trole eq 'gr') {
2802: $namespace = 'groupslog';
2803: $storehash{'group'} = $sec;
2804: } else {
2805: $storehash{'section'} = $sec;
2806: }
2807: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2808: if (($trole ne 'st') || ($sec ne '')) {
2809: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2810: }
1.957 raeburn 2811: }
2812: }
2813: return;
2814: }
2815:
1.351 www 2816: sub get_course_adv_roles {
1.948 raeburn 2817: my ($cid,$codes) = @_;
1.620 albertel 2818: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2819: my %coursehash=&coursedescription($cid);
1.988 raeburn 2820: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2821: my %nothide=();
1.800 albertel 2822: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2823: if ($user !~ /:/) {
2824: $nothide{join(':',split(/[\@]/,$user))}=1;
2825: } else {
2826: $nothide{$user}=1;
2827: }
1.470 www 2828: }
1.351 www 2829: my %returnhash=();
2830: my %dumphash=
2831: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2832: my $now=time;
1.997 raeburn 2833: my %privileged;
1.1000 raeburn 2834: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2835: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2836: if (($tstart) && ($tstart<0)) { next; }
2837: if (($tend) && ($tend<$now)) { next; }
2838: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2839: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2840: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2841: unless (ref($privileged{$domain}) eq 'HASH') {
2842: my %dompersonnel =
1.998 raeburn 2843: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2844: $privileged{$domain} = {};
2845: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2846: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2847: foreach my $user (keys(%{$dompersonnel{$server}})) {
2848: my ($trole,$uname,$udom) = split(/:/,$user);
2849: $privileged{$udom}{$uname} = 1;
2850: }
2851: }
2852: }
2853: }
2854: if ((exists($privileged{$domain}{$username})) &&
2855: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2856: if ($role eq 'cr') { next; }
1.948 raeburn 2857: if ($codes) {
2858: if ($section) { $role .= ':'.$section; }
2859: if ($returnhash{$role}) {
2860: $returnhash{$role}.=','.$username.':'.$domain;
2861: } else {
2862: $returnhash{$role}=$username.':'.$domain;
2863: }
1.351 www 2864: } else {
1.988 raeburn 2865: my $key=&plaintext($role,$crstype);
1.973 bisitz 2866: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2867: if ($returnhash{$key}) {
2868: $returnhash{$key}.=','.$username.':'.$domain;
2869: } else {
2870: $returnhash{$key}=$username.':'.$domain;
2871: }
1.351 www 2872: }
1.948 raeburn 2873: }
1.400 www 2874: return %returnhash;
2875: }
2876:
2877: sub get_my_roles {
1.937 raeburn 2878: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2879: unless (defined($uname)) { $uname=$env{'user.name'}; }
2880: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2881: my (%dumphash,%nothide);
1.858 raeburn 2882: if ($context eq 'userroles') {
2883: %dumphash = &dump('roles',$udom,$uname);
2884: } else {
2885: %dumphash=
1.400 www 2886: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2887: if ($hidepriv) {
2888: my %coursehash=&coursedescription($udom.'_'.$uname);
2889: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2890: if ($user !~ /:/) {
2891: $nothide{join(':',split(/[\@]/,$user))} = 1;
2892: } else {
2893: $nothide{$user} = 1;
2894: }
2895: }
2896: }
1.858 raeburn 2897: }
1.400 www 2898: my %returnhash=();
2899: my $now=time;
1.999 raeburn 2900: my %privileged;
1.800 albertel 2901: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2902: my ($role,$tend,$tstart);
2903: if ($context eq 'userroles') {
2904: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2905: } else {
2906: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2907: }
1.400 www 2908: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2909: my $status = 'active';
1.939 raeburn 2910: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2911: $status = 'previous';
2912: }
2913: if (($tstart) && ($now<$tstart)) {
2914: $status = 'future';
2915: }
2916: if (ref($types) eq 'ARRAY') {
2917: if (!grep(/^\Q$status\E$/,@{$types})) {
2918: next;
2919: }
2920: } else {
2921: if ($status ne 'active') {
2922: next;
2923: }
2924: }
1.867 raeburn 2925: my ($rolecode,$username,$domain,$section,$area);
2926: if ($context eq 'userroles') {
2927: ($area,$rolecode) = split(/_/,$entry);
2928: (undef,$domain,$username,$section) = split(/\//,$area);
2929: } else {
2930: ($role,$username,$domain,$section) = split(/\:/,$entry);
2931: }
1.832 raeburn 2932: if (ref($roledoms) eq 'ARRAY') {
2933: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2934: next;
2935: }
2936: }
2937: if (ref($roles) eq 'ARRAY') {
2938: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2939: if ($role =~ /^cr\//) {
2940: if (!grep(/^cr$/,@{$roles})) {
2941: next;
2942: }
2943: } else {
2944: next;
2945: }
1.832 raeburn 2946: }
1.867 raeburn 2947: }
1.937 raeburn 2948: if ($hidepriv) {
1.999 raeburn 2949: if ($context eq 'userroles') {
2950: if ((&privileged($username,$domain)) &&
2951: (!$nothide{$username.':'.$domain})) {
2952: next;
2953: }
2954: } else {
2955: unless (ref($privileged{$domain}) eq 'HASH') {
2956: my %dompersonnel =
2957: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2958: $privileged{$domain} = {};
2959: if (keys(%dompersonnel)) {
2960: foreach my $server (keys(%dompersonnel)) {
2961: if (ref($dompersonnel{$server}) eq 'HASH') {
2962: foreach my $user (keys(%{$dompersonnel{$server}})) {
2963: my ($trole,$uname,$udom) = split(/:/,$user);
2964: $privileged{$udom}{$uname} = $trole;
2965: }
2966: }
2967: }
2968: }
2969: }
2970: if (exists($privileged{$domain}{$username})) {
2971: if (!$nothide{$username.':'.$domain}) {
2972: next;
2973: }
2974: }
1.937 raeburn 2975: }
2976: }
1.933 raeburn 2977: if ($withsec) {
2978: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2979: $tstart.':'.$tend;
2980: } else {
2981: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2982: }
1.832 raeburn 2983: }
1.373 www 2984: return %returnhash;
1.399 www 2985: }
2986:
2987: # ----------------------------------------------------- Frontpage Announcements
2988: #
2989: #
2990:
2991: sub postannounce {
2992: my ($server,$text)=@_;
1.844 albertel 2993: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2994: unless ($text=~/\w/) { $text=''; }
2995: return &reply('setannounce:'.&escape($text),$server);
2996: }
2997:
2998: sub getannounce {
1.448 albertel 2999:
3000: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3001: my $announcement='';
1.800 albertel 3002: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3003: close($fh);
1.399 www 3004: if ($announcement=~/\w/) {
3005: return
3006: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3007: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3008: } else {
3009: return '';
3010: }
3011: } else {
3012: return '';
3013: }
1.351 www 3014: }
1.353 www 3015:
3016: # ---------------------------------------------------------- Course ID routines
3017: # Deal with domain's nohist_courseid.db files
3018: #
3019:
3020: sub courseidput {
1.921 raeburn 3021: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3022: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3023: my $outcome;
3024: if ($caller eq 'timeonly') {
3025: my $cids = '';
3026: foreach my $item (keys(%$storehash)) {
3027: $cids.=&escape($item).'&';
3028: }
3029: $cids=~s/\&$//;
3030: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3031: $coursehome);
3032: } else {
3033: my $items = '';
3034: foreach my $item (keys(%$storehash)) {
3035: $items.= &escape($item).'='.
3036: &freeze_escape($$storehash{$item}).'&';
3037: }
3038: $items=~s/\&$//;
3039: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3040: $coursehome);
1.918 raeburn 3041: }
3042: if ($outcome eq 'unknown_cmd') {
3043: my $what;
3044: foreach my $cid (keys(%$storehash)) {
3045: $what .= &escape($cid).'=';
1.921 raeburn 3046: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3047: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3048: }
3049: $what =~ s/\:$/&/;
3050: }
3051: $what =~ s/\&$//;
3052: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3053: } else {
3054: return $outcome;
3055: }
1.353 www 3056: }
3057:
3058: sub courseiddump {
1.921 raeburn 3059: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3060: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3061: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3062: $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
1.918 raeburn 3063: my $as_hash = 1;
3064: my %returnhash;
3065: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3066: my %libserv = &all_library();
3067: foreach my $tryserver (keys(%libserv)) {
3068: if ( ( $hostidflag == 1
3069: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3070: || (!defined($hostidflag)) ) {
3071:
1.918 raeburn 3072: if (($domfilter eq '') ||
3073: (&host_domain($tryserver) eq $domfilter)) {
3074: my $rep =
3075: &reply('courseiddump:'.&host_domain($tryserver).':'.
3076: $sincefilter.':'.&escape($descfilter).':'.
3077: &escape($instcodefilter).':'.&escape($ownerfilter).
3078: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3079: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3080: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3081: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3082: &escape($cc_clone).':'.$cloneonly.':'.
3083: &escape($createdbefore).':'.&escape($createdafter).':'.
3084: &escape($creationcontext),$tryserver);
1.918 raeburn 3085: my @pairs=split(/\&/,$rep);
3086: foreach my $item (@pairs) {
3087: my ($key,$value)=split(/\=/,$item,2);
3088: $key = &unescape($key);
3089: next if ($key =~ /^error: 2 /);
3090: my $result = &thaw_unescape($value);
3091: if (ref($result) eq 'HASH') {
3092: $returnhash{$key}=$result;
3093: } else {
1.921 raeburn 3094: my @responses = split(/:/,$value);
3095: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3096: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3097: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3098: }
1.1008 raeburn 3099: }
1.353 www 3100: }
3101: }
3102: }
3103: }
3104: return %returnhash;
3105: }
3106:
1.1055 raeburn 3107: sub courselastaccess {
3108: my ($cdom,$cnum,$hostidref) = @_;
3109: my %returnhash;
3110: if ($cdom && $cnum) {
3111: my $chome = &homeserver($cnum,$cdom);
3112: if ($chome ne 'no_host') {
3113: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3114: &extract_lastaccess(\%returnhash,$rep);
3115: }
3116: } else {
3117: if (!$cdom) { $cdom=''; }
3118: my %libserv = &all_library();
3119: foreach my $tryserver (keys(%libserv)) {
3120: if (ref($hostidref) eq 'ARRAY') {
3121: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3122: }
3123: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3124: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3125: &extract_lastaccess(\%returnhash,$rep);
3126: }
3127: }
3128: }
3129: return %returnhash;
3130: }
3131:
3132: sub extract_lastaccess {
3133: my ($returnhash,$rep) = @_;
3134: if (ref($returnhash) eq 'HASH') {
3135: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3136: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3137: $rep eq '') {
3138: my @pairs=split(/\&/,$rep);
3139: foreach my $item (@pairs) {
3140: my ($key,$value)=split(/\=/,$item,2);
3141: $key = &unescape($key);
3142: next if ($key =~ /^error: 2 /);
3143: $returnhash->{$key} = &thaw_unescape($value);
3144: }
3145: }
3146: }
3147: return;
3148: }
3149:
1.658 raeburn 3150: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3151:
3152: sub dcmailput {
1.685 raeburn 3153: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3154: my $status = &Apache::lonnet::critical(
1.740 www 3155: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3156: &escape($message),$server);
1.662 raeburn 3157: return $status;
3158: }
3159:
1.658 raeburn 3160: sub dcmaildump {
3161: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3162: my %returnhash=();
1.846 albertel 3163:
3164: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3165: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3166: &escape($enddate).':';
3167: my @esc_senders=map { &escape($_)} @$senders;
3168: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3169: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3170: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3171: if (($key) && ($value)) {
3172: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3173: }
3174: }
3175: }
3176: return %returnhash;
3177: }
1.662 raeburn 3178: # ---------------------------------------------------------- Domain roles
3179:
3180: sub get_domain_roles {
3181: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3182: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3183: $startdate = '.';
3184: }
1.1018 raeburn 3185: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3186: $enddate = '.';
3187: }
1.922 raeburn 3188: my $rolelist;
3189: if (ref($roles) eq 'ARRAY') {
3190: $rolelist = join(':',@{$roles});
3191: }
1.662 raeburn 3192: my %personnel = ();
1.841 albertel 3193:
3194: my %servers = &get_servers($dom,'library');
3195: foreach my $tryserver (keys(%servers)) {
3196: %{$personnel{$tryserver}}=();
3197: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3198: &escape($startdate).':'.
3199: &escape($enddate).':'.
3200: &escape($rolelist), $tryserver))) {
3201: my ($key,$value) = split(/\=/,$line,2);
3202: if (($key) && ($value)) {
3203: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3204: }
3205: }
1.662 raeburn 3206: }
3207: return %personnel;
3208: }
1.658 raeburn 3209:
1.1057 www 3210: # ----------------------------------------------------------- Interval timing
1.149 www 3211:
1.504 albertel 3212: sub get_first_access {
3213: my ($type,$argsymb)=@_;
1.790 albertel 3214: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3215: if ($argsymb) { $symb=$argsymb; }
3216: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3217: if ($type eq 'course') {
3218: $res='course';
3219: } elsif ($type eq 'map') {
1.588 albertel 3220: $res=&symbread($map);
3221: } else {
3222: $res=$symb;
3223: }
3224: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3225: return $times{"$courseid\0$res"};
1.504 albertel 3226: }
3227:
3228: sub set_first_access {
3229: my ($type)=@_;
1.790 albertel 3230: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3231: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3232: if ($type eq 'course') {
3233: $res='course';
3234: } elsif ($type eq 'map') {
1.588 albertel 3235: $res=&symbread($map);
3236: } else {
3237: $res=$symb;
3238: }
3239: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3240: if (!$firstaccess) {
1.588 albertel 3241: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3242: }
3243: return 'already_set';
1.504 albertel 3244: }
3245:
1.110 www 3246: # --------------------------------------------- Set Expire Date for Spreadsheet
3247:
3248: sub expirespread {
3249: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3250: my $cid=$env{'request.course.id'};
1.110 www 3251: if ($cid) {
3252: my $now=time;
3253: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3254: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3255: $env{'course.'.$cid.'.num'}.
1.110 www 3256: ':nohist_expirationdates:'.
3257: &escape($key).'='.$now,
1.620 albertel 3258: $env{'course.'.$cid.'.home'})
1.110 www 3259: }
3260: return 'ok';
1.14 www 3261: }
3262:
1.109 www 3263: # ----------------------------------------------------- Devalidate Spreadsheets
3264:
3265: sub devalidate {
1.325 www 3266: my ($symb,$uname,$udom)=@_;
1.620 albertel 3267: my $cid=$env{'request.course.id'};
1.109 www 3268: if ($cid) {
1.391 matthew 3269: # delete the stored spreadsheets for
3270: # - the student level sheet of this user in course's homespace
3271: # - the assessment level sheet for this resource
3272: # for this user in user's homespace
1.553 albertel 3273: # - current conditional state info
1.325 www 3274: my $key=$uname.':'.$udom.':';
1.109 www 3275: my $status=
1.299 matthew 3276: &del('nohist_calculatedsheets',
1.391 matthew 3277: [$key.'studentcalc:'],
1.620 albertel 3278: $env{'course.'.$cid.'.domain'},
3279: $env{'course.'.$cid.'.num'})
1.133 albertel 3280: .' '.
3281: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3282: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3283: unless ($status eq 'ok ok') {
3284: &logthis('Could not devalidate spreadsheet '.
1.325 www 3285: $uname.' at '.$udom.' for '.
1.109 www 3286: $symb.': '.$status);
1.133 albertel 3287: }
1.553 albertel 3288: &delenv('user.state.'.$cid);
1.109 www 3289: }
3290: }
3291:
1.265 albertel 3292: sub get_scalar {
3293: my ($string,$end) = @_;
3294: my $value;
3295: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3296: $value = $1;
3297: } elsif ($$string =~ s/^([^&]*?)&//) {
3298: $value = $1;
3299: }
3300: return &unescape($value);
3301: }
3302:
3303: sub array2str {
3304: my (@array) = @_;
3305: my $result=&arrayref2str(\@array);
3306: $result=~s/^__ARRAY_REF__//;
3307: $result=~s/__END_ARRAY_REF__$//;
3308: return $result;
3309: }
3310:
1.204 albertel 3311: sub arrayref2str {
3312: my ($arrayref) = @_;
1.265 albertel 3313: my $result='__ARRAY_REF__';
1.204 albertel 3314: foreach my $elem (@$arrayref) {
1.265 albertel 3315: if(ref($elem) eq 'ARRAY') {
3316: $result.=&arrayref2str($elem).'&';
3317: } elsif(ref($elem) eq 'HASH') {
3318: $result.=&hashref2str($elem).'&';
3319: } elsif(ref($elem)) {
3320: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3321: } else {
3322: $result.=&escape($elem).'&';
3323: }
3324: }
3325: $result=~s/\&$//;
1.265 albertel 3326: $result .= '__END_ARRAY_REF__';
1.204 albertel 3327: return $result;
3328: }
3329:
1.168 albertel 3330: sub hash2str {
1.204 albertel 3331: my (%hash) = @_;
3332: my $result=&hashref2str(\%hash);
1.265 albertel 3333: $result=~s/^__HASH_REF__//;
3334: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3335: return $result;
3336: }
3337:
3338: sub hashref2str {
3339: my ($hashref)=@_;
1.265 albertel 3340: my $result='__HASH_REF__';
1.800 albertel 3341: foreach my $key (sort(keys(%$hashref))) {
3342: if (ref($key) eq 'ARRAY') {
3343: $result.=&arrayref2str($key).'=';
3344: } elsif (ref($key) eq 'HASH') {
3345: $result.=&hashref2str($key).'=';
3346: } elsif (ref($key)) {
1.265 albertel 3347: $result.='=';
1.800 albertel 3348: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3349: } else {
1.800 albertel 3350: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3351: }
3352:
1.800 albertel 3353: if(ref($hashref->{$key}) eq 'ARRAY') {
3354: $result.=&arrayref2str($hashref->{$key}).'&';
3355: } elsif(ref($hashref->{$key}) eq 'HASH') {
3356: $result.=&hashref2str($hashref->{$key}).'&';
3357: } elsif(ref($hashref->{$key})) {
1.265 albertel 3358: $result.='&';
1.800 albertel 3359: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3360: } else {
1.800 albertel 3361: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3362: }
3363: }
1.168 albertel 3364: $result=~s/\&$//;
1.265 albertel 3365: $result .= '__END_HASH_REF__';
1.168 albertel 3366: return $result;
3367: }
3368:
3369: sub str2hash {
1.265 albertel 3370: my ($string)=@_;
3371: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3372: return %$hash;
3373: }
3374:
3375: sub str2hashref {
1.168 albertel 3376: my ($string) = @_;
1.265 albertel 3377:
3378: my %hash;
3379:
3380: if($string !~ /^__HASH_REF__/) {
3381: if (! ($string eq '' || !defined($string))) {
3382: $hash{'error'}='Not hash reference';
3383: }
3384: return (\%hash, $string);
3385: }
3386:
3387: $string =~ s/^__HASH_REF__//;
3388:
3389: while($string !~ /^__END_HASH_REF__/) {
3390: #key
3391: my $key='';
3392: if($string =~ /^__HASH_REF__/) {
3393: ($key, $string)=&str2hashref($string);
3394: if(defined($key->{'error'})) {
3395: $hash{'error'}='Bad data';
3396: return (\%hash, $string);
3397: }
3398: } elsif($string =~ /^__ARRAY_REF__/) {
3399: ($key, $string)=&str2arrayref($string);
3400: if($key->[0] eq 'Array reference error') {
3401: $hash{'error'}='Bad data';
3402: return (\%hash, $string);
3403: }
3404: } else {
3405: $string =~ s/^(.*?)=//;
1.267 albertel 3406: $key=&unescape($1);
1.265 albertel 3407: }
3408: $string =~ s/^=//;
3409:
3410: #value
3411: my $value='';
3412: if($string =~ /^__HASH_REF__/) {
3413: ($value, $string)=&str2hashref($string);
3414: if(defined($value->{'error'})) {
3415: $hash{'error'}='Bad data';
3416: return (\%hash, $string);
3417: }
3418: } elsif($string =~ /^__ARRAY_REF__/) {
3419: ($value, $string)=&str2arrayref($string);
3420: if($value->[0] eq 'Array reference error') {
3421: $hash{'error'}='Bad data';
3422: return (\%hash, $string);
3423: }
3424: } else {
3425: $value=&get_scalar(\$string,'__END_HASH_REF__');
3426: }
3427: $string =~ s/^&//;
3428:
3429: $hash{$key}=$value;
1.204 albertel 3430: }
1.265 albertel 3431:
3432: $string =~ s/^__END_HASH_REF__//;
3433:
3434: return (\%hash, $string);
1.204 albertel 3435: }
3436:
3437: sub str2array {
1.265 albertel 3438: my ($string)=@_;
3439: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3440: return @$array;
3441: }
3442:
3443: sub str2arrayref {
1.204 albertel 3444: my ($string) = @_;
1.265 albertel 3445: my @array;
3446:
3447: if($string !~ /^__ARRAY_REF__/) {
3448: if (! ($string eq '' || !defined($string))) {
3449: $array[0]='Array reference error';
3450: }
3451: return (\@array, $string);
3452: }
3453:
3454: $string =~ s/^__ARRAY_REF__//;
3455:
3456: while($string !~ /^__END_ARRAY_REF__/) {
3457: my $value='';
3458: if($string =~ /^__HASH_REF__/) {
3459: ($value, $string)=&str2hashref($string);
3460: if(defined($value->{'error'})) {
3461: $array[0] ='Array reference error';
3462: return (\@array, $string);
3463: }
3464: } elsif($string =~ /^__ARRAY_REF__/) {
3465: ($value, $string)=&str2arrayref($string);
3466: if($value->[0] eq 'Array reference error') {
3467: $array[0] ='Array reference error';
3468: return (\@array, $string);
3469: }
3470: } else {
3471: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3472: }
3473: $string =~ s/^&//;
3474:
3475: push(@array, $value);
1.191 harris41 3476: }
1.265 albertel 3477:
3478: $string =~ s/^__END_ARRAY_REF__//;
3479:
3480: return (\@array, $string);
1.168 albertel 3481: }
3482:
1.167 albertel 3483: # -------------------------------------------------------------------Temp Store
3484:
1.168 albertel 3485: sub tmpreset {
3486: my ($symb,$namespace,$domain,$stuname) = @_;
3487: if (!$symb) {
3488: $symb=&symbread();
1.620 albertel 3489: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3490: }
3491: $symb=escape($symb);
3492:
1.620 albertel 3493: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3494: $namespace=~s/\//\_/g;
3495: $namespace=~s/\W//g;
3496:
1.620 albertel 3497: if (!$domain) { $domain=$env{'user.domain'}; }
3498: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3499: if ($domain eq 'public' && $stuname eq 'public') {
3500: $stuname=$ENV{'REMOTE_ADDR'};
3501: }
1.168 albertel 3502: my $path=$perlvar{'lonDaemons'}.'/tmp';
3503: my %hash;
3504: if (tie(%hash,'GDBM_File',
3505: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3506: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3507: foreach my $key (keys(%hash)) {
1.180 albertel 3508: if ($key=~ /:$symb/) {
1.168 albertel 3509: delete($hash{$key});
3510: }
3511: }
3512: }
3513: }
3514:
1.167 albertel 3515: sub tmpstore {
1.168 albertel 3516: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3517:
3518: if (!$symb) {
3519: $symb=&symbread();
1.620 albertel 3520: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3521: }
3522: $symb=escape($symb);
3523:
3524: if (!$namespace) {
3525: # I don't think we would ever want to store this for a course.
3526: # it seems this will only be used if we don't have a course.
1.620 albertel 3527: #$namespace=$env{'request.course.id'};
1.168 albertel 3528: #if (!$namespace) {
1.620 albertel 3529: $namespace=$env{'request.state'};
1.168 albertel 3530: #}
3531: }
3532: $namespace=~s/\//\_/g;
3533: $namespace=~s/\W//g;
1.620 albertel 3534: if (!$domain) { $domain=$env{'user.domain'}; }
3535: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3536: if ($domain eq 'public' && $stuname eq 'public') {
3537: $stuname=$ENV{'REMOTE_ADDR'};
3538: }
1.168 albertel 3539: my $now=time;
3540: my %hash;
3541: my $path=$perlvar{'lonDaemons'}.'/tmp';
3542: if (tie(%hash,'GDBM_File',
3543: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3544: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3545: $hash{"version:$symb"}++;
3546: my $version=$hash{"version:$symb"};
3547: my $allkeys='';
3548: foreach my $key (keys(%$storehash)) {
3549: $allkeys.=$key.':';
1.591 albertel 3550: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3551: }
3552: $hash{"$version:$symb:timestamp"}=$now;
3553: $allkeys.='timestamp';
3554: $hash{"$version:keys:$symb"}=$allkeys;
3555: if (untie(%hash)) {
3556: return 'ok';
3557: } else {
3558: return "error:$!";
3559: }
3560: } else {
3561: return "error:$!";
3562: }
3563: }
1.167 albertel 3564:
1.168 albertel 3565: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3566:
1.168 albertel 3567: sub tmprestore {
3568: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3569:
1.168 albertel 3570: if (!$symb) {
3571: $symb=&symbread();
1.620 albertel 3572: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3573: }
3574: $symb=escape($symb);
3575:
1.620 albertel 3576: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3577:
1.620 albertel 3578: if (!$domain) { $domain=$env{'user.domain'}; }
3579: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3580: if ($domain eq 'public' && $stuname eq 'public') {
3581: $stuname=$ENV{'REMOTE_ADDR'};
3582: }
1.168 albertel 3583: my %returnhash;
3584: $namespace=~s/\//\_/g;
3585: $namespace=~s/\W//g;
3586: my %hash;
3587: my $path=$perlvar{'lonDaemons'}.'/tmp';
3588: if (tie(%hash,'GDBM_File',
3589: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3590: &GDBM_READER(),0640)) {
1.168 albertel 3591: my $version=$hash{"version:$symb"};
3592: $returnhash{'version'}=$version;
3593: my $scope;
3594: for ($scope=1;$scope<=$version;$scope++) {
3595: my $vkeys=$hash{"$scope:keys:$symb"};
3596: my @keys=split(/:/,$vkeys);
3597: my $key;
3598: $returnhash{"$scope:keys"}=$vkeys;
3599: foreach $key (@keys) {
1.591 albertel 3600: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3601: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3602: }
3603: }
1.168 albertel 3604: if (!(untie(%hash))) {
3605: return "error:$!";
3606: }
3607: } else {
3608: return "error:$!";
3609: }
3610: return %returnhash;
1.167 albertel 3611: }
3612:
1.9 www 3613: # ----------------------------------------------------------------------- Store
3614:
3615: sub store {
1.124 www 3616: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3617: my $home='';
3618:
1.168 albertel 3619: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3620:
1.213 www 3621: $symb=&symbclean($symb);
1.122 albertel 3622: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3623:
1.620 albertel 3624: if (!$domain) { $domain=$env{'user.domain'}; }
3625: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3626:
3627: &devalidate($symb,$stuname,$domain);
1.109 www 3628:
3629: $symb=escape($symb);
1.187 www 3630: if (!$namespace) {
1.620 albertel 3631: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3632: return '';
3633: }
3634: }
1.620 albertel 3635: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3636:
3637: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3638: $$storehash{'host'}=$perlvar{'lonHostID'};
3639:
1.12 www 3640: my $namevalue='';
1.800 albertel 3641: foreach my $key (keys(%$storehash)) {
3642: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3643: }
1.12 www 3644: $namevalue=~s/\&$//;
1.187 www 3645: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3646: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3647: }
3648:
1.47 www 3649: # -------------------------------------------------------------- Critical Store
3650:
3651: sub cstore {
1.124 www 3652: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3653: my $home='';
3654:
1.168 albertel 3655: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3656:
1.213 www 3657: $symb=&symbclean($symb);
1.122 albertel 3658: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3659:
1.620 albertel 3660: if (!$domain) { $domain=$env{'user.domain'}; }
3661: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3662:
3663: &devalidate($symb,$stuname,$domain);
1.109 www 3664:
3665: $symb=escape($symb);
1.187 www 3666: if (!$namespace) {
1.620 albertel 3667: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3668: return '';
3669: }
3670: }
1.620 albertel 3671: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3672:
3673: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3674: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3675:
1.47 www 3676: my $namevalue='';
1.800 albertel 3677: foreach my $key (keys(%$storehash)) {
3678: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3679: }
1.47 www 3680: $namevalue=~s/\&$//;
1.187 www 3681: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3682: return critical
3683: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3684: }
3685:
1.9 www 3686: # --------------------------------------------------------------------- Restore
3687:
3688: sub restore {
1.124 www 3689: my ($symb,$namespace,$domain,$stuname) = @_;
3690: my $home='';
3691:
1.168 albertel 3692: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3693:
1.122 albertel 3694: if (!$symb) {
3695: unless ($symb=escape(&symbread())) { return ''; }
3696: } else {
1.213 www 3697: $symb=&escape(&symbclean($symb));
1.122 albertel 3698: }
1.188 www 3699: if (!$namespace) {
1.620 albertel 3700: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3701: return '';
3702: }
3703: }
1.620 albertel 3704: if (!$domain) { $domain=$env{'user.domain'}; }
3705: if (!$stuname) { $stuname=$env{'user.name'}; }
3706: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3707: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3708:
1.12 www 3709: my %returnhash=();
1.800 albertel 3710: foreach my $line (split(/\&/,$answer)) {
3711: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3712: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3713: }
1.75 www 3714: my $version;
3715: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3716: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3717: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3718: }
1.75 www 3719: }
1.13 www 3720: return %returnhash;
1.34 www 3721: }
3722:
3723: # ---------------------------------------------------------- Course Description
3724:
3725: sub coursedescription {
1.731 albertel 3726: my ($courseid,$args)=@_;
1.34 www 3727: $courseid=~s/^\///;
1.49 www 3728: $courseid=~s/\_/\//g;
1.34 www 3729: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3730: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3731: my $normalid=$cdomain.'_'.$cnum;
3732: # need to always cache even if we get errors otherwise we keep
3733: # trying and trying and trying to get the course description.
3734: my %envhash=();
3735: my %returnhash=();
1.731 albertel 3736:
3737: my $expiretime=600;
3738: if ($env{'request.course.id'} eq $normalid) {
3739: $expiretime=120;
3740: }
3741:
3742: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3743: if (!$args->{'freshen_cache'}
3744: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3745: foreach my $key (keys(%env)) {
3746: next if ($key !~ /^\Q$prefix\E(.*)/);
3747: my ($setting) = $1;
3748: $returnhash{$setting} = $env{$key};
3749: }
3750: return %returnhash;
3751: }
3752:
3753: # get the data agin
3754: if (!$args->{'one_time'}) {
3755: $envhash{'course.'.$normalid.'.last_cache'}=time;
3756: }
1.811 albertel 3757:
1.34 www 3758: if ($chome ne 'no_host') {
1.302 albertel 3759: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3760: if (!exists($returnhash{'con_lost'})) {
3761: $returnhash{'home'}= $chome;
3762: $returnhash{'domain'} = $cdomain;
3763: $returnhash{'num'} = $cnum;
1.741 raeburn 3764: if (!defined($returnhash{'type'})) {
3765: $returnhash{'type'} = 'Course';
3766: }
1.130 albertel 3767: while (my ($name,$value) = each %returnhash) {
1.53 www 3768: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3769: }
1.270 www 3770: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3771: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3772: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3773: $envhash{'course.'.$normalid.'.home'}=$chome;
3774: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3775: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3776: }
3777: }
1.731 albertel 3778: if (!$args->{'one_time'}) {
1.949 raeburn 3779: &appenv(\%envhash);
1.731 albertel 3780: }
1.302 albertel 3781: return %returnhash;
1.461 www 3782: }
3783:
3784: # -------------------------------------------------See if a user is privileged
3785:
3786: sub privileged {
3787: my ($username,$domain)=@_;
3788: my $rolesdump=&reply("dump:$domain:$username:roles",
3789: &homeserver($username,$domain));
1.1033 raeburn 3790: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3791: ($rolesdump =~ /^error:/)) {
3792: return 0;
3793: }
1.461 www 3794: my $now=time;
3795: if ($rolesdump ne '') {
1.800 albertel 3796: foreach my $entry (split(/&/,$rolesdump)) {
3797: if ($entry!~/^rolesdef_/) {
3798: my ($area,$role)=split(/=/,$entry);
1.461 www 3799: $area=~s/\_\w\w$//;
3800: my ($trole,$tend,$tstart)=split(/_/,$role);
3801: if (($trole eq 'dc') || ($trole eq 'su')) {
3802: my $active=1;
3803: if ($tend) {
3804: if ($tend<$now) { $active=0; }
3805: }
3806: if ($tstart) {
3807: if ($tstart>$now) { $active=0; }
3808: }
3809: if ($active) { return 1; }
3810: }
3811: }
3812: }
3813: }
3814: return 0;
1.9 www 3815: }
1.1 albertel 3816:
1.103 harris41 3817: # -------------------------------------------------------- Get user privileges
1.11 www 3818:
3819: sub rolesinit {
3820: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 3821: my $now=time;
3822: my %userroles = ('user.login.time' => $now);
1.11 www 3823: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033 raeburn 3824: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3825: ($rolesdump =~ /^error:/)) {
3826: return \%userroles;
3827: }
1.11 www 3828: my %allroles=();
1.678 raeburn 3829: my %allgroups=();
3830: my $group_privs;
1.11 www 3831:
3832: if ($rolesdump ne '') {
1.800 albertel 3833: foreach my $entry (split(/&/,$rolesdump)) {
3834: if ($entry!~/^rolesdef_/) {
3835: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3836: $area=~s/\_\w\w$//;
1.678 raeburn 3837: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3838: if ($role=~/^cr/) {
1.807 albertel 3839: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3840: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3841: ($tend,$tstart)=split('_',$trest);
3842: } else {
3843: $trole=$role;
3844: }
1.678 raeburn 3845: } elsif ($role =~ m|^gr/|) {
3846: ($trole,$tend,$tstart) = split(/_/,$role);
3847: ($trole,$group_privs) = split(/\//,$trole);
3848: $group_privs = &unescape($group_privs);
1.587 albertel 3849: } else {
3850: ($trole,$tend,$tstart)=split(/_/,$role);
3851: }
1.743 albertel 3852: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3853: $username);
3854: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3855: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3856: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3857: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3858: my $spec=$trole.'.'.$area;
3859: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3860: if ($trole =~ /^cr\//) {
1.567 raeburn 3861: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3862: } elsif ($trole eq 'gr') {
3863: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3864: } else {
1.567 raeburn 3865: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3866: }
1.12 www 3867: }
1.662 raeburn 3868: }
1.191 harris41 3869: }
1.743 albertel 3870: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3871: $userroles{'user.adv'} = $adv;
3872: $userroles{'user.author'} = $author;
1.620 albertel 3873: $env{'user.adv'}=$adv;
1.11 www 3874: }
1.743 albertel 3875: return \%userroles;
1.11 www 3876: }
3877:
1.567 raeburn 3878: sub set_arearole {
3879: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3880: # log the associated role with the area
3881: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3882: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3883: }
3884:
3885: sub custom_roleprivs {
3886: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3887: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3888: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3889: if (&hostname($homsvr) ne '') {
1.567 raeburn 3890: my ($rdummy,$roledef)=
3891: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3892: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3893: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3894: if (defined($syspriv)) {
1.1043 raeburn 3895: if ($trest =~ /^$match_community$/) {
3896: $syspriv =~ s/bre\&S//;
3897: }
1.567 raeburn 3898: $$allroles{'cm./'}.=':'.$syspriv;
3899: $$allroles{$spec.'./'}.=':'.$syspriv;
3900: }
3901: if ($tdomain ne '') {
3902: if (defined($dompriv)) {
3903: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3904: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3905: }
3906: if (($trest ne '') && (defined($coursepriv))) {
3907: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3908: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3909: }
3910: }
3911: }
3912: }
3913: }
3914:
1.678 raeburn 3915: sub group_roleprivs {
3916: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3917: my $access = 1;
3918: my $now = time;
3919: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3920: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3921: if ($access) {
1.811 albertel 3922: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3923: $$allgroups{$course}{$group} .=':'.$group_privs;
3924: }
3925: }
1.567 raeburn 3926:
3927: sub standard_roleprivs {
3928: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3929: if (defined($pr{$trole.':s'})) {
3930: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3931: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3932: }
3933: if ($tdomain ne '') {
3934: if (defined($pr{$trole.':d'})) {
3935: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3936: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3937: }
3938: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3939: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3940: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3941: }
3942: }
3943: }
3944:
3945: sub set_userprivs {
1.678 raeburn 3946: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3947: my $author=0;
3948: my $adv=0;
1.678 raeburn 3949: my %grouproles = ();
3950: if (keys(%{$allgroups}) > 0) {
1.1000 raeburn 3951: foreach my $role (keys(%{$allroles})) {
1.681 raeburn 3952: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3953: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3954: $trole = $1;
3955: $area = $2;
1.681 raeburn 3956: $sec = $3;
3957: $extendedarea = $area.$sec;
3958: if (exists($$allgroups{$area})) {
3959: foreach my $group (keys(%{$$allgroups{$area}})) {
3960: my $spec = $trole.'.'.$extendedarea;
3961: $grouproles{$spec.'.'.$area.'/'.$group} =
3962: $$allgroups{$area}{$group};
1.678 raeburn 3963: }
3964: }
3965: }
3966: }
3967: }
1.800 albertel 3968: foreach my $group (keys(%grouproles)) {
3969: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3970: }
1.800 albertel 3971: foreach my $role (keys(%{$allroles})) {
3972: my %thesepriv;
1.941 raeburn 3973: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3974: foreach my $item (split(/:/,$$allroles{$role})) {
3975: if ($item ne '') {
3976: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3977: if ($restrictions eq '') {
3978: $thesepriv{$privilege}='F';
3979: } elsif ($thesepriv{$privilege} ne 'F') {
3980: $thesepriv{$privilege}.=$restrictions;
3981: }
3982: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3983: }
3984: }
3985: my $thesestr='';
1.800 albertel 3986: foreach my $priv (keys(%thesepriv)) {
3987: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3988: }
3989: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3990: }
3991: return ($author,$adv);
3992: }
3993:
1.994 raeburn 3994: sub role_status {
1.1002 raeburn 3995: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 3996: my @pwhere = ();
3997: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
3998: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
3999: unless (!defined($$role) || $$role eq '') {
4000: $$where=join('.',@pwhere);
4001: $$trolecode=$$role.'.'.$$where;
4002: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4003: $$tstatus='is';
4004: if ($$tstart && $$tstart>$then) {
4005: $$tstatus='future';
1.1034 raeburn 4006: if ($$tstart<$now) {
4007: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4008: if (($$where ne '') && ($$role ne '')) {
4009: my (%allroles,%allgroups,$group_privs);
4010: my %userroles = (
4011: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4012: );
4013: my $spec=$$role.'.'.$$where;
4014: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4015: if ($$role =~ /^cr\//) {
4016: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4017: } elsif ($$role eq 'gr') {
4018: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4019: $env{'user.name'});
4020: my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
4021: (undef,my $group_privs) = split(/\//,$trole);
4022: $group_privs = &unescape($group_privs);
4023: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4024: } else {
4025: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4026: }
4027: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
4028: &appenv(\%userroles,[$$role,'cm']);
4029: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4030: }
4031: }
1.1034 raeburn 4032: $$tstatus = 'is';
1.1002 raeburn 4033: }
1.994 raeburn 4034: }
4035: if ($$tend) {
4036: if ($$tend<$then) {
4037: $$tstatus='expired';
4038: } elsif ($$tend<$now) {
4039: $$tstatus='will_not';
4040: }
4041: }
4042: }
4043: }
4044: }
4045:
4046: sub check_adhoc_privs {
1.1002 raeburn 4047: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4048: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4049: if ($env{$cckey}) {
4050: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4051: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4052: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4053: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4054: }
4055: } else {
4056: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4057: }
4058: }
4059:
4060: sub set_adhoc_privileges {
4061: # role can be cc or ca
4062: my ($dcdom,$pickedcourse,$role) = @_;
4063: my $area = '/'.$dcdom.'/'.$pickedcourse;
4064: my $spec = $role.'.'.$area;
4065: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4066: $env{'user.name'});
4067: my %ccrole = ();
4068: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4069: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4070: &appenv(\%userroles,[$role,'cm']);
4071: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4072: &appenv( {'request.role' => $spec,
4073: 'request.role.domain' => $dcdom,
4074: 'request.course.sec' => ''
4075: }
4076: );
4077: my $tadv=0;
4078: if (&allowed('adv') eq 'F') { $tadv=1; }
4079: &appenv({'request.role.adv' => $tadv});
4080: }
4081:
1.12 www 4082: # --------------------------------------------------------------- get interface
4083:
4084: sub get {
1.131 albertel 4085: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4086: my $items='';
1.800 albertel 4087: foreach my $item (@$storearr) {
4088: $items.=&escape($item).'&';
1.191 harris41 4089: }
1.12 www 4090: $items=~s/\&$//;
1.620 albertel 4091: if (!$udomain) { $udomain=$env{'user.domain'}; }
4092: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4093: my $uhome=&homeserver($uname,$udomain);
4094:
1.133 albertel 4095: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4096: my @pairs=split(/\&/,$rep);
1.273 albertel 4097: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4098: return @pairs;
4099: }
1.15 www 4100: my %returnhash=();
1.42 www 4101: my $i=0;
1.800 albertel 4102: foreach my $item (@$storearr) {
4103: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4104: $i++;
1.191 harris41 4105: }
1.15 www 4106: return %returnhash;
1.27 www 4107: }
4108:
4109: # --------------------------------------------------------------- del interface
4110:
4111: sub del {
1.133 albertel 4112: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4113: my $items='';
1.800 albertel 4114: foreach my $item (@$storearr) {
4115: $items.=&escape($item).'&';
1.191 harris41 4116: }
1.984 neumanie 4117:
1.27 www 4118: $items=~s/\&$//;
1.620 albertel 4119: if (!$udomain) { $udomain=$env{'user.domain'}; }
4120: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4121: my $uhome=&homeserver($uname,$udomain);
4122: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4123: }
4124:
4125: # -------------------------------------------------------------- dump interface
4126:
4127: sub dump {
1.755 albertel 4128: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4129: if (!$udomain) { $udomain=$env{'user.domain'}; }
4130: if (!$uname) { $uname=$env{'user.name'}; }
4131: my $uhome=&homeserver($uname,$udomain);
4132: if ($regexp) {
4133: $regexp=&escape($regexp);
4134: } else {
4135: $regexp='.';
4136: }
4137: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4138: my @pairs=split(/\&/,$rep);
4139: my %returnhash=();
4140: foreach my $item (@pairs) {
4141: my ($key,$value)=split(/=/,$item,2);
4142: $key = &unescape($key);
4143: next if ($key =~ /^error: 2 /);
4144: $returnhash{$key}=&thaw_unescape($value);
4145: }
4146: return %returnhash;
1.407 www 4147: }
4148:
1.717 albertel 4149: # --------------------------------------------------------- dumpstore interface
4150:
4151: sub dumpstore {
4152: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4153: if (!$udomain) { $udomain=$env{'user.domain'}; }
4154: if (!$uname) { $uname=$env{'user.name'}; }
4155: my $uhome=&homeserver($uname,$udomain);
4156: if ($regexp) {
4157: $regexp=&escape($regexp);
4158: } else {
4159: $regexp='.';
4160: }
4161: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4162: my @pairs=split(/\&/,$rep);
4163: my %returnhash=();
4164: foreach my $item (@pairs) {
4165: my ($key,$value)=split(/=/,$item,2);
4166: next if ($key =~ /^error: 2 /);
4167: $returnhash{$key}=&thaw_unescape($value);
4168: }
4169: return %returnhash;
1.717 albertel 4170: }
4171:
1.407 www 4172: # -------------------------------------------------------------- keys interface
4173:
4174: sub getkeys {
4175: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4176: if (!$udomain) { $udomain=$env{'user.domain'}; }
4177: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4178: my $uhome=&homeserver($uname,$udomain);
4179: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4180: my @keyarray=();
1.800 albertel 4181: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4182: next if ($key =~ /^error: 2 /);
1.800 albertel 4183: push(@keyarray,&unescape($key));
1.407 www 4184: }
4185: return @keyarray;
1.318 matthew 4186: }
4187:
1.319 matthew 4188: # --------------------------------------------------------------- currentdump
4189: sub currentdump {
1.328 matthew 4190: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4191: $courseid = $env{'request.course.id'} if (! defined($courseid));
4192: $sdom = $env{'user.domain'} if (! defined($sdom));
4193: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4194: my $uhome = &homeserver($sname,$sdom);
4195: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4196: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4197: #
1.318 matthew 4198: my %returnhash=();
1.319 matthew 4199: #
4200: if ($rep eq "unknown_cmd") {
4201: # an old lond will not know currentdump
4202: # Do a dump and make it look like a currentdump
1.822 albertel 4203: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4204: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4205: my %hash = @tmp;
4206: @tmp=();
1.424 matthew 4207: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4208: } else {
4209: my @pairs=split(/\&/,$rep);
1.800 albertel 4210: foreach my $pair (@pairs) {
4211: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4212: my ($symb,$param) = split(/:/,$key);
4213: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4214: &thaw_unescape($value);
1.319 matthew 4215: }
1.191 harris41 4216: }
1.12 www 4217: return %returnhash;
1.424 matthew 4218: }
4219:
4220: sub convert_dump_to_currentdump{
4221: my %hash = %{shift()};
4222: my %returnhash;
4223: # Code ripped from lond, essentially. The only difference
4224: # here is the unescaping done by lonnet::dump(). Conceivably
4225: # we might run in to problems with parameter names =~ /^v\./
4226: while (my ($key,$value) = each(%hash)) {
4227: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4228: $symb = &unescape($symb);
4229: $param = &unescape($param);
1.424 matthew 4230: next if ($v eq 'version' || $symb eq 'keys');
4231: next if (exists($returnhash{$symb}) &&
4232: exists($returnhash{$symb}->{$param}) &&
4233: $returnhash{$symb}->{'v.'.$param} > $v);
4234: $returnhash{$symb}->{$param}=$value;
4235: $returnhash{$symb}->{'v.'.$param}=$v;
4236: }
4237: #
4238: # Remove all of the keys in the hashes which keep track of
4239: # the version of the parameter.
4240: while (my ($symb,$param_hash) = each(%returnhash)) {
4241: # use a foreach because we are going to delete from the hash.
4242: foreach my $key (keys(%$param_hash)) {
4243: delete($param_hash->{$key}) if ($key =~ /^v\./);
4244: }
4245: }
4246: return \%returnhash;
1.12 www 4247: }
4248:
1.627 albertel 4249: # ------------------------------------------------------ critical inc interface
4250:
4251: sub cinc {
4252: return &inc(@_,'critical');
4253: }
4254:
1.449 matthew 4255: # --------------------------------------------------------------- inc interface
4256:
4257: sub inc {
1.627 albertel 4258: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4259: if (!$udomain) { $udomain=$env{'user.domain'}; }
4260: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4261: my $uhome=&homeserver($uname,$udomain);
4262: my $items='';
4263: if (! ref($store)) {
4264: # got a single value, so use that instead
4265: $items = &escape($store).'=&';
4266: } elsif (ref($store) eq 'SCALAR') {
4267: $items = &escape($$store).'=&';
4268: } elsif (ref($store) eq 'ARRAY') {
4269: $items = join('=&',map {&escape($_);} @{$store});
4270: } elsif (ref($store) eq 'HASH') {
4271: while (my($key,$value) = each(%{$store})) {
4272: $items.= &escape($key).'='.&escape($value).'&';
4273: }
4274: }
4275: $items=~s/\&$//;
1.627 albertel 4276: if ($critical) {
4277: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4278: } else {
4279: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4280: }
1.449 matthew 4281: }
4282:
1.12 www 4283: # --------------------------------------------------------------- put interface
4284:
4285: sub put {
1.134 albertel 4286: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4287: if (!$udomain) { $udomain=$env{'user.domain'}; }
4288: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4289: my $uhome=&homeserver($uname,$udomain);
1.12 www 4290: my $items='';
1.800 albertel 4291: foreach my $item (keys(%$storehash)) {
4292: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4293: }
1.12 www 4294: $items=~s/\&$//;
1.134 albertel 4295: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4296: }
4297:
1.631 albertel 4298: # ------------------------------------------------------------ newput interface
4299:
4300: sub newput {
4301: my ($namespace,$storehash,$udomain,$uname)=@_;
4302: if (!$udomain) { $udomain=$env{'user.domain'}; }
4303: if (!$uname) { $uname=$env{'user.name'}; }
4304: my $uhome=&homeserver($uname,$udomain);
4305: my $items='';
4306: foreach my $key (keys(%$storehash)) {
4307: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4308: }
4309: $items=~s/\&$//;
4310: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4311: }
4312:
4313: # --------------------------------------------------------- putstore interface
4314:
1.524 raeburn 4315: sub putstore {
1.715 albertel 4316: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4317: if (!$udomain) { $udomain=$env{'user.domain'}; }
4318: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4319: my $uhome=&homeserver($uname,$udomain);
4320: my $items='';
1.715 albertel 4321: foreach my $key (keys(%$storehash)) {
4322: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4323: }
1.715 albertel 4324: $items=~s/\&$//;
1.716 albertel 4325: my $esc_symb=&escape($symb);
4326: my $esc_v=&escape($version);
1.715 albertel 4327: my $reply =
1.716 albertel 4328: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4329: $uhome);
4330: if ($reply eq 'unknown_cmd') {
1.716 albertel 4331: # gfall back to way things use to be done
1.715 albertel 4332: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4333: $uname);
1.524 raeburn 4334: }
1.715 albertel 4335: return $reply;
4336: }
4337:
4338: sub old_putstore {
1.716 albertel 4339: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4340: if (!$udomain) { $udomain=$env{'user.domain'}; }
4341: if (!$uname) { $uname=$env{'user.name'}; }
4342: my $uhome=&homeserver($uname,$udomain);
4343: my %newstorehash;
1.800 albertel 4344: foreach my $item (keys(%$storehash)) {
4345: my $key = $version.':'.&escape($symb).':'.$item;
4346: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4347: }
4348: my $items='';
4349: my %allitems = ();
1.800 albertel 4350: foreach my $item (keys(%newstorehash)) {
4351: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4352: my $key = $1.':keys:'.$2;
4353: $allitems{$key} .= $3.':';
4354: }
1.800 albertel 4355: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4356: }
1.800 albertel 4357: foreach my $item (keys(%allitems)) {
4358: $allitems{$item} =~ s/\:$//;
4359: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4360: }
4361: $items=~s/\&$//;
4362: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4363: }
4364:
1.47 www 4365: # ------------------------------------------------------ critical put interface
4366:
4367: sub cput {
1.134 albertel 4368: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4369: if (!$udomain) { $udomain=$env{'user.domain'}; }
4370: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4371: my $uhome=&homeserver($uname,$udomain);
1.47 www 4372: my $items='';
1.800 albertel 4373: foreach my $item (keys(%$storehash)) {
4374: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4375: }
1.47 www 4376: $items=~s/\&$//;
1.134 albertel 4377: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4378: }
4379:
4380: # -------------------------------------------------------------- eget interface
4381:
4382: sub eget {
1.133 albertel 4383: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4384: my $items='';
1.800 albertel 4385: foreach my $item (@$storearr) {
4386: $items.=&escape($item).'&';
1.191 harris41 4387: }
1.12 www 4388: $items=~s/\&$//;
1.620 albertel 4389: if (!$udomain) { $udomain=$env{'user.domain'}; }
4390: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4391: my $uhome=&homeserver($uname,$udomain);
4392: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4393: my @pairs=split(/\&/,$rep);
4394: my %returnhash=();
1.42 www 4395: my $i=0;
1.800 albertel 4396: foreach my $item (@$storearr) {
4397: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4398: $i++;
1.191 harris41 4399: }
1.12 www 4400: return %returnhash;
4401: }
4402:
1.667 albertel 4403: # ------------------------------------------------------------ tmpput interface
4404: sub tmpput {
1.802 raeburn 4405: my ($storehash,$server,$context)=@_;
1.667 albertel 4406: my $items='';
1.800 albertel 4407: foreach my $item (keys(%$storehash)) {
4408: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4409: }
4410: $items=~s/\&$//;
1.802 raeburn 4411: if (defined($context)) {
4412: $items .= ':'.&escape($context);
4413: }
1.667 albertel 4414: return &reply("tmpput:$items",$server);
4415: }
4416:
4417: # ------------------------------------------------------------ tmpget interface
4418: sub tmpget {
1.688 albertel 4419: my ($token,$server)=@_;
4420: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4421: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4422: my %returnhash;
4423: foreach my $item (split(/\&/,$rep)) {
4424: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4425: next if ($key =~ /^error: 2 /);
1.667 albertel 4426: $returnhash{&unescape($key)}=&thaw_unescape($value);
4427: }
4428: return %returnhash;
4429: }
4430:
1.688 albertel 4431: # ------------------------------------------------------------ tmpget interface
4432: sub tmpdel {
4433: my ($token,$server)=@_;
4434: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4435: return &reply("tmpdel:$token",$server);
4436: }
4437:
1.765 albertel 4438: # -------------------------------------------------- portfolio access checking
4439:
4440: sub portfolio_access {
1.766 albertel 4441: my ($requrl) = @_;
1.765 albertel 4442: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4443: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4444: if ($result) {
4445: my %setters;
4446: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4447: my ($startblock,$endblock) =
4448: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4449: if ($startblock && $endblock) {
4450: return 'B';
4451: }
4452: } else {
4453: my ($startblock,$endblock) =
4454: &Apache::loncommon::blockcheck(\%setters,'port');
4455: if ($startblock && $endblock) {
4456: return 'B';
4457: }
4458: }
4459: }
1.765 albertel 4460: if ($result eq 'ok') {
1.766 albertel 4461: return 'F';
1.765 albertel 4462: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4463: return 'A';
1.765 albertel 4464: }
1.766 albertel 4465: return '';
1.765 albertel 4466: }
4467:
4468: sub get_portfolio_access {
1.767 albertel 4469: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4470:
4471: if (!ref($access_hash)) {
4472: my $current_perms = &get_portfile_permissions($udom,$unum);
4473: my %access_controls = &get_access_controls($current_perms,$group,
4474: $file_name);
4475: $access_hash = $access_controls{$file_name};
4476: }
4477:
1.765 albertel 4478: my ($public,$guest,@domains,@users,@courses,@groups);
4479: my $now = time;
4480: if (ref($access_hash) eq 'HASH') {
4481: foreach my $key (keys(%{$access_hash})) {
4482: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4483: if ($start > $now) {
4484: next;
4485: }
4486: if ($end && $end<$now) {
4487: next;
4488: }
4489: if ($scope eq 'public') {
4490: $public = $key;
4491: last;
4492: } elsif ($scope eq 'guest') {
4493: $guest = $key;
4494: } elsif ($scope eq 'domains') {
4495: push(@domains,$key);
4496: } elsif ($scope eq 'users') {
4497: push(@users,$key);
4498: } elsif ($scope eq 'course') {
4499: push(@courses,$key);
4500: } elsif ($scope eq 'group') {
4501: push(@groups,$key);
4502: }
4503: }
4504: if ($public) {
4505: return 'ok';
4506: }
4507: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4508: if ($guest) {
4509: return $guest;
4510: }
4511: } else {
4512: if (@domains > 0) {
4513: foreach my $domkey (@domains) {
4514: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4515: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4516: return 'ok';
4517: }
4518: }
4519: }
4520: }
4521: if (@users > 0) {
4522: foreach my $userkey (@users) {
1.865 raeburn 4523: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4524: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4525: if (ref($item) eq 'HASH') {
4526: if (($item->{'uname'} eq $env{'user.name'}) &&
4527: ($item->{'udom'} eq $env{'user.domain'})) {
4528: return 'ok';
4529: }
4530: }
4531: }
4532: }
1.765 albertel 4533: }
4534: }
4535: my %roleshash;
4536: my @courses_and_groups = @courses;
4537: push(@courses_and_groups,@groups);
4538: if (@courses_and_groups > 0) {
4539: my (%allgroups,%allroles);
4540: my ($start,$end,$role,$sec,$group);
4541: foreach my $envkey (%env) {
1.1060 ! raeburn 4542: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4543: my $cid = $2.'_'.$3;
4544: if ($1 eq 'gr') {
4545: $group = $4;
4546: $allgroups{$cid}{$group} = $env{$envkey};
4547: } else {
4548: if ($4 eq '') {
4549: $sec = 'none';
4550: } else {
4551: $sec = $4;
4552: }
4553: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4554: }
1.811 albertel 4555: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4556: my $cid = $2.'_'.$3;
4557: if ($4 eq '') {
4558: $sec = 'none';
4559: } else {
4560: $sec = $4;
4561: }
4562: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4563: }
4564: }
4565: if (keys(%allroles) == 0) {
4566: return;
4567: }
4568: foreach my $key (@courses_and_groups) {
4569: my %content = %{$$access_hash{$key}};
4570: my $cnum = $content{'number'};
4571: my $cdom = $content{'domain'};
4572: my $cid = $cdom.'_'.$cnum;
4573: if (!exists($allroles{$cid})) {
4574: next;
4575: }
4576: foreach my $role_id (keys(%{$content{'roles'}})) {
4577: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4578: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4579: my @status = @{$content{'roles'}{$role_id}{'access'}};
4580: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4581: foreach my $role (keys(%{$allroles{$cid}})) {
4582: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4583: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4584: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4585: if (grep/^all$/,@sections) {
4586: return 'ok';
4587: } else {
4588: if (grep/^$sec$/,@sections) {
4589: return 'ok';
4590: }
4591: }
4592: }
4593: }
4594: if (keys(%{$allgroups{$cid}}) == 0) {
4595: if (grep/^none$/,@groups) {
4596: return 'ok';
4597: }
4598: } else {
4599: if (grep/^all$/,@groups) {
4600: return 'ok';
4601: }
4602: foreach my $group (keys(%{$allgroups{$cid}})) {
4603: if (grep/^$group$/,@groups) {
4604: return 'ok';
4605: }
4606: }
4607: }
4608: }
4609: }
4610: }
4611: }
4612: }
4613: if ($guest) {
4614: return $guest;
4615: }
4616: }
4617: }
4618: return;
4619: }
4620:
4621: sub course_group_datechecker {
4622: my ($dates,$now,$status) = @_;
4623: my ($start,$end) = split(/\./,$dates);
4624: if (!$start && !$end) {
4625: return 'ok';
4626: }
4627: if (grep/^active$/,@{$status}) {
4628: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4629: return 'ok';
4630: }
4631: }
4632: if (grep/^previous$/,@{$status}) {
4633: if ($end > $now ) {
4634: return 'ok';
4635: }
4636: }
4637: if (grep/^future$/,@{$status}) {
4638: if ($start > $now) {
4639: return 'ok';
4640: }
4641: }
4642: return;
4643: }
4644:
4645: sub parse_portfolio_url {
4646: my ($url) = @_;
4647:
4648: my ($type,$udom,$unum,$group,$file_name);
4649:
1.823 albertel 4650: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4651: $type = 1;
4652: $udom = $1;
4653: $unum = $2;
4654: $file_name = $3;
1.823 albertel 4655: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4656: $type = 2;
4657: $udom = $1;
4658: $unum = $2;
4659: $group = $3;
4660: $file_name = $3.'/'.$4;
4661: }
4662: if (wantarray) {
4663: return ($type,$udom,$unum,$file_name,$group);
4664: }
4665: return $type;
4666: }
4667:
4668: sub is_portfolio_url {
4669: my ($url) = @_;
4670: return scalar(&parse_portfolio_url($url));
4671: }
4672:
1.798 raeburn 4673: sub is_portfolio_file {
4674: my ($file) = @_;
1.820 raeburn 4675: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4676: return 1;
4677: }
4678: return;
4679: }
4680:
1.976 raeburn 4681: sub usertools_access {
1.985 raeburn 4682: my ($uname,$udom,$tool,$action,$context) = @_;
4683: my ($access,%tools);
4684: if ($context eq '') {
4685: $context = 'tools';
4686: }
4687: if ($context eq 'requestcourses') {
4688: %tools = (
4689: official => 1,
4690: unofficial => 1,
1.1006 raeburn 4691: community => 1,
1.985 raeburn 4692: );
4693: } else {
4694: %tools = (
4695: aboutme => 1,
4696: blog => 1,
4697: portfolio => 1,
4698: );
4699: }
1.976 raeburn 4700: return if (!defined($tools{$tool}));
4701:
4702: if ((!defined($udom)) || (!defined($uname))) {
4703: $udom = $env{'user.domain'};
4704: $uname = $env{'user.name'};
4705: }
4706:
1.978 raeburn 4707: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4708: if ($action ne 'reload') {
1.985 raeburn 4709: if ($context eq 'requestcourses') {
4710: return $env{'environment.canrequest.'.$tool};
4711: } else {
4712: return $env{'environment.availabletools.'.$tool};
4713: }
4714: }
1.976 raeburn 4715: }
4716:
4717: my ($toolstatus,$inststatus);
4718:
1.985 raeburn 4719: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4720: ($action ne 'reload')) {
4721: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4722: $inststatus = $env{'environment.inststatus'};
4723: } else {
1.1025 raeburn 4724: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985 raeburn 4725: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4726: $inststatus = $userenv{'inststatus'};
4727: }
4728:
4729: if ($toolstatus ne '') {
4730: if ($toolstatus) {
4731: $access = 1;
4732: } else {
4733: $access = 0;
4734: }
4735: return $access;
4736: }
4737:
4738: my $is_adv = &is_advanced_user($udom,$uname);
4739: my %domdef = &get_domain_defaults($udom);
4740: if (ref($domdef{$tool}) eq 'HASH') {
4741: if ($is_adv) {
4742: if ($domdef{$tool}{'_LC_adv'} ne '') {
4743: if ($domdef{$tool}{'_LC_adv'}) {
4744: $access = 1;
4745: } else {
4746: $access = 0;
4747: }
4748: return $access;
4749: }
4750: }
4751: if ($inststatus ne '') {
4752: my ($hasaccess,$hasnoaccess);
4753: foreach my $affiliation (split(/:/,$inststatus)) {
4754: if ($domdef{$tool}{$affiliation} ne '') {
4755: if ($domdef{$tool}{$affiliation}) {
4756: $hasaccess = 1;
4757: } else {
4758: $hasnoaccess = 1;
4759: }
4760: }
4761: }
4762: if ($hasaccess || $hasnoaccess) {
4763: if ($hasaccess) {
4764: $access = 1;
4765: } elsif ($hasnoaccess) {
4766: $access = 0;
4767: }
4768: return $access;
4769: }
4770: } else {
4771: if ($domdef{$tool}{'default'} ne '') {
4772: if ($domdef{$tool}{'default'}) {
4773: $access = 1;
4774: } elsif ($domdef{$tool}{'default'} == 0) {
4775: $access = 0;
4776: }
4777: return $access;
4778: }
4779: }
4780: } else {
1.985 raeburn 4781: if ($context eq 'tools') {
4782: $access = 1;
4783: } else {
4784: $access = 0;
4785: }
1.976 raeburn 4786: return $access;
4787: }
4788: }
4789:
1.1050 raeburn 4790: sub is_course_owner {
4791: my ($cdom,$cnum,$udom,$uname) = @_;
4792: if (($udom eq '') || ($uname eq '')) {
4793: $udom = $env{'user.domain'};
4794: $uname = $env{'user.name'};
4795: }
4796: unless (($udom eq '') || ($uname eq '')) {
4797: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
4798: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
4799: return 1;
4800: } else {
4801: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
4802: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
4803: return 1;
4804: }
4805: }
4806: }
4807: }
4808: return;
4809: }
4810:
1.976 raeburn 4811: sub is_advanced_user {
4812: my ($udom,$uname) = @_;
4813: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4814: my %allroles;
4815: my $is_adv;
4816: foreach my $role (keys(%roleshash)) {
4817: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4818: my $area = '/'.$tdomain.'/'.$trest;
4819: if ($sec ne '') {
4820: $area .= '/'.$sec;
4821: }
4822: if (($area ne '') && ($trole ne '')) {
4823: my $spec=$trole.'.'.$area;
4824: if ($trole =~ /^cr\//) {
4825: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4826: } elsif ($trole ne 'gr') {
4827: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4828: }
4829: }
4830: }
4831: foreach my $role (keys(%allroles)) {
4832: last if ($is_adv);
4833: foreach my $item (split(/:/,$allroles{$role})) {
4834: if ($item ne '') {
4835: my ($privilege,$restrictions)=split(/&/,$item);
4836: if ($privilege eq 'adv') {
4837: $is_adv = 1;
4838: last;
4839: }
4840: }
4841: }
4842: }
4843: return $is_adv;
4844: }
1.798 raeburn 4845:
1.1035 raeburn 4846: sub check_can_request {
1.1036 raeburn 4847: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 4848: my $canreq = 0;
4849: my ($types,$typename) = &Apache::loncommon::course_types();
4850: my @options = ('approval','validate','autolimit');
4851: my $optregex = join('|',@options);
4852: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
4853: foreach my $type (@{$types}) {
4854: if (&usertools_access($env{'user.name'},
4855: $env{'user.domain'},
4856: $type,undef,'requestcourses')) {
4857: $canreq ++;
1.1036 raeburn 4858: if (ref($request_domains) eq 'HASH') {
4859: push(@{$request_domains->{$type}},$env{'user.domain'});
4860: }
1.1035 raeburn 4861: if ($dom eq $env{'user.domain'}) {
4862: $can_request->{$type} = 1;
4863: }
4864: }
4865: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
4866: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
4867: if (@curr > 0) {
1.1036 raeburn 4868: foreach my $item (@curr) {
4869: if (ref($request_domains) eq 'HASH') {
4870: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
4871: if ($otherdom ne '') {
4872: if (ref($request_domains->{$type}) eq 'ARRAY') {
4873: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
4874: push(@{$request_domains->{$type}},$otherdom);
4875: }
4876: } else {
4877: push(@{$request_domains->{$type}},$otherdom);
4878: }
4879: }
4880: }
4881: }
4882: unless($dom eq $env{'user.domain'}) {
4883: $canreq ++;
1.1035 raeburn 4884: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
4885: $can_request->{$type} = 1;
4886: }
4887: }
4888: }
4889: }
4890: }
4891: }
4892: return $canreq;
4893: }
4894:
1.341 www 4895: # ---------------------------------------------- Custom access rule evaluation
4896:
4897: sub customaccess {
4898: my ($priv,$uri)=@_;
1.807 albertel 4899: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4900: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4901: $udom = &LONCAPA::clean_domain($udom);
4902: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4903: my $access=0;
1.800 albertel 4904: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4905: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4906: if ($type eq 'user') {
4907: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4908: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4909: if ($tdom) {
4910: if ($tdom ne $env{'user.domain'}) { next; }
4911: }
1.896 albertel 4912: if ($tuname) {
4913: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4914: }
4915: $access=($effect eq 'allow');
4916: last;
4917: }
4918: } else {
4919: if ($role) {
4920: if ($role ne $urole) { next; }
4921: }
4922: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4923: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4924: if ($tdom) {
4925: if ($tdom ne $udom) { next; }
4926: }
4927: if ($tcrs) {
4928: if ($tcrs ne $ucrs) { next; }
4929: }
4930: if ($tsec) {
4931: if ($tsec ne $usec) { next; }
4932: }
4933: $access=($effect eq 'allow');
4934: last;
4935: }
4936: if ($realm eq '' && $role eq '') {
4937: $access=($effect eq 'allow');
4938: }
1.402 bowersj2 4939: }
1.341 www 4940: }
4941: return $access;
4942: }
4943:
1.103 harris41 4944: # ------------------------------------------------- Check for a user privilege
1.12 www 4945:
4946: sub allowed {
1.810 raeburn 4947: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4948: my $ver_orguri=$uri;
1.439 www 4949: $uri=&deversion($uri);
1.152 www 4950: my $orguri=$uri;
1.52 www 4951: $uri=&declutter($uri);
1.809 raeburn 4952:
1.810 raeburn 4953: if ($priv eq 'evb') {
4954: # Evade communication block restrictions for specified role in a course
4955: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4956: return $1;
4957: } else {
4958: return;
4959: }
4960: }
4961:
1.620 albertel 4962: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4963: # Free bre access to adm and meta resources
1.775 albertel 4964: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4965: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4966: && ($priv eq 'bre')) {
1.14 www 4967: return 'F';
1.159 www 4968: }
4969:
1.545 banghart 4970: # Free bre access to user's own portfolio contents
1.714 raeburn 4971: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4972: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4973: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4974: my %setters;
4975: my ($startblock,$endblock) =
4976: &Apache::loncommon::blockcheck(\%setters,'port');
4977: if ($startblock && $endblock) {
4978: return 'B';
4979: } else {
4980: return 'F';
4981: }
1.545 banghart 4982: }
4983:
1.762 raeburn 4984: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4985: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4986: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4987: if (exists($env{'request.course.id'})) {
4988: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4989: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4990: if (($domain eq $cdom) && ($name eq $cnum)) {
4991: my $courseprivid=$env{'request.course.id'};
4992: $courseprivid=~s/\_/\//;
4993: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4994: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4995: return $1;
1.762 raeburn 4996: } else {
4997: if ($env{'request.course.sec'}) {
4998: $courseprivid.='/'.$env{'request.course.sec'};
4999: }
5000: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5001: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5002: return $2;
5003: }
1.714 raeburn 5004: }
5005: }
5006: }
5007: }
5008:
1.159 www 5009: # Free bre to public access
5010:
5011: if ($priv eq 'bre') {
1.238 www 5012: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5013: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5014: return 'F';
5015: }
1.238 www 5016: if ($copyright eq 'priv') {
5017: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5018: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5019: return '';
5020: }
5021: }
5022: if ($copyright eq 'domain') {
5023: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5024: unless (($env{'user.domain'} eq $1) ||
5025: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5026: return '';
5027: }
1.262 matthew 5028: }
1.620 albertel 5029: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5030: # Library role, so allow browsing of resources in this domain.
5031: return 'F';
1.238 www 5032: }
1.341 www 5033: if ($copyright eq 'custom') {
5034: unless (&customaccess($priv,$uri)) { return ''; }
5035: }
1.14 www 5036: }
1.264 matthew 5037: # Domain coordinator is trying to create a course
1.620 albertel 5038: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5039: # uri is the requested domain in this case.
5040: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5041: # a role of dc for the domain in question.
1.620 albertel 5042: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5043: }
1.29 www 5044:
1.52 www 5045: my $thisallowed='';
5046: my $statecond=0;
5047: my $courseprivid='';
5048:
1.1039 raeburn 5049: my $ownaccess;
1.1043 raeburn 5050: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5051: if (($priv eq 'bro') && ($env{'user.author'})) {
5052: if ($uri eq '') {
5053: $ownaccess = 1;
5054: } else {
5055: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5056: my $udom = $env{'user.domain'};
5057: my $uname = $env{'user.name'};
5058: if ($uri =~ m{^\Q$udom\E/?$}) {
5059: $ownaccess = 1;
1.1040 raeburn 5060: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5061: unless ($uri =~ m{\.\./}) {
5062: $ownaccess = 1;
5063: }
5064: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5065: my $now = time;
5066: if ($uri =~ m{^([^/]+)/?$}) {
5067: my $adom = $1;
5068: foreach my $key (keys(%env)) {
1.1042 raeburn 5069: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5070: my ($start,$end) = split('.',$env{$key});
5071: if (($now >= $start) && (!$end || $end < $now)) {
5072: $ownaccess = 1;
5073: last;
5074: }
5075: }
5076: }
5077: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5078: my $adom = $1;
5079: my $aname = $2;
1.1042 raeburn 5080: foreach my $role ('ca','aa') {
5081: if ($env{"user.role.$role./$adom/$aname"}) {
5082: my ($start,$end) =
5083: split('.',$env{"user.role.$role./$adom/$aname"});
5084: if (($now >= $start) && (!$end || $end < $now)) {
5085: $ownaccess = 1;
5086: last;
5087: }
1.1039 raeburn 5088: }
5089: }
5090: }
5091: }
5092: }
5093: }
5094: }
5095:
1.52 www 5096: # Course
5097:
1.620 albertel 5098: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5099: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5100: $thisallowed.=$1;
5101: }
1.52 www 5102: }
1.29 www 5103:
1.52 www 5104: # Domain
5105:
1.620 albertel 5106: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5107: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5108: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5109: $thisallowed.=$1;
5110: }
1.12 www 5111: }
1.52 www 5112:
5113: # Course: uri itself is a course
1.66 www 5114: my $courseuri=$uri;
5115: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5116: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5117:
1.620 albertel 5118: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5119: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5120: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5121: $thisallowed.=$1;
5122: }
1.12 www 5123: }
1.29 www 5124:
1.665 albertel 5125: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5126: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5127: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5128: $thisallowed='';
1.671 raeburn 5129: my ($match)=&is_on_map($uri);
5130: if ($match) {
5131: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5132: =~/\Q$priv\E\&([^\:]*)/) {
5133: $thisallowed.=$1;
5134: }
5135: } else {
1.705 albertel 5136: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5137: if ($refuri) {
5138: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5139: $thisallowed='F';
1.671 raeburn 5140: } else {
5141: $refuri=&declutter($refuri);
5142: my ($match) = &is_on_map($refuri);
5143: if ($match) {
5144: $thisallowed='F';
5145: }
1.669 raeburn 5146: }
1.671 raeburn 5147: }
5148: }
1.314 www 5149: }
1.492 albertel 5150:
1.766 albertel 5151: if ($priv eq 'bre'
5152: && $thisallowed ne 'F'
5153: && $thisallowed ne '2'
5154: && &is_portfolio_url($uri)) {
5155: $thisallowed = &portfolio_access($uri);
5156: }
5157:
1.52 www 5158: # Full access at system, domain or course-wide level? Exit.
1.29 www 5159: if ($thisallowed=~/F/) {
5160: return 'F';
5161: }
5162:
1.52 www 5163: # If this is generating or modifying users, exit with special codes
1.29 www 5164:
1.643 www 5165: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5166: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5167: my ($audom,$auname)=split('/',$uri);
1.643 www 5168: # no author name given, so this just checks on the general right to make a co-author in this domain
5169: unless ($auname) { return $thisallowed; }
5170: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5171: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5172: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5173: ($audom ne $env{'request.role.domain'}))) { return ''; }
5174: }
1.52 www 5175: return $thisallowed;
5176: }
5177: #
1.103 harris41 5178: # Gathered so far: system, domain and course wide privileges
1.52 www 5179: #
5180: # Course: See if uri or referer is an individual resource that is part of
5181: # the course
5182:
1.620 albertel 5183: if ($env{'request.course.id'}) {
1.232 www 5184:
1.620 albertel 5185: $courseprivid=$env{'request.course.id'};
5186: if ($env{'request.course.sec'}) {
5187: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5188: }
5189: $courseprivid=~s/\_/\//;
5190: my $checkreferer=1;
1.232 www 5191: my ($match,$cond)=&is_on_map($uri);
5192: if ($match) {
5193: $statecond=$cond;
1.620 albertel 5194: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5195: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5196: $thisallowed.=$1;
5197: $checkreferer=0;
5198: }
1.29 www 5199: }
1.83 www 5200:
1.148 www 5201: if ($checkreferer) {
1.620 albertel 5202: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5203: unless ($refuri) {
1.800 albertel 5204: foreach my $key (keys(%env)) {
5205: if ($key=~/^httpref\..*\*/) {
5206: my $pattern=$key;
1.156 www 5207: $pattern=~s/^httpref\.\/res\///;
1.148 www 5208: $pattern=~s/\*/\[\^\/\]\+/g;
5209: $pattern=~s/\//\\\//g;
1.152 www 5210: if ($orguri=~/$pattern/) {
1.800 albertel 5211: $refuri=$env{$key};
1.148 www 5212: }
5213: }
1.191 harris41 5214: }
1.148 www 5215: }
1.232 www 5216:
1.148 www 5217: if ($refuri) {
1.152 www 5218: $refuri=&declutter($refuri);
1.232 www 5219: my ($match,$cond)=&is_on_map($refuri);
5220: if ($match) {
5221: my $refstatecond=$cond;
1.620 albertel 5222: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5223: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5224: $thisallowed.=$1;
1.53 www 5225: $uri=$refuri;
5226: $statecond=$refstatecond;
1.52 www 5227: }
5228: }
1.148 www 5229: }
1.29 www 5230: }
1.52 www 5231: }
1.29 www 5232:
1.52 www 5233: #
1.103 harris41 5234: # Gathered now: all privileges that could apply, and condition number
1.52 www 5235: #
5236: #
5237: # Full or no access?
5238: #
1.29 www 5239:
1.52 www 5240: if ($thisallowed=~/F/) {
5241: return 'F';
5242: }
1.29 www 5243:
1.52 www 5244: unless ($thisallowed) {
5245: return '';
5246: }
1.29 www 5247:
1.52 www 5248: # Restrictions exist, deal with them
5249: #
5250: # C:according to course preferences
5251: # R:according to resource settings
5252: # L:unless locked
5253: # X:according to user session state
5254: #
5255:
5256: # Possibly locked functionality, check all courses
1.54 www 5257: # Locks might take effect only after 10 minutes cache expiration for other
5258: # courses, and 2 minutes for current course
1.52 www 5259:
5260: my $envkey;
5261: if ($thisallowed=~/L/) {
1.1000 raeburn 5262: foreach $envkey (keys(%env)) {
1.54 www 5263: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5264: my $courseid=$2;
5265: my $roleid=$1.'.'.$2;
1.92 www 5266: $courseid=~s/^\///;
1.54 www 5267: my $expiretime=600;
1.620 albertel 5268: if ($env{'request.role'} eq $roleid) {
1.54 www 5269: $expiretime=120;
5270: }
5271: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5272: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5273: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5274: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5275: }
1.620 albertel 5276: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5277: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5278: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5279: &log($env{'user.domain'},$env{'user.name'},
5280: $env{'user.home'},
1.57 www 5281: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5282: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5283: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5284: return '';
5285: }
5286: }
1.620 albertel 5287: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5288: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5289: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5290: &log($env{'user.domain'},$env{'user.name'},
5291: $env{'user.home'},
1.57 www 5292: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5293: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5294: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5295: return '';
5296: }
5297: }
5298: }
1.29 www 5299: }
1.52 www 5300: }
5301:
5302: #
5303: # Rest of the restrictions depend on selected course
5304: #
5305:
1.620 albertel 5306: unless ($env{'request.course.id'}) {
1.766 albertel 5307: if ($thisallowed eq 'A') {
5308: return 'A';
1.814 raeburn 5309: } elsif ($thisallowed eq 'B') {
5310: return 'B';
1.766 albertel 5311: } else {
5312: return '1';
5313: }
1.52 www 5314: }
1.29 www 5315:
1.52 www 5316: #
5317: # Now user is definitely in a course
5318: #
1.53 www 5319:
5320:
5321: # Course preferences
5322:
5323: if ($thisallowed=~/C/) {
1.620 albertel 5324: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5325: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5326: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5327: =~/\Q$rolecode\E/) {
1.689 albertel 5328: if ($priv ne 'pch') {
5329: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5330: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5331: $env{'request.course.id'});
5332: }
1.237 www 5333: return '';
5334: }
5335:
1.620 albertel 5336: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5337: =~/\Q$unamedom\E/) {
1.689 albertel 5338: if ($priv ne 'pch') {
5339: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5340: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5341: $env{'request.course.id'});
5342: }
1.54 www 5343: return '';
5344: }
1.53 www 5345: }
5346:
5347: # Resource preferences
5348:
5349: if ($thisallowed=~/R/) {
1.620 albertel 5350: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5351: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5352: if ($priv ne 'pch') {
5353: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5354: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5355: }
5356: return '';
1.54 www 5357: }
1.53 www 5358: }
1.30 www 5359:
1.246 www 5360: # Restricted by state or randomout?
1.30 www 5361:
1.52 www 5362: if ($thisallowed=~/X/) {
1.620 albertel 5363: if ($env{'acc.randomout'}) {
1.579 albertel 5364: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5365: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5366: return '';
5367: }
1.247 www 5368: }
5369: if (&condval($statecond)) {
1.52 www 5370: return '2';
5371: } else {
5372: return '';
5373: }
5374: }
1.30 www 5375:
1.766 albertel 5376: if ($thisallowed eq 'A') {
5377: return 'A';
1.814 raeburn 5378: } elsif ($thisallowed eq 'B') {
5379: return 'B';
1.766 albertel 5380: }
1.52 www 5381: return 'F';
1.232 www 5382: }
5383:
1.710 albertel 5384: sub split_uri_for_cond {
5385: my $uri=&deversion(&declutter(shift));
5386: my @uriparts=split(/\//,$uri);
5387: my $filename=pop(@uriparts);
5388: my $pathname=join('/',@uriparts);
5389: return ($pathname,$filename);
5390: }
1.232 www 5391: # --------------------------------------------------- Is a resource on the map?
5392:
5393: sub is_on_map {
1.710 albertel 5394: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5395: #Trying to find the conditional for the file
1.620 albertel 5396: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5397: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5398: if ($match) {
1.289 bowersj2 5399: return (1,$1);
5400: } else {
1.434 www 5401: return (0,0);
1.289 bowersj2 5402: }
1.12 www 5403: }
5404:
1.427 www 5405: # --------------------------------------------------------- Get symb from alias
5406:
5407: sub get_symb_from_alias {
5408: my $symb=shift;
5409: my ($map,$resid,$url)=&decode_symb($symb);
5410: # Already is a symb
5411: if ($url) { return $symb; }
5412: # Must be an alias
5413: my $aliassymb='';
5414: my %bighash;
1.620 albertel 5415: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5416: &GDBM_READER(),0640)) {
5417: my $rid=$bighash{'mapalias_'.$symb};
5418: if ($rid) {
5419: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5420: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5421: $resid,$bighash{'src_'.$rid});
1.427 www 5422: }
5423: untie %bighash;
5424: }
5425: return $aliassymb;
5426: }
5427:
1.12 www 5428: # ----------------------------------------------------------------- Define Role
5429:
5430: sub definerole {
5431: if (allowed('mcr','/')) {
5432: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5433: foreach my $role (split(':',$sysrole)) {
5434: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5435: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5436: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5437: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5438: return "refused:s:$crole&$cqual";
5439: }
5440: }
1.191 harris41 5441: }
1.800 albertel 5442: foreach my $role (split(':',$domrole)) {
5443: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5444: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5445: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5446: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5447: return "refused:d:$crole&$cqual";
5448: }
5449: }
1.191 harris41 5450: }
1.800 albertel 5451: foreach my $role (split(':',$courole)) {
5452: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5453: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5454: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5455: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5456: return "refused:c:$crole&$cqual";
5457: }
5458: }
1.191 harris41 5459: }
1.620 albertel 5460: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5461: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5462: "rolesdef_$rolename=".
5463: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5464: return reply($command,$env{'user.home'});
1.12 www 5465: } else {
5466: return 'refused';
5467: }
1.105 harris41 5468: }
5469:
5470: # ---------------- Make a metadata query against the network of library servers
5471:
5472: sub metadata_query {
1.244 matthew 5473: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5474: my %rhash;
1.845 albertel 5475: my %libserv = &all_library();
1.244 matthew 5476: my @server_list = (defined($server_array) ? @$server_array
5477: : keys(%libserv) );
5478: for my $server (@server_list) {
1.118 harris41 5479: unless ($custom or $customshow) {
5480: my $reply=&reply("querysend:".&escape($query),$server);
5481: $rhash{$server}=$reply;
5482: }
5483: else {
5484: my $reply=&reply("querysend:".&escape($query).':'.
5485: &escape($custom).':'.&escape($customshow),
5486: $server);
5487: $rhash{$server}=$reply;
5488: }
1.112 harris41 5489: }
1.118 harris41 5490: return \%rhash;
1.240 www 5491: }
5492:
5493: # ----------------------------------------- Send log queries and wait for reply
5494:
5495: sub log_query {
5496: my ($uname,$udom,$query,%filters)=@_;
5497: my $uhome=&homeserver($uname,$udom);
5498: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5499: my $uhost=&hostname($uhome);
1.800 albertel 5500: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5501: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5502: $uhome);
1.479 albertel 5503: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5504: return get_query_reply($queryid);
5505: }
5506:
1.818 raeburn 5507: # -------------------------- Update MySQL table for portfolio file
5508:
5509: sub update_portfolio_table {
1.821 raeburn 5510: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5511: if ($group ne '') {
5512: $file_name =~s /^\Q$group\E//;
5513: }
1.818 raeburn 5514: my $homeserver = &homeserver($uname,$udom);
5515: my $queryid=
1.821 raeburn 5516: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5517: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5518: my $reply = &get_query_reply($queryid);
5519: return $reply;
5520: }
5521:
1.899 raeburn 5522: # -------------------------- Update MySQL allusers table
5523:
5524: sub update_allusers_table {
5525: my ($uname,$udom,$names) = @_;
5526: my $homeserver = &homeserver($uname,$udom);
5527: my $queryid=
5528: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5529: 'lastname='.&escape($names->{'lastname'}).'%%'.
5530: 'firstname='.&escape($names->{'firstname'}).'%%'.
5531: 'middlename='.&escape($names->{'middlename'}).'%%'.
5532: 'generation='.&escape($names->{'generation'}).'%%'.
5533: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5534: 'id='.&escape($names->{'id'}),$homeserver);
5535: my $reply = &get_query_reply($queryid);
5536: return $reply;
5537: }
5538:
1.508 raeburn 5539: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5540:
5541: sub fetch_enrollment_query {
1.511 raeburn 5542: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5543: my $homeserver;
1.547 raeburn 5544: my $maxtries = 1;
1.508 raeburn 5545: if ($context eq 'automated') {
5546: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5547: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5548: } else {
5549: $homeserver = &homeserver($cnum,$dom);
5550: }
1.838 albertel 5551: my $host=&hostname($homeserver);
1.506 raeburn 5552: my $cmd = '';
1.1000 raeburn 5553: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5554: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5555: }
5556: $cmd =~ s/%%$//;
5557: $cmd = &escape($cmd);
5558: my $query = 'fetchenrollment';
1.620 albertel 5559: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5560: unless ($queryid=~/^\Q$host\E\_/) {
5561: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5562: return 'error: '.$queryid;
5563: }
1.506 raeburn 5564: my $reply = &get_query_reply($queryid);
1.547 raeburn 5565: my $tries = 1;
5566: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5567: $reply = &get_query_reply($queryid);
5568: $tries ++;
5569: }
1.526 raeburn 5570: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5571: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5572: } else {
1.901 albertel 5573: my @responses = split(/:/,$reply);
1.515 raeburn 5574: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5575: foreach my $line (@responses) {
5576: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5577: $$replyref{$key} = $value;
5578: }
5579: } else {
1.506 raeburn 5580: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5581: foreach my $line (@responses) {
5582: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5583: $$replyref{$key} = $value;
5584: if ($value > 0) {
1.800 albertel 5585: foreach my $item (@{$$affiliatesref{$key}}) {
5586: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5587: my $destname = $pathname.'/'.$filename;
5588: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5589: if ($xml_classlist =~ /^error/) {
5590: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5591: } else {
1.506 raeburn 5592: if ( open(FILE,">$destname") ) {
5593: print FILE &unescape($xml_classlist);
5594: close(FILE);
1.526 raeburn 5595: } else {
5596: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5597: }
5598: }
5599: }
5600: }
5601: }
5602: }
5603: return 'ok';
5604: }
5605: return 'error';
5606: }
5607:
1.242 www 5608: sub get_query_reply {
5609: my $queryid=shift;
1.240 www 5610: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5611: my $reply='';
5612: for (1..100) {
5613: sleep 2;
5614: if (-e $replyfile.'.end') {
1.448 albertel 5615: if (open(my $fh,$replyfile)) {
1.904 albertel 5616: $reply = join('',<$fh>);
5617: close($fh);
1.240 www 5618: } else { return 'error: reply_file_error'; }
1.242 www 5619: return &unescape($reply);
5620: }
1.240 www 5621: }
1.242 www 5622: return 'timeout:'.$queryid;
1.240 www 5623: }
5624:
5625: sub courselog_query {
1.241 www 5626: #
5627: # possible filters:
5628: # url: url or symb
5629: # username
5630: # domain
5631: # action: view, submit, grade
5632: # start: timestamp
5633: # end: timestamp
5634: #
1.240 www 5635: my (%filters)=@_;
1.620 albertel 5636: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5637: if ($filters{'url'}) {
5638: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5639: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5640: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5641: }
1.620 albertel 5642: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5643: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5644: return &log_query($cname,$cdom,'courselog',%filters);
5645: }
5646:
5647: sub userlog_query {
1.858 raeburn 5648: #
5649: # possible filters:
5650: # action: log check role
5651: # start: timestamp
5652: # end: timestamp
5653: #
1.240 www 5654: my ($uname,$udom,%filters)=@_;
5655: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5656: }
5657:
1.506 raeburn 5658: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5659:
5660: sub auto_run {
1.508 raeburn 5661: my ($cnum,$cdom) = @_;
1.876 raeburn 5662: my $response = 0;
5663: my $settings;
5664: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5665: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5666: $settings = $domconfig{'autoenroll'};
5667: if ($settings->{'run'} eq '1') {
5668: $response = 1;
5669: }
5670: } else {
1.934 raeburn 5671: my $homeserver;
5672: if (&is_course($cdom,$cnum)) {
5673: $homeserver = &homeserver($cnum,$cdom);
5674: } else {
5675: $homeserver = &domain($cdom,'primary');
5676: }
5677: if ($homeserver ne 'no_host') {
5678: $response = &reply('autorun:'.$cdom,$homeserver);
5679: }
1.876 raeburn 5680: }
1.506 raeburn 5681: return $response;
5682: }
1.776 albertel 5683:
1.506 raeburn 5684: sub auto_get_sections {
1.508 raeburn 5685: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5686: my $homeserver;
5687: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5688: $homeserver = &homeserver($cnum,$cdom);
5689: }
5690: if (!defined($homeserver)) {
5691: if ($cdom =~ /^$match_domain$/) {
5692: $homeserver = &domain($cdom,'primary');
5693: }
5694: }
5695: my @secs;
5696: if (defined($homeserver)) {
5697: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5698: unless ($response eq 'refused') {
5699: @secs = split(/:/,$response);
5700: }
1.506 raeburn 5701: }
5702: return @secs;
5703: }
1.776 albertel 5704:
1.506 raeburn 5705: sub auto_new_course {
1.508 raeburn 5706: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5707: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5708: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5709: return $response;
5710: }
1.776 albertel 5711:
1.506 raeburn 5712: sub auto_validate_courseID {
1.508 raeburn 5713: my ($cnum,$cdom,$inst_course_id) = @_;
5714: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5715: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5716: return $response;
5717: }
1.776 albertel 5718:
1.1007 raeburn 5719: sub auto_validate_instcode {
1.1020 raeburn 5720: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5721: my ($homeserver,$response);
5722: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5723: $homeserver = &homeserver($cnum,$cdom);
5724: }
5725: if (!defined($homeserver)) {
5726: if ($cdom =~ /^$match_domain$/) {
5727: $homeserver = &domain($cdom,'primary');
5728: }
5729: }
5730: my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
1.1020 raeburn 5731: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5732: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5733: return ($outcome,$description);
1.1007 raeburn 5734: }
5735:
1.506 raeburn 5736: sub auto_create_password {
1.873 raeburn 5737: my ($cnum,$cdom,$authparam,$udom) = @_;
5738: my ($homeserver,$response);
1.506 raeburn 5739: my $create_passwd = 0;
5740: my $authchk = '';
1.873 raeburn 5741: if ($udom =~ /^$match_domain$/) {
5742: $homeserver = &domain($udom,'primary');
5743: }
5744: if ($homeserver eq '') {
5745: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5746: $homeserver = &homeserver($cnum,$cdom);
5747: }
5748: }
5749: if ($homeserver eq '') {
5750: $authchk = 'nodomain';
1.506 raeburn 5751: } else {
1.873 raeburn 5752: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5753: if ($response eq 'refused') {
5754: $authchk = 'refused';
5755: } else {
1.901 albertel 5756: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5757: }
1.506 raeburn 5758: }
5759: return ($authparam,$create_passwd,$authchk);
5760: }
5761:
1.706 raeburn 5762: sub auto_photo_permission {
5763: my ($cnum,$cdom,$students) = @_;
5764: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5765: my ($outcome,$perm_reqd,$conditions) =
5766: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5767: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5768: return (undef,undef);
5769: }
1.706 raeburn 5770: return ($outcome,$perm_reqd,$conditions);
5771: }
5772:
5773: sub auto_checkphotos {
5774: my ($uname,$udom,$pid) = @_;
5775: my $homeserver = &homeserver($uname,$udom);
5776: my ($result,$resulttype);
5777: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5778: &escape($uname).':'.&escape($pid),
5779: $homeserver));
1.709 albertel 5780: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5781: return (undef,undef);
5782: }
1.706 raeburn 5783: if ($outcome) {
5784: ($result,$resulttype) = split(/:/,$outcome);
5785: }
5786: return ($result,$resulttype);
5787: }
5788:
5789: sub auto_photochoice {
5790: my ($cnum,$cdom) = @_;
5791: my $homeserver = &homeserver($cnum,$cdom);
5792: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5793: &escape($cdom),
5794: $homeserver)));
1.709 albertel 5795: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5796: return (undef,undef);
5797: }
1.706 raeburn 5798: return ($update,$comment);
5799: }
5800:
5801: sub auto_photoupdate {
5802: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5803: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5804: my $host=&hostname($homeserver);
1.706 raeburn 5805: my $cmd = '';
5806: my $maxtries = 1;
1.800 albertel 5807: foreach my $affiliate (keys(%{$affiliatesref})) {
5808: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5809: }
5810: $cmd =~ s/%%$//;
5811: $cmd = &escape($cmd);
5812: my $query = 'institutionalphotos';
5813: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5814: unless ($queryid=~/^\Q$host\E\_/) {
5815: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5816: return 'error: '.$queryid;
5817: }
5818: my $reply = &get_query_reply($queryid);
5819: my $tries = 1;
5820: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5821: $reply = &get_query_reply($queryid);
5822: $tries ++;
5823: }
5824: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5825: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5826: } else {
5827: my @responses = split(/:/,$reply);
5828: my $outcome = shift(@responses);
5829: foreach my $item (@responses) {
5830: my ($key,$value) = split(/=/,$item);
5831: $$photo{$key} = $value;
5832: }
5833: return $outcome;
5834: }
5835: return 'error';
5836: }
5837:
1.521 raeburn 5838: sub auto_instcode_format {
1.793 albertel 5839: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5840: $cat_order) = @_;
1.521 raeburn 5841: my $courses = '';
1.772 raeburn 5842: my @homeservers;
1.521 raeburn 5843: if ($caller eq 'global') {
1.841 albertel 5844: my %servers = &get_servers($codedom,'library');
5845: foreach my $tryserver (keys(%servers)) {
5846: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5847: push(@homeservers,$tryserver);
5848: }
1.584 raeburn 5849: }
1.1022 raeburn 5850: } elsif ($caller eq 'requests') {
5851: if ($codedom =~ /^$match_domain$/) {
5852: my $chome = &domain($codedom,'primary');
5853: unless ($chome eq 'no_host') {
5854: push(@homeservers,$chome);
5855: }
5856: }
1.521 raeburn 5857: } else {
1.772 raeburn 5858: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5859: }
1.793 albertel 5860: foreach my $code (keys(%{$instcodes})) {
5861: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5862: }
5863: chop($courses);
1.772 raeburn 5864: my $ok_response = 0;
5865: my $response;
5866: while (@homeservers > 0 && $ok_response == 0) {
5867: my $server = shift(@homeservers);
5868: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5869: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5870: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5871: split(/:/,$response);
1.772 raeburn 5872: %{$codes} = (%{$codes},&str2hash($codes_str));
5873: push(@{$codetitles},&str2array($codetitles_str));
5874: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5875: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5876: $ok_response = 1;
5877: }
5878: }
5879: if ($ok_response) {
1.521 raeburn 5880: return 'ok';
1.772 raeburn 5881: } else {
5882: return $response;
1.521 raeburn 5883: }
5884: }
5885:
1.792 raeburn 5886: sub auto_instcode_defaults {
5887: my ($domain,$returnhash,$code_order) = @_;
5888: my @homeservers;
1.841 albertel 5889:
5890: my %servers = &get_servers($domain,'library');
5891: foreach my $tryserver (keys(%servers)) {
5892: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5893: push(@homeservers,$tryserver);
5894: }
1.792 raeburn 5895: }
1.841 albertel 5896:
1.792 raeburn 5897: my $response;
1.841 albertel 5898: foreach my $server (@homeservers) {
1.792 raeburn 5899: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5900: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5901:
5902: foreach my $pair (split(/\&/,$response)) {
5903: my ($name,$value)=split(/\=/,$pair);
5904: if ($name eq 'code_order') {
5905: @{$code_order} = split(/\&/,&unescape($value));
5906: } else {
5907: $returnhash->{&unescape($name)}=&unescape($value);
5908: }
5909: }
5910: return 'ok';
1.792 raeburn 5911: }
1.841 albertel 5912:
5913: return $response;
1.1003 raeburn 5914: }
5915:
5916: sub auto_possible_instcodes {
1.1007 raeburn 5917: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
5918: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
5919: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
5920: return;
5921: }
1.1003 raeburn 5922: my (@homeservers,$uhome);
5923: if (defined(&domain($domain,'primary'))) {
5924: $uhome=&domain($domain,'primary');
5925: push(@homeservers,&domain($domain,'primary'));
5926: } else {
5927: my %servers = &get_servers($domain,'library');
5928: foreach my $tryserver (keys(%servers)) {
5929: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5930: push(@homeservers,$tryserver);
5931: }
5932: }
5933: }
5934: my $response;
5935: foreach my $server (@homeservers) {
5936: $response=&reply('autopossibleinstcodes:'.$domain,$server);
5937: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 5938: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
5939: split(':',$response);
5940: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
5941: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 5942: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 5943: my ($name,$value)=split('=',$item);
5944: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5945: }
5946: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 5947: my ($name,$value)=split('=',$item);
5948: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5949: }
5950: return 'ok';
5951: }
5952: return $response;
5953: }
1.792 raeburn 5954:
1.1010 raeburn 5955: sub auto_courserequest_checks {
5956: my ($dom) = @_;
1.1020 raeburn 5957: my ($homeserver,%validations);
5958: if ($dom =~ /^$match_domain$/) {
5959: $homeserver = &domain($dom,'primary');
5960: }
5961: unless ($homeserver eq 'no_host') {
5962: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
5963: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
5964: my @items = split(/&/,$response);
5965: foreach my $item (@items) {
5966: my ($key,$value) = split('=',$item);
5967: $validations{&unescape($key)} = &thaw_unescape($value);
5968: }
5969: }
5970: }
1.1010 raeburn 5971: return %validations;
5972: }
5973:
1.1020 raeburn 5974: sub auto_courserequest_validation {
5975: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
5976: my ($homeserver,$response);
5977: if ($dom =~ /^$match_domain$/) {
5978: $homeserver = &domain($dom,'primary');
5979: }
5980: unless ($homeserver eq 'no_host') {
1.1021 raeburn 5981:
1.1020 raeburn 5982: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 5983: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 5984: ':'.&escape($instcode).':'.&escape($instseclist),
5985: $homeserver));
5986: }
5987: return $response;
5988: }
5989:
1.777 albertel 5990: sub auto_validate_class_sec {
1.918 raeburn 5991: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5992: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5993: my $ownerlist;
5994: if (ref($owners) eq 'ARRAY') {
5995: $ownerlist = join(',',@{$owners});
5996: } else {
5997: $ownerlist = $owners;
5998: }
1.773 raeburn 5999: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6000: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6001: return $response;
6002: }
6003:
1.679 raeburn 6004: # ------------------------------------------------------- Course Group routines
6005:
6006: sub get_coursegroups {
1.809 raeburn 6007: my ($cdom,$cnum,$group,$namespace) = @_;
6008: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6009: }
6010:
1.679 raeburn 6011: sub modify_coursegroup {
6012: my ($cdom,$cnum,$groupsettings) = @_;
6013: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6014: }
6015:
1.809 raeburn 6016: sub toggle_coursegroup_status {
6017: my ($cdom,$cnum,$group,$action) = @_;
6018: my ($from_namespace,$to_namespace);
6019: if ($action eq 'delete') {
6020: $from_namespace = 'coursegroups';
6021: $to_namespace = 'deleted_groups';
6022: } else {
6023: $from_namespace = 'deleted_groups';
6024: $to_namespace = 'coursegroups';
6025: }
6026: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6027: if (my $tmp = &error(%curr_group)) {
6028: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6029: return ('read error',$tmp);
6030: } else {
6031: my %savedsettings = %curr_group;
1.809 raeburn 6032: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6033: my $deloutcome;
6034: if ($result eq 'ok') {
1.809 raeburn 6035: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6036: } else {
6037: return ('write error',$result);
6038: }
6039: if ($deloutcome eq 'ok') {
6040: return 'ok';
6041: } else {
6042: return ('delete error',$deloutcome);
6043: }
6044: }
6045: }
6046:
1.679 raeburn 6047: sub modify_group_roles {
1.957 raeburn 6048: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6049: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6050: my $role = 'gr/'.&escape($userprivs);
6051: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6052: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6053: if ($result eq 'ok') {
6054: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6055: }
1.679 raeburn 6056: return $result;
6057: }
6058:
6059: sub modify_coursegroup_membership {
6060: my ($cdom,$cnum,$membership) = @_;
6061: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6062: return $result;
6063: }
6064:
1.682 raeburn 6065: sub get_active_groups {
6066: my ($udom,$uname,$cdom,$cnum) = @_;
6067: my $now = time;
6068: my %groups = ();
6069: foreach my $key (keys(%env)) {
1.811 albertel 6070: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6071: my ($start,$end) = split(/\./,$env{$key});
6072: if (($end!=0) && ($end<$now)) { next; }
6073: if (($start!=0) && ($start>$now)) { next; }
6074: if ($1 eq $cdom && $2 eq $cnum) {
6075: $groups{$3} = $env{$key} ;
6076: }
6077: }
6078: }
6079: return %groups;
6080: }
6081:
1.683 raeburn 6082: sub get_group_membership {
6083: my ($cdom,$cnum,$group) = @_;
6084: return(&dump('groupmembership',$cdom,$cnum,$group));
6085: }
6086:
6087: sub get_users_groups {
6088: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6089: my @usersgroups;
1.683 raeburn 6090: my $cachetime=1800;
6091:
6092: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6093: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6094: if (defined($cached)) {
1.734 albertel 6095: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6096: } else {
6097: $grouplist = '';
1.816 raeburn 6098: my $courseurl = &courseid_to_courseurl($courseid);
6099: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6100: my $access_end = $env{'course.'.$courseid.
6101: '.default_enrollment_end_date'};
6102: my $now = time;
6103: foreach my $key (keys(%roleshash)) {
6104: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6105: my $group = $1;
6106: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6107: my $start = $2;
6108: my $end = $1;
6109: if ($start == -1) { next; } # deleted from group
6110: if (($start!=0) && ($start>$now)) { next; }
6111: if (($end!=0) && ($end<$now)) {
6112: if ($access_end && $access_end < $now) {
6113: if ($access_end - $end < 86400) {
6114: push(@usersgroups,$group);
1.733 raeburn 6115: }
6116: }
1.817 raeburn 6117: next;
1.733 raeburn 6118: }
1.817 raeburn 6119: push(@usersgroups,$group);
1.683 raeburn 6120: }
6121: }
6122: }
1.817 raeburn 6123: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6124: $grouplist = join(':',@usersgroups);
6125: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6126: }
1.733 raeburn 6127: return @usersgroups;
1.683 raeburn 6128: }
6129:
6130: sub devalidate_getgroups_cache {
6131: my ($udom,$uname,$cdom,$cnum)=@_;
6132: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6133:
1.683 raeburn 6134: my $hashid="$udom:$uname:$courseid";
6135: &devalidate_cache_new('getgroups',$hashid);
6136: }
6137:
1.12 www 6138: # ------------------------------------------------------------------ Plain Text
6139:
6140: sub plaintext {
1.988 raeburn 6141: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6142: if ($short =~ m{^cr/}) {
1.758 albertel 6143: return (split('/',$short))[-1];
6144: }
1.742 raeburn 6145: if (!defined($cid)) {
6146: $cid = $env{'request.course.id'};
6147: }
6148: my %rolenames = (
1.1008 raeburn 6149: Course => 'std',
6150: Community => 'alt1',
1.742 raeburn 6151: );
1.1037 raeburn 6152: if ($cid ne '') {
6153: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6154: unless ($forcedefault) {
6155: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6156: &Apache::lonlocal::mt_escape(\$roletext);
6157: return &Apache::lonlocal::mt($roletext);
6158: }
6159: }
6160: }
6161: if ((defined($type)) && (defined($rolenames{$type})) &&
6162: (defined($rolenames{$type})) &&
6163: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6164: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6165: } elsif ($cid ne '') {
6166: my $crstype = $env{'course.'.$cid.'.type'};
6167: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6168: (defined($prp{$short}{$rolenames{$crstype}}))) {
6169: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6170: }
1.742 raeburn 6171: }
1.1037 raeburn 6172: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6173: }
6174:
6175: # ----------------------------------------------------------------- Assign Role
6176:
6177: sub assignrole {
1.957 raeburn 6178: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6179: $context)=@_;
1.21 www 6180: my $mrole;
6181: if ($role =~ /^cr\//) {
1.393 www 6182: my $cwosec=$url;
1.811 albertel 6183: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6184: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6185: my $refused = 1;
6186: if ($context eq 'requestcourses') {
6187: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6188: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6189: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6190: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6191: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6192: if ($crsenv{'internal.courseowner'} eq
6193: $env{'user.name'}.':'.$env{'user.domain'}) {
6194: $refused = '';
6195: }
6196: }
6197: }
6198: }
6199: }
6200: if ($refused) {
6201: &logthis('Refused custom assignrole: '.
6202: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6203: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6204: return 'refused';
6205: }
1.104 www 6206: }
1.21 www 6207: $mrole='cr';
1.678 raeburn 6208: } elsif ($role =~ /^gr\//) {
6209: my $cwogrp=$url;
1.811 albertel 6210: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6211: unless (&allowed('mdg',$cwogrp)) {
6212: &logthis('Refused group assignrole: '.
6213: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6214: $env{'user.name'}.' at '.$env{'user.domain'});
6215: return 'refused';
6216: }
6217: $mrole='gr';
1.21 www 6218: } else {
1.82 www 6219: my $cwosec=$url;
1.811 albertel 6220: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6221: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6222: my $refused;
6223: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6224: if (!(&allowed('c'.$role,$url))) {
6225: $refused = 1;
6226: }
6227: } else {
6228: $refused = 1;
6229: }
1.947 raeburn 6230: if ($refused) {
1.1045 raeburn 6231: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6232: if (!$selfenroll && $context eq 'course') {
6233: my %crsenv;
6234: if ($role eq 'cc' || $role eq 'co') {
6235: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6236: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6237: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6238: if ($crsenv{'internal.courseowner'} eq
6239: $env{'user.name'}.':'.$env{'user.domain'}) {
6240: $refused = '';
6241: }
6242: }
6243: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6244: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6245: if ($crsenv{'internal.courseowner'} eq
6246: $env{'user.name'}.':'.$env{'user.domain'}) {
6247: $refused = '';
6248: }
6249: }
6250: }
6251: }
6252: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6253: $refused = '';
1.1017 raeburn 6254: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6255: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6256: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6257: my $wrongcc;
6258: if ($cnum =~ /^$match_community$/) {
6259: $wrongcc = 1 if ($role eq 'cc');
6260: } else {
6261: $wrongcc = 1 if ($role eq 'co');
6262: }
6263: unless ($wrongcc) {
6264: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6265: if ($crsenv{'internal.courseowner'} eq
6266: $env{'user.name'}.':'.$env{'user.domain'}) {
6267: $refused = '';
6268: }
1.1017 raeburn 6269: }
6270: }
6271: }
6272: if ($refused) {
1.947 raeburn 6273: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6274: ' '.$role.' '.$end.' '.$start.' by '.
6275: $env{'user.name'}.' at '.$env{'user.domain'});
6276: return 'refused';
6277: }
1.932 raeburn 6278: }
1.104 www 6279: }
1.21 www 6280: $mrole=$role;
6281: }
1.620 albertel 6282: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6283: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6284: if ($end) { $command.='_'.$end; }
1.21 www 6285: if ($start) {
6286: if ($end) {
1.81 www 6287: $command.='_'.$start;
1.21 www 6288: } else {
1.81 www 6289: $command.='_0_'.$start;
1.21 www 6290: }
6291: }
1.739 raeburn 6292: my $origstart = $start;
6293: my $origend = $end;
1.957 raeburn 6294: my $delflag;
1.357 www 6295: # actually delete
6296: if ($deleteflag) {
1.373 www 6297: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6298: # modify command to delete the role
1.620 albertel 6299: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6300: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6301: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6302: # set start and finish to negative values for userrolelog
6303: $start=-1;
6304: $end=-1;
1.957 raeburn 6305: $delflag = 1;
1.357 www 6306: }
6307: }
6308: # send command
1.349 www 6309: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6310: # log new user role if status is ok
1.349 www 6311: if ($answer eq 'ok') {
1.663 raeburn 6312: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6313: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6314: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6315: unless ($role =~ /^gr/) {
6316: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6317: $origstart,$selfenroll,$context);
1.739 raeburn 6318: }
1.1053 raeburn 6319: if ($role eq 'cc') {
6320: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6321: }
1.349 www 6322: }
6323: return $answer;
1.169 harris41 6324: }
6325:
1.1053 raeburn 6326: sub autoupdate_coowners {
6327: my ($url,$end,$start,$uname,$udom) = @_;
6328: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6329: if (($cdom ne '') && ($cnum ne '')) {
6330: my $now = time;
6331: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6332: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6333: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6334: my $instcode = $coursehash{'internal.coursecode'};
6335: if ($instcode ne '') {
1.1056 raeburn 6336: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6337: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6338: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6339: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6340: if ($result eq 'valid') {
6341: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6342: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6343: push(@newcoowners,$coowner);
6344: }
6345: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6346: push(@newcoowners,$uname.':'.$udom);
6347: }
6348: @newcoowners = sort(@newcoowners);
6349: } else {
6350: push(@newcoowners,$uname.':'.$udom);
6351: }
6352: } else {
6353: if ($coursehash{'internal.co-owners'}) {
6354: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6355: unless ($coowner eq $uname.':'.$udom) {
6356: push(@newcoowners,$coowner);
6357: }
6358: }
6359: unless (@newcoowners > 0) {
6360: $delcoowners = 1;
6361: $coowners = '';
6362: }
6363: }
6364: }
6365: if (@newcoowners || $delcoowners) {
6366: &store_coowners($cdom,$cnum,$coursehash{'home'},
6367: $delcoowners,@newcoowners);
6368: }
6369: }
6370: }
6371: }
6372: }
6373: }
6374: }
6375:
6376: sub store_coowners {
6377: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6378: my $cid = $cdom.'_'.$cnum;
6379: my ($coowners,$delresult,$putresult);
6380: if (@newcoowners) {
6381: $coowners = join(',',@newcoowners);
6382: my %coownershash = (
6383: 'internal.co-owners' => $coowners,
6384: );
6385: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6386: if ($putresult eq 'ok') {
6387: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6388: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6389: }
6390: }
6391: }
6392: if ($delcoowners) {
6393: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6394: if ($delresult eq 'ok') {
6395: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6396: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6397: }
6398: }
6399: }
6400: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6401: my %crsinfo =
6402: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6403: if (ref($crsinfo{$cid}) eq 'HASH') {
6404: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6405: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6406: }
6407: }
6408: }
6409:
1.169 harris41 6410: # -------------------------------------------------- Modify user authentication
1.197 www 6411: # Overrides without validation
6412:
1.169 harris41 6413: sub modifyuserauth {
6414: my ($udom,$uname,$umode,$upass)=@_;
6415: my $uhome=&homeserver($uname,$udom);
1.197 www 6416: unless (&allowed('mau',$udom)) { return 'refused'; }
6417: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6418: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6419: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6420: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6421: &escape($upass),$uhome);
1.620 albertel 6422: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6423: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6424: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6425: &log($udom,,$uname,$uhome,
1.620 albertel 6426: 'Authentication changed by '.$env{'user.domain'}.', '.
6427: $env{'user.name'}.', '.$umode.
1.197 www 6428: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6429: unless ($reply eq 'ok') {
1.197 www 6430: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6431: return 'error: '.$reply;
6432: }
1.170 harris41 6433: return 'ok';
1.80 www 6434: }
6435:
1.81 www 6436: # --------------------------------------------------------------- Modify a user
1.80 www 6437:
1.81 www 6438: sub modifyuser {
1.206 matthew 6439: my ($udom, $uname, $uid,
6440: $umode, $upass, $first,
6441: $middle, $last, $gene,
1.1058 raeburn 6442: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6443: $udom= &LONCAPA::clean_domain($udom);
6444: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6445: my $showcandelete = 'none';
6446: if (ref($candelete) eq 'ARRAY') {
6447: if (@{$candelete} > 0) {
6448: $showcandelete = join(', ',@{$candelete});
6449: }
6450: }
1.81 www 6451: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6452: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6453: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6454: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6455: ' desiredhome not specified').
1.620 albertel 6456: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6457: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6458: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 6459: # ----------------------------------------------------------------- Create User
1.406 albertel 6460: if (($uhome eq 'no_host') &&
6461: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6462: my $unhome='';
1.844 albertel 6463: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6464: $unhome = $desiredhome;
1.620 albertel 6465: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6466: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6467: } else { # load balancing routine for determining $unhome
1.81 www 6468: my $loadm=10000000;
1.841 albertel 6469: my %servers = &get_servers($udom,'library');
6470: foreach my $tryserver (keys(%servers)) {
6471: my $answer=reply('load',$tryserver);
6472: if (($answer=~/\d+/) && ($answer<$loadm)) {
6473: $loadm=$answer;
6474: $unhome=$tryserver;
6475: }
1.80 www 6476: }
6477: }
6478: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6479: return 'error: unable to find a home server for '.$uname.
6480: ' in domain '.$udom;
1.80 www 6481: }
6482: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6483: &escape($upass),$unhome);
6484: unless ($reply eq 'ok') {
6485: return 'error: '.$reply;
6486: }
1.230 stredwic 6487: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6488: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6489: return 'error: unable verify users home machine.';
1.80 www 6490: }
1.209 matthew 6491: } # End of creation of new user
1.80 www 6492: # ---------------------------------------------------------------------- Add ID
6493: if ($uid) {
6494: $uid=~tr/A-Z/a-z/;
6495: my %uidhash=&idrget($udom,$uname);
1.196 www 6496: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6497: && (!$forceid)) {
1.80 www 6498: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6499: return 'error: user id "'.$uid.'" does not match '.
6500: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6501: }
6502: } else {
6503: &idput($udom,($uname => $uid));
6504: }
6505: }
6506: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6507: my @tmp=&get('environment',
1.899 raeburn 6508: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6509: 'permanentemail','inststatus'],
1.134 albertel 6510: $udom,$uname);
1.313 matthew 6511: my %names;
6512: if ($tmp[0] =~ m/^error:.*/) {
6513: %names=();
6514: } else {
6515: %names = @tmp;
6516: }
1.388 www 6517: #
1.1058 raeburn 6518: # If name, email and/or uid are blank (e.g., because an uploaded file
6519: # of users did not contain them), do not overwrite existing values
6520: # unless field is in $candelete array ref.
6521: #
6522:
6523: my @fields = ('firstname','middlename','lastname','generation',
6524: 'permanentemail','id');
6525: my %newvalues;
6526: if (ref($candelete) eq 'ARRAY') {
6527: foreach my $field (@fields) {
6528: if (grep(/^\Q$field\E$/,@{$candelete})) {
6529: if ($field eq 'firstname') {
6530: $names{$field} = $first;
6531: } elsif ($field eq 'middlename') {
6532: $names{$field} = $middle;
6533: } elsif ($field eq 'lastname') {
6534: $names{$field} = $last;
6535: } elsif ($field eq 'generation') {
6536: $names{$field} = $gene;
6537: } elsif ($field eq 'permanentemail') {
6538: $names{$field} = $email;
6539: } elsif ($field eq 'id') {
6540: $names{$field} = $uid;
6541: }
6542: }
6543: }
6544: }
1.388 www 6545: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6546: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6547: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6548: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6549: if ($email) {
6550: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6551: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6552: }
1.899 raeburn 6553: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6554: if (defined($inststatus)) {
6555: $names{'inststatus'} = '';
6556: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6557: if (ref($usertypes) eq 'HASH') {
6558: my @okstatuses;
6559: foreach my $item (split(/:/,$inststatus)) {
6560: if (defined($usertypes->{$item})) {
6561: push(@okstatuses,$item);
6562: }
6563: }
6564: if (@okstatuses) {
6565: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6566: }
6567: }
6568: }
1.134 albertel 6569: my $reply = &put('environment', \%names, $udom,$uname);
6570: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 6571: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 6572: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 6573: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6574: $umode.', '.$first.', '.$middle.', '.
6575: $last.', '.$gene.', '.$email.', '.$inststatus;
6576: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6577: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6578: } else {
6579: $logmsg .= ' during self creation';
6580: }
6581: &logthis($logmsg);
1.134 albertel 6582: return 'ok';
1.80 www 6583: }
6584:
1.81 www 6585: # -------------------------------------------------------------- Modify student
1.80 www 6586:
1.81 www 6587: sub modifystudent {
6588: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6589: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6590: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6591: if (!$cid) {
1.620 albertel 6592: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6593: return 'not_in_class';
6594: }
1.80 www 6595: }
6596: # --------------------------------------------------------------- Make the user
1.81 www 6597: my $reply=&modifyuser
1.209 matthew 6598: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6599: $desiredhome,$email,$inststatus);
1.80 www 6600: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6601: # This will cause &modify_student_enrollment to get the uid from the
6602: # students environment
6603: $uid = undef if (!$forceid);
1.455 albertel 6604: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6605: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6606: return $reply;
6607: }
6608:
6609: sub modify_student_enrollment {
1.957 raeburn 6610: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6611: my ($cdom,$cnum,$chome);
6612: if (!$cid) {
1.620 albertel 6613: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6614: return 'not_in_class';
6615: }
1.620 albertel 6616: $cdom=$env{'course.'.$cid.'.domain'};
6617: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6618: } else {
6619: ($cdom,$cnum)=split(/_/,$cid);
6620: }
1.620 albertel 6621: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6622: if (!$chome) {
1.457 raeburn 6623: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6624: }
1.455 albertel 6625: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6626: # Make sure the user exists
1.81 www 6627: my $uhome=&homeserver($uname,$udom);
6628: if (($uhome eq '') || ($uhome eq 'no_host')) {
6629: return 'error: no such user';
6630: }
1.297 matthew 6631: # Get student data if we were not given enough information
6632: if (!defined($first) || $first eq '' ||
6633: !defined($last) || $last eq '' ||
6634: !defined($uid) || $uid eq '' ||
6635: !defined($middle) || $middle eq '' ||
6636: !defined($gene) || $gene eq '') {
1.294 matthew 6637: # They did not supply us with enough data to enroll the student, so
6638: # we need to pick up more information.
1.297 matthew 6639: my %tmp = &get('environment',
1.294 matthew 6640: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6641: ,$udom,$uname);
6642:
1.800 albertel 6643: #foreach my $key (keys(%tmp)) {
6644: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6645: #}
1.294 matthew 6646: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6647: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6648: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6649: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6650: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6651: }
1.556 albertel 6652: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6653: my $reply=cput('classlist',
6654: {"$uname:$udom" =>
1.515 raeburn 6655: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6656: $cdom,$cnum);
1.81 www 6657: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6658: return 'error: '.$reply;
1.652 albertel 6659: } else {
6660: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6661: }
1.297 matthew 6662: # Add student role to user
1.83 www 6663: my $uurl='/'.$cid;
1.81 www 6664: $uurl=~s/\_/\//g;
6665: if ($usec) {
6666: $uurl.='/'.$usec;
6667: }
1.957 raeburn 6668: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6669: }
6670:
1.556 albertel 6671: sub format_name {
6672: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6673: my $name;
6674: if ($first ne 'lastname') {
6675: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6676: } else {
6677: if ($lastname=~/\S/) {
6678: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6679: $name=~s/\s+,/,/;
6680: } else {
6681: $name.= $firstname.' '.$middlename.' '.$generation;
6682: }
6683: }
6684: $name=~s/^\s+//;
6685: $name=~s/\s+$//;
6686: $name=~s/\s+/ /g;
6687: return $name;
6688: }
6689:
1.84 www 6690: # ------------------------------------------------- Write to course preferences
6691:
6692: sub writecoursepref {
6693: my ($courseid,%prefs)=@_;
6694: $courseid=~s/^\///;
6695: $courseid=~s/\_/\//g;
6696: my ($cdomain,$cnum)=split(/\//,$courseid);
6697: my $chome=homeserver($cnum,$cdomain);
6698: if (($chome eq '') || ($chome eq 'no_host')) {
6699: return 'error: no such course';
6700: }
6701: my $cstring='';
1.800 albertel 6702: foreach my $pref (keys(%prefs)) {
6703: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6704: }
1.84 www 6705: $cstring=~s/\&$//;
6706: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6707: }
6708:
6709: # ---------------------------------------------------------- Make/modify course
6710:
6711: sub createcourse {
1.741 raeburn 6712: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6713: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 6714: $url=&declutter($url);
6715: my $cid='';
1.1028 raeburn 6716: if ($context eq 'requestcourses') {
6717: my $can_create = 0;
6718: my ($ownername,$ownerdom) = split(':',$course_owner);
6719: if ($udom eq $ownerdom) {
6720: if (&usertools_access($ownername,$ownerdom,$category,undef,
6721: $context)) {
6722: $can_create = 1;
6723: }
6724: } else {
6725: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6726: $category);
6727: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6728: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6729: if (@curr > 0) {
6730: my @options = qw(approval validate autolimit);
6731: my $optregex = join('|',@options);
6732: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6733: $can_create = 1;
6734: }
6735: }
6736: }
6737: }
6738: if ($can_create) {
6739: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6740: unless (&allowed('ccc',$udom)) {
6741: return 'refused';
6742: }
1.1017 raeburn 6743: }
6744: } else {
6745: return 'refused';
6746: }
1.1028 raeburn 6747: } elsif (!&allowed('ccc',$udom)) {
6748: return 'refused';
1.84 www 6749: }
1.1011 raeburn 6750: # --------------------------------------------------------------- Get Unique ID
6751: my $uname;
6752: if ($cnum =~ /^$match_courseid$/) {
6753: my $chome=&homeserver($cnum,$udom,'true');
6754: if (($chome eq '') || ($chome eq 'no_host')) {
6755: $uname = $cnum;
6756: } else {
1.1038 raeburn 6757: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6758: }
6759: } else {
1.1038 raeburn 6760: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6761: }
6762: return $uname if ($uname =~ /^error/);
6763: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 6764: if (!defined($course_server)) {
6765: if (defined(&domain($udom,'primary'))) {
6766: $course_server = &domain($udom,'primary');
6767: } else {
6768: $course_server = $env{'user.home'};
6769: }
6770: }
6771: my %host_servers =
6772: &Apache::lonnet::get_servers($udom,'library');
6773: unless ($host_servers{$course_server}) {
6774: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 6775: }
1.84 www 6776: # ------------------------------------------------------------- Make the course
6777: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6778: $course_server);
1.84 www 6779: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 6780: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6781: if (($uhome eq '') || ($uhome eq 'no_host')) {
6782: return 'error: no such course';
6783: }
1.271 www 6784: # ----------------------------------------------------------------- Course made
1.516 raeburn 6785: # log existence
1.1029 raeburn 6786: my $now = time;
1.918 raeburn 6787: my $newcourse = {
6788: $udom.'_'.$uname => {
1.921 raeburn 6789: description => $description,
6790: inst_code => $inst_code,
6791: owner => $course_owner,
6792: type => $crstype,
1.1029 raeburn 6793: creator => $env{'user.name'}.':'.
6794: $env{'user.domain'},
6795: created => $now,
6796: context => $context,
1.918 raeburn 6797: },
6798: };
1.921 raeburn 6799: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6800: # set toplevel url
1.271 www 6801: my $topurl=$url;
6802: unless ($nonstandard) {
6803: # ------------------------------------------ For standard courses, make top url
6804: my $mapurl=&clutter($url);
1.278 www 6805: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6806: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6807: <map>
6808: <resource id="1" type="start"></resource>
6809: <resource id="2" src="$mapurl"></resource>
6810: <resource id="3" type="finish"></resource>
6811: <link index="1" from="1" to="2"></link>
6812: <link index="2" from="2" to="3"></link>
6813: </map>
6814: ENDINITMAP
6815: $topurl=&declutter(
1.638 albertel 6816: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6817: );
6818: }
6819: # ----------------------------------------------------------- Write preferences
1.84 www 6820: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 6821: ('description' => $description,
6822: 'url' => $topurl,
6823: 'internal.creator' => $env{'user.name'}.':'.
6824: $env{'user.domain'},
6825: 'internal.created' => $now,
6826: 'internal.creationcontext' => $context)
6827: );
1.84 www 6828: return '/'.$udom.'/'.$uname;
6829: }
6830:
1.1011 raeburn 6831: # ------------------------------------------------------------------- Create ID
6832: sub generate_coursenum {
1.1038 raeburn 6833: my ($udom,$crstype) = @_;
1.1011 raeburn 6834: my $domdesc = &domain($udom);
6835: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 6836: my $first;
6837: if ($crstype eq 'Community') {
6838: $first = '0';
6839: } else {
6840: $first = int(1+rand(9));
6841: }
6842: my $uname=$first.
1.1011 raeburn 6843: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6844: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6845: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6846: # ----------------------------------------------- Make sure that does not exist
6847: my $uhome=&homeserver($uname,$udom,'true');
6848: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 6849: if ($crstype eq 'Community') {
6850: $first = '0';
6851: } else {
6852: $first = int(1+rand(9));
6853: }
6854: $uname=$first.
1.1011 raeburn 6855: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6856: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6857: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6858: $uhome=&homeserver($uname,$udom,'true');
6859: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6860: return 'error: unable to generate unique course-ID';
6861: }
6862: }
6863: return $uname;
6864: }
6865:
1.813 albertel 6866: sub is_course {
6867: my ($cdom,$cnum) = @_;
6868: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6869: undef,'.');
1.813 albertel 6870: if (exists($courses{$cdom.'_'.$cnum})) {
6871: return 1;
6872: }
6873: return 0;
6874: }
6875:
1.1015 raeburn 6876: sub store_userdata {
6877: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 6878: my $result;
1.1016 raeburn 6879: if ($datakey ne '') {
1.1013 raeburn 6880: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 6881: if ($udom eq '' || $uname eq '') {
6882: $udom = $env{'user.domain'};
6883: $uname = $env{'user.name'};
6884: }
6885: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 6886: if (($uhome eq '') || ($uhome eq 'no_host')) {
6887: $result = 'error: no_host';
6888: } else {
6889: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
6890: $storehash->{'host'} = $perlvar{'lonHostID'};
6891:
6892: my $namevalue='';
6893: foreach my $key (keys(%{$storehash})) {
6894: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6895: }
6896: $namevalue=~s/\&$//;
6897: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 6898: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 6899: }
6900: } else {
6901: $result = 'error: data to store was not a hash reference';
6902: }
6903: } else {
6904: $result= 'error: invalid requestkey';
6905: }
6906: return $result;
6907: }
6908:
1.21 www 6909: # ---------------------------------------------------------- Assign Custom Role
6910:
6911: sub assigncustomrole {
1.957 raeburn 6912: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6913: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6914: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6915: }
6916:
6917: # ----------------------------------------------------------------- Revoke Role
6918:
6919: sub revokerole {
1.957 raeburn 6920: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6921: my $now=time;
1.965 raeburn 6922: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6923: }
6924:
6925: # ---------------------------------------------------------- Revoke Custom Role
6926:
6927: sub revokecustomrole {
1.957 raeburn 6928: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6929: my $now=time;
1.357 www 6930: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6931: $deleteflag,$selfenroll,$context);
1.17 www 6932: }
6933:
1.533 banghart 6934: # ------------------------------------------------------------ Disk usage
1.535 albertel 6935: sub diskusage {
1.955 raeburn 6936: my ($udom,$uname,$directorypath,$getpropath)=@_;
6937: $directorypath =~ s/\/$//;
6938: my $listing=&reply('du2:'.&escape($directorypath).':'
6939: .&escape($getpropath).':'.&escape($uname).':'
6940: .&escape($udom),homeserver($uname,$udom));
6941: if ($listing eq 'unknown_cmd') {
6942: if ($getpropath) {
6943: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6944: }
6945: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6946: }
1.514 albertel 6947: return $listing;
1.512 banghart 6948: }
6949:
1.566 banghart 6950: sub is_locked {
6951: my ($file_name, $domain, $user) = @_;
6952: my @check;
6953: my $is_locked;
6954: push @check, $file_name;
1.613 albertel 6955: my %locked = &get('file_permissions',\@check,
1.620 albertel 6956: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6957: my ($tmp)=keys(%locked);
6958: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6959:
1.566 banghart 6960: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6961: $is_locked = 'false';
6962: foreach my $entry (@{$locked{$file_name}}) {
6963: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6964: $is_locked = 'true';
6965: last;
1.745 raeburn 6966: }
6967: }
1.566 banghart 6968: } else {
6969: $is_locked = 'false';
6970: }
6971: }
6972:
1.759 albertel 6973: sub declutter_portfile {
6974: my ($file) = @_;
1.833 albertel 6975: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6976: return $file;
6977: }
6978:
1.559 banghart 6979: # ------------------------------------------------------------- Mark as Read Only
6980:
6981: sub mark_as_readonly {
6982: my ($domain,$user,$files,$what) = @_;
1.613 albertel 6983: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6984: my ($tmp)=keys(%current_permissions);
6985: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 6986: foreach my $file (@{$files}) {
1.759 albertel 6987: $file = &declutter_portfile($file);
1.561 banghart 6988: push(@{$current_permissions{$file}},$what);
1.559 banghart 6989: }
1.613 albertel 6990: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6991: return;
6992: }
6993:
1.572 banghart 6994: # ------------------------------------------------------------Save Selected Files
6995:
6996: sub save_selected_files {
6997: my ($user, $path, @files) = @_;
6998: my $filename = $user."savedfiles";
1.573 banghart 6999: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7000: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7001: foreach my $file (@files) {
1.620 albertel 7002: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7003: }
7004: foreach my $file (@other_files) {
1.574 banghart 7005: print (OUT $file."\n");
1.572 banghart 7006: }
1.574 banghart 7007: close (OUT);
1.572 banghart 7008: return 'ok';
7009: }
7010:
1.574 banghart 7011: sub clear_selected_files {
7012: my ($user) = @_;
7013: my $filename = $user."savedfiles";
7014: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7015: print (OUT undef);
7016: close (OUT);
7017: return ("ok");
7018: }
7019:
1.572 banghart 7020: sub files_in_path {
7021: my ($user, $path) = @_;
7022: my $filename = $user."savedfiles";
7023: my %return_files;
1.574 banghart 7024: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7025: while (my $line_in = <IN>) {
1.574 banghart 7026: chomp ($line_in);
7027: my @paths_and_file = split (m!/!, $line_in);
7028: my $file_part = pop (@paths_and_file);
7029: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7030: $path_part.='/';
7031: my $path_and_file = $path_part.$file_part;
7032: if ($path_part eq $path) {
7033: $return_files{$file_part}= 'selected';
7034: }
7035: }
1.574 banghart 7036: close (IN);
7037: return (\%return_files);
1.572 banghart 7038: }
7039:
7040: # called in portfolio select mode, to show files selected NOT in current directory
7041: sub files_not_in_path {
7042: my ($user, $path) = @_;
7043: my $filename = $user."savedfiles";
7044: my @return_files;
7045: my $path_part;
1.800 albertel 7046: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7047: while (my $line = <IN>) {
1.572 banghart 7048: #ok, I know it's clunky, but I want it to work
1.800 albertel 7049: my @paths_and_file = split(m|/|, $line);
7050: my $file_part = pop(@paths_and_file);
7051: chomp($file_part);
7052: my $path_part = join('/', @paths_and_file);
1.572 banghart 7053: $path_part .= '/';
7054: my $path_and_file = $path_part.$file_part;
7055: if ($path_part ne $path) {
1.800 albertel 7056: push(@return_files, ($path_and_file));
1.572 banghart 7057: }
7058: }
1.800 albertel 7059: close(OUT);
1.574 banghart 7060: return (@return_files);
1.572 banghart 7061: }
7062:
1.745 raeburn 7063: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7064:
1.745 raeburn 7065: sub get_portfile_permissions {
7066: my ($domain,$user) = @_;
1.613 albertel 7067: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7068: my ($tmp)=keys(%current_permissions);
7069: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7070: return \%current_permissions;
7071: }
7072:
7073: #---------------------------------------------Get portfolio file access controls
7074:
1.749 raeburn 7075: sub get_access_controls {
1.745 raeburn 7076: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7077: my %access;
7078: my $real_file = $file;
7079: $file =~ s/\.meta$//;
1.745 raeburn 7080: if (defined($file)) {
1.749 raeburn 7081: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7082: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7083: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7084: }
7085: }
1.745 raeburn 7086: } else {
1.749 raeburn 7087: foreach my $key (keys(%{$current_permissions})) {
7088: if ($key =~ /\0accesscontrol$/) {
7089: if (defined($group)) {
7090: if ($key !~ m-^\Q$group\E/-) {
7091: next;
7092: }
7093: }
7094: my ($fullpath) = split(/\0/,$key);
7095: if (ref($$current_permissions{$key}) eq 'HASH') {
7096: foreach my $control (keys(%{$$current_permissions{$key}})) {
7097: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7098: }
7099: }
7100: }
7101: }
7102: }
7103: return %access;
7104: }
7105:
7106: sub modify_access_controls {
7107: my ($file_name,$changes,$domain,$user)=@_;
7108: my ($outcome,$deloutcome);
7109: my %store_permissions;
7110: my %new_values;
7111: my %new_control;
7112: my %translation;
7113: my @deletions = ();
7114: my $now = time;
7115: if (exists($$changes{'activate'})) {
7116: if (ref($$changes{'activate'}) eq 'HASH') {
7117: my @newitems = sort(keys(%{$$changes{'activate'}}));
7118: my $numnew = scalar(@newitems);
7119: for (my $i=0; $i<$numnew; $i++) {
7120: my $newkey = $newitems[$i];
7121: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7122: if ($newkey =~ /^\d+:/) {
7123: $newkey =~ s/^(\d+)/$newid/;
7124: $translation{$1} = $newid;
7125: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7126: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7127: $translation{$1} = $newid;
7128: }
1.749 raeburn 7129: $new_values{$file_name."\0".$newkey} =
7130: $$changes{'activate'}{$newitems[$i]};
7131: $new_control{$newkey} = $now;
7132: }
7133: }
7134: }
7135: my %todelete;
7136: my %changed_items;
7137: foreach my $action ('delete','update') {
7138: if (exists($$changes{$action})) {
7139: if (ref($$changes{$action}) eq 'HASH') {
7140: foreach my $key (keys(%{$$changes{$action}})) {
7141: my ($itemnum) = ($key =~ /^([^:]+):/);
7142: if ($action eq 'delete') {
7143: $todelete{$itemnum} = 1;
7144: } else {
7145: $changed_items{$itemnum} = $key;
7146: }
7147: }
1.745 raeburn 7148: }
7149: }
1.749 raeburn 7150: }
7151: # get lock on access controls for file.
7152: my $lockhash = {
7153: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7154: ':'.$env{'user.domain'},
7155: };
7156: my $tries = 0;
7157: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7158:
7159: while (($gotlock ne 'ok') && $tries <3) {
7160: $tries ++;
7161: sleep 1;
7162: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7163: }
7164: if ($gotlock eq 'ok') {
7165: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7166: my ($tmp)=keys(%curr_permissions);
7167: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7168: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7169: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7170: if (ref($curr_controls) eq 'HASH') {
7171: foreach my $control_item (keys(%{$curr_controls})) {
7172: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7173: if (defined($todelete{$itemnum})) {
7174: push(@deletions,$file_name."\0".$control_item);
7175: } else {
7176: if (defined($changed_items{$itemnum})) {
7177: $new_control{$changed_items{$itemnum}} = $now;
7178: push(@deletions,$file_name."\0".$control_item);
7179: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7180: } else {
7181: $new_control{$control_item} = $$curr_controls{$control_item};
7182: }
7183: }
1.745 raeburn 7184: }
7185: }
7186: }
1.970 raeburn 7187: my ($group);
7188: if (&is_course($domain,$user)) {
7189: ($group,my $file) = split(/\//,$file_name,2);
7190: }
1.749 raeburn 7191: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7192: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7193: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7194: # remove lock
7195: my @del_lock = ($file_name."\0".'locked_access_records');
7196: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7197: my $sqlresult =
1.970 raeburn 7198: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7199: $group);
1.749 raeburn 7200: } else {
7201: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7202: }
1.749 raeburn 7203: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7204: }
7205:
1.827 raeburn 7206: sub make_public_indefinitely {
7207: my ($requrl) = @_;
7208: my $now = time;
7209: my $action = 'activate';
7210: my $aclnum = 0;
7211: if (&is_portfolio_url($requrl)) {
7212: my (undef,$udom,$unum,$file_name,$group) =
7213: &parse_portfolio_url($requrl);
7214: my $current_perms = &get_portfile_permissions($udom,$unum);
7215: my %access_controls = &get_access_controls($current_perms,
7216: $group,$file_name);
7217: foreach my $key (keys(%{$access_controls{$file_name}})) {
7218: my ($num,$scope,$end,$start) =
7219: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7220: if ($scope eq 'public') {
7221: if ($start <= $now && $end == 0) {
7222: $action = 'none';
7223: } else {
7224: $action = 'update';
7225: $aclnum = $num;
7226: }
7227: last;
7228: }
7229: }
7230: if ($action eq 'none') {
7231: return 'ok';
7232: } else {
7233: my %changes;
7234: my $newend = 0;
7235: my $newstart = $now;
7236: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7237: $changes{$action}{$newkey} = {
7238: type => 'public',
7239: time => {
7240: start => $newstart,
7241: end => $newend,
7242: },
7243: };
7244: my ($outcome,$deloutcome,$new_values,$translation) =
7245: &modify_access_controls($file_name,\%changes,$udom,$unum);
7246: return $outcome;
7247: }
7248: } else {
7249: return 'invalid';
7250: }
7251: }
7252:
1.745 raeburn 7253: #------------------------------------------------------Get Marked as Read Only
7254:
7255: sub get_marked_as_readonly {
7256: my ($domain,$user,$what,$group) = @_;
7257: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7258: my @readonly_files;
1.629 banghart 7259: my $cmp1=$what;
7260: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7261: while (my ($file_name,$value) = each(%{$current_permissions})) {
7262: if (defined($group)) {
7263: if ($file_name !~ m-^\Q$group\E/-) {
7264: next;
7265: }
7266: }
1.561 banghart 7267: if (ref($value) eq "ARRAY"){
7268: foreach my $stored_what (@{$value}) {
1.629 banghart 7269: my $cmp2=$stored_what;
1.759 albertel 7270: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7271: $cmp2=join('',@{$stored_what});
1.745 raeburn 7272: }
1.629 banghart 7273: if ($cmp1 eq $cmp2) {
1.561 banghart 7274: push(@readonly_files, $file_name);
1.745 raeburn 7275: last;
1.563 banghart 7276: } elsif (!defined($what)) {
7277: push(@readonly_files, $file_name);
1.745 raeburn 7278: last;
1.561 banghart 7279: }
7280: }
1.745 raeburn 7281: }
1.561 banghart 7282: }
7283: return @readonly_files;
7284: }
1.577 banghart 7285: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7286:
1.577 banghart 7287: sub get_marked_as_readonly_hash {
1.745 raeburn 7288: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7289: my %readonly_files;
1.745 raeburn 7290: while (my ($file_name,$value) = each(%{$current_permissions})) {
7291: if (defined($group)) {
7292: if ($file_name !~ m-^\Q$group\E/-) {
7293: next;
7294: }
7295: }
1.577 banghart 7296: if (ref($value) eq "ARRAY"){
7297: foreach my $stored_what (@{$value}) {
1.745 raeburn 7298: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7299: foreach my $lock_descriptor(@{$stored_what}) {
7300: if ($lock_descriptor eq 'graded') {
7301: $readonly_files{$file_name} = 'graded';
7302: } elsif ($lock_descriptor eq 'handback') {
7303: $readonly_files{$file_name} = 'handback';
7304: } else {
7305: if (!exists($readonly_files{$file_name})) {
7306: $readonly_files{$file_name} = 'locked';
7307: }
7308: }
1.745 raeburn 7309: }
1.750 banghart 7310: }
1.577 banghart 7311: }
7312: }
7313: }
7314: return %readonly_files;
7315: }
1.559 banghart 7316: # ------------------------------------------------------------ Unmark as Read Only
7317:
7318: sub unmark_as_readonly {
1.629 banghart 7319: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7320: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7321: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7322: $file_name = &declutter_portfile($file_name);
1.634 albertel 7323: my $symb_crs = $what;
7324: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7325: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7326: my ($tmp)=keys(%current_permissions);
7327: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7328: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7329: foreach my $file (@readonly_files) {
1.759 albertel 7330: my $clean_file = &declutter_portfile($file);
7331: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7332: my $current_locks = $current_permissions{$file};
1.563 banghart 7333: my @new_locks;
7334: my @del_keys;
7335: if (ref($current_locks) eq "ARRAY"){
7336: foreach my $locker (@{$current_locks}) {
1.632 albertel 7337: my $compare=$locker;
1.749 raeburn 7338: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7339: $compare=join('',@{$locker});
1.746 raeburn 7340: if ($compare ne $symb_crs) {
7341: push(@new_locks, $locker);
7342: }
1.563 banghart 7343: }
7344: }
1.650 albertel 7345: if (scalar(@new_locks) > 0) {
1.563 banghart 7346: $current_permissions{$file} = \@new_locks;
7347: } else {
7348: push(@del_keys, $file);
1.613 albertel 7349: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7350: delete($current_permissions{$file});
1.563 banghart 7351: }
7352: }
1.561 banghart 7353: }
1.613 albertel 7354: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7355: return;
7356: }
1.512 banghart 7357:
1.17 www 7358: # ------------------------------------------------------------ Directory lister
7359:
7360: sub dirlist {
1.955 raeburn 7361: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7362: $uri=~s/^\///;
7363: $uri=~s/\/$//;
1.253 stredwic 7364: my ($udom, $uname);
1.955 raeburn 7365: if ($getuserdir) {
1.253 stredwic 7366: $udom = $userdomain;
7367: $uname = $username;
1.955 raeburn 7368: } else {
7369: (undef,$udom,$uname)=split(/\//,$uri);
7370: if(defined($userdomain)) {
7371: $udom = $userdomain;
7372: }
7373: if(defined($username)) {
7374: $uname = $username;
7375: }
1.253 stredwic 7376: }
1.955 raeburn 7377: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7378:
1.955 raeburn 7379: $dirRoot = $perlvar{'lonDocRoot'};
7380: if (defined($getpropath)) {
7381: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7382: $dirRoot =~ s/\/$//;
1.955 raeburn 7383: } elsif (defined($getuserdir)) {
7384: my $subdir=$uname.'__';
7385: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7386: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7387: ."/$udom/$subdir/$uname";
7388: } elsif (defined($alternateRoot)) {
7389: $dirRoot = $alternateRoot;
1.751 banghart 7390: }
1.253 stredwic 7391:
7392: if($udom) {
7393: if($uname) {
1.955 raeburn 7394: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7395: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7396: .':'.&escape($uname).':'.&escape($udom),
7397: &homeserver($uname,$udom));
7398: if ($listing eq 'unknown_cmd') {
7399: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7400: &homeserver($uname,$udom));
7401: } else {
7402: @listing_results = map { &unescape($_); } split(/:/,$listing);
7403: }
1.605 matthew 7404: if ($listing eq 'unknown_cmd') {
1.800 albertel 7405: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7406: &homeserver($uname,$udom));
1.605 matthew 7407: @listing_results = split(/:/,$listing);
7408: } else {
7409: @listing_results = map { &unescape($_); } split(/:/,$listing);
7410: }
7411: return @listing_results;
1.955 raeburn 7412: } elsif(!$alternateRoot) {
1.800 albertel 7413: my %allusers;
1.841 albertel 7414: my %servers = &get_servers($udom,'library');
1.955 raeburn 7415: foreach my $tryserver (keys(%servers)) {
7416: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7417: &escape($udom),$tryserver);
7418: if ($listing eq 'unknown_cmd') {
7419: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7420: $udom, $tryserver);
7421: } else {
7422: @listing_results = map { &unescape($_); } split(/:/,$listing);
7423: }
1.841 albertel 7424: if ($listing eq 'unknown_cmd') {
7425: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7426: $udom, $tryserver);
7427: @listing_results = split(/:/,$listing);
7428: } else {
7429: @listing_results =
7430: map { &unescape($_); } split(/:/,$listing);
7431: }
7432: if ($listing_results[0] ne 'no_such_dir' &&
7433: $listing_results[0] ne 'empty' &&
7434: $listing_results[0] ne 'con_lost') {
7435: foreach my $line (@listing_results) {
7436: my ($entry) = split(/&/,$line,2);
7437: $allusers{$entry} = 1;
7438: }
7439: }
1.253 stredwic 7440: }
7441: my $alluserstr='';
1.800 albertel 7442: foreach my $user (sort(keys(%allusers))) {
7443: $alluserstr.=$user.'&user:';
1.253 stredwic 7444: }
7445: $alluserstr=~s/:$//;
7446: return split(/:/,$alluserstr);
7447: } else {
1.800 albertel 7448: return ('missing user name');
1.253 stredwic 7449: }
1.955 raeburn 7450: } elsif(!defined($getpropath)) {
1.841 albertel 7451: my @all_domains = sort(&all_domains());
1.955 raeburn 7452: foreach my $domain (@all_domains) {
7453: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7454: }
7455: return @all_domains;
7456: } else {
1.800 albertel 7457: return ('missing domain');
1.275 stredwic 7458: }
7459: }
7460:
7461: # --------------------------------------------- GetFileTimestamp
7462: # This function utilizes dirlist and returns the date stamp for
7463: # when it was last modified. It will also return an error of -1
7464: # if an error occurs
7465:
7466: sub GetFileTimestamp {
1.955 raeburn 7467: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7468: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7469: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7470: my ($fileStat) =
7471: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7472: undef,$getuserdir);
1.275 stredwic 7473: my @stats = split('&', $fileStat);
7474: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7475: # @stats contains first the filename, then the stat output
7476: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7477: } else {
7478: return -1;
1.253 stredwic 7479: }
1.26 www 7480: }
7481:
1.712 albertel 7482: sub stat_file {
7483: my ($uri) = @_;
1.787 albertel 7484: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7485:
1.955 raeburn 7486: my ($udom,$uname,$file);
1.712 albertel 7487: if ($uri =~ m-^/(uploaded|editupload)/-) {
7488: ($udom,$uname,$file) =
1.811 albertel 7489: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7490: $file = 'userfiles/'.$file;
7491: }
7492: if ($uri =~ m-^/res/-) {
7493: ($udom,$uname) =
1.807 albertel 7494: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7495: $file = $uri;
7496: }
7497:
7498: if (!$udom || !$uname || !$file) {
7499: # unable to handle the uri
7500: return ();
7501: }
1.956 raeburn 7502: my $getpropath;
7503: if ($file =~ /^userfiles\//) {
7504: $getpropath = 1;
7505: }
1.955 raeburn 7506: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7507: my @stats = split('&', $result);
1.721 banghart 7508:
1.712 albertel 7509: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7510: shift(@stats); #filename is first
7511: return @stats;
7512: }
7513: return ();
7514: }
7515:
1.26 www 7516: # -------------------------------------------------------- Value of a Condition
7517:
1.713 albertel 7518: # gets the value of a specific preevaluated condition
7519: # stored in the string $env{user.state.<cid>}
7520: # or looks up a condition reference in the bighash and if if hasn't
7521: # already been evaluated recurses into docondval to get the value of
7522: # the condition, then memoizing it to
7523: # $env{user.state.<cid>.<condition>}
1.40 www 7524: sub directcondval {
7525: my $number=shift;
1.620 albertel 7526: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7527: &Apache::lonuserstate::evalstate();
7528: }
1.713 albertel 7529: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7530: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7531: } elsif ($number =~ /^_/) {
7532: my $sub_condition;
7533: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7534: &GDBM_READER(),0640)) {
7535: $sub_condition=$bighash{'conditions'.$number};
7536: untie(%bighash);
7537: }
7538: my $value = &docondval($sub_condition);
1.949 raeburn 7539: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7540: return $value;
7541: }
1.620 albertel 7542: if ($env{'user.state.'.$env{'request.course.id'}}) {
7543: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7544: } else {
7545: return 2;
7546: }
7547: }
7548:
1.713 albertel 7549: # get the collection of conditions for this resource
1.26 www 7550: sub condval {
7551: my $condidx=shift;
1.54 www 7552: my $allpathcond='';
1.713 albertel 7553: foreach my $cond (split(/\|/,$condidx)) {
7554: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7555: $allpathcond.=
7556: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7557: }
1.191 harris41 7558: }
1.54 www 7559: $allpathcond=~s/\|$//;
1.713 albertel 7560: return &docondval($allpathcond);
7561: }
7562:
7563: #evaluates an expression of conditions
7564: sub docondval {
7565: my ($allpathcond) = @_;
7566: my $result=0;
7567: if ($env{'request.course.id'}
7568: && defined($allpathcond)) {
7569: my $operand='|';
7570: my @stack;
7571: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7572: if ($chunk eq '(') {
7573: push @stack,($operand,$result);
7574: } elsif ($chunk eq ')') {
7575: my $before=pop @stack;
7576: if (pop @stack eq '&') {
7577: $result=$result>$before?$before:$result;
7578: } else {
7579: $result=$result>$before?$result:$before;
7580: }
7581: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7582: $operand=$chunk;
7583: } else {
7584: my $new=directcondval($chunk);
7585: if ($operand eq '&') {
7586: $result=$result>$new?$new:$result;
7587: } else {
7588: $result=$result>$new?$result:$new;
7589: }
7590: }
7591: }
1.26 www 7592: }
7593: return $result;
1.421 albertel 7594: }
7595:
7596: # ---------------------------------------------------- Devalidate courseresdata
7597:
7598: sub devalidatecourseresdata {
7599: my ($coursenum,$coursedomain)=@_;
7600: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7601: &devalidate_cache_new('courseres',$hashid);
1.28 www 7602: }
7603:
1.763 www 7604:
1.200 www 7605: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7606: #
7607: # Parameters:
7608: # $coursenum - Number of the course.
7609: # $coursedomain - Domain at which the course was created.
7610: # Returns:
7611: # A hash of the course parameters along (I think) with timestamps
7612: # and version info.
1.877 foxr 7613:
1.624 albertel 7614: sub get_courseresdata {
7615: my ($coursenum,$coursedomain)=@_;
1.200 www 7616: my $coursehom=&homeserver($coursenum,$coursedomain);
7617: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7618: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7619: my %dumpreply;
1.417 albertel 7620: unless (defined($cached)) {
1.624 albertel 7621: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7622: $result=\%dumpreply;
1.251 albertel 7623: my ($tmp) = keys(%dumpreply);
7624: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7625: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7626: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7627: return $tmp;
1.416 albertel 7628: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7629: $result=undef;
1.599 albertel 7630: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7631: }
7632: }
1.624 albertel 7633: return $result;
7634: }
7635:
1.633 albertel 7636: sub devalidateuserresdata {
7637: my ($uname,$udom)=@_;
7638: my $hashid="$udom:$uname";
7639: &devalidate_cache_new('userres',$hashid);
7640: }
7641:
1.624 albertel 7642: sub get_userresdata {
7643: my ($uname,$udom)=@_;
7644: #most student don\'t have any data set, check if there is some data
7645: if (&EXT_cache_status($udom,$uname)) { return undef; }
7646:
7647: my $hashid="$udom:$uname";
7648: my ($result,$cached)=&is_cached_new('userres',$hashid);
7649: if (!defined($cached)) {
7650: my %resourcedata=&dump('resourcedata',$udom,$uname);
7651: $result=\%resourcedata;
7652: &do_cache_new('userres',$hashid,$result,600);
7653: }
7654: my ($tmp)=keys(%$result);
7655: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7656: return $result;
7657: }
7658: #error 2 occurs when the .db doesn't exist
7659: if ($tmp!~/error: 2 /) {
1.672 albertel 7660: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7661: " Trying to get resource data for ".
7662: $uname." at ".$udom.": ".
7663: $tmp."</font>");
7664: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7665: #&EXT_cache_set($udom,$uname);
7666: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7667: undef($tmp); # not really an error so don't send it back
1.624 albertel 7668: }
7669: return $tmp;
7670: }
1.879 foxr 7671: #----------------------------------------------- resdata - return resource data
7672: # Purpose:
7673: # Return resource data for either users or for a course.
7674: # Parameters:
7675: # $name - Course/user name.
7676: # $domain - Name of the domain the user/course is registered on.
7677: # $type - Type of thing $name is (must be 'course' or 'user'
7678: # @which - Array of names of resources desired.
7679: # Returns:
7680: # The value of the first reasource in @which that is found in the
7681: # resource hash.
7682: # Exceptional Conditions:
7683: # If the $type passed in is not valid (not the string 'course' or
7684: # 'user', an undefined reference is returned.
7685: # If none of the resources are found, an undef is returned
1.624 albertel 7686: sub resdata {
7687: my ($name,$domain,$type,@which)=@_;
7688: my $result;
7689: if ($type eq 'course') {
7690: $result=&get_courseresdata($name,$domain);
7691: } elsif ($type eq 'user') {
7692: $result=&get_userresdata($name,$domain);
7693: }
7694: if (!ref($result)) { return $result; }
1.251 albertel 7695: foreach my $item (@which) {
1.927 albertel 7696: if (defined($result->{$item->[0]})) {
7697: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7698: }
1.250 albertel 7699: }
1.291 albertel 7700: return undef;
1.200 www 7701: }
7702:
1.379 matthew 7703: #
7704: # EXT resource caching routines
7705: #
7706:
7707: sub clear_EXT_cache_status {
1.383 albertel 7708: &delenv('cache.EXT.');
1.379 matthew 7709: }
7710:
7711: sub EXT_cache_status {
7712: my ($target_domain,$target_user) = @_;
1.383 albertel 7713: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7714: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7715: # We know already the user has no data
7716: return 1;
7717: } else {
7718: return 0;
7719: }
7720: }
7721:
7722: sub EXT_cache_set {
7723: my ($target_domain,$target_user) = @_;
1.383 albertel 7724: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7725: #&appenv({$cachename => time});
1.379 matthew 7726: }
7727:
1.28 www 7728: # --------------------------------------------------------- Value of a Variable
1.58 www 7729: sub EXT {
1.715 albertel 7730:
1.395 albertel 7731: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7732: unless ($varname) { return ''; }
1.218 albertel 7733: #get real user name/domain, courseid and symb
7734: my $courseid;
1.359 albertel 7735: my $publicuser;
1.427 www 7736: if ($symbparm) {
7737: $symbparm=&get_symb_from_alias($symbparm);
7738: }
1.218 albertel 7739: if (!($uname && $udom)) {
1.790 albertel 7740: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7741: if (!$symbparm) { $symbparm=$cursymb; }
7742: } else {
1.620 albertel 7743: $courseid=$env{'request.course.id'};
1.218 albertel 7744: }
1.48 www 7745: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7746: my $rest;
1.320 albertel 7747: if (defined($therest[0])) {
1.48 www 7748: $rest=join('.',@therest);
7749: } else {
7750: $rest='';
7751: }
1.320 albertel 7752:
1.57 www 7753: my $qualifierrest=$qualifier;
7754: if ($rest) { $qualifierrest.='.'.$rest; }
7755: my $spacequalifierrest=$space;
7756: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7757: if ($realm eq 'user') {
1.48 www 7758: # --------------------------------------------------------------- user.resource
7759: if ($space eq 'resource') {
1.651 albertel 7760: if ( (defined($Apache::lonhomework::parsing_a_problem)
7761: || defined($Apache::lonhomework::parsing_a_task))
7762: &&
1.744 albertel 7763: ($symbparm eq &symbread()) ) {
7764: # if we are in the middle of processing the resource the
7765: # get the value we are planning on committing
7766: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7767: return $Apache::lonhomework::results{$qualifierrest};
7768: } else {
7769: return $Apache::lonhomework::history{$qualifierrest};
7770: }
1.335 albertel 7771: } else {
1.359 albertel 7772: my %restored;
1.620 albertel 7773: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 7774: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7775: } else {
7776: %restored=&restore($symbparm,$courseid,$udom,$uname);
7777: }
1.335 albertel 7778: return $restored{$qualifierrest};
7779: }
1.48 www 7780: # ----------------------------------------------------------------- user.access
7781: } elsif ($space eq 'access') {
1.218 albertel 7782: # FIXME - not supporting calls for a specific user
1.48 www 7783: return &allowed($qualifier,$rest);
7784: # ------------------------------------------ user.preferences, user.environment
7785: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7786: if (($uname eq $env{'user.name'}) &&
7787: ($udom eq $env{'user.domain'})) {
7788: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7789: } else {
1.359 albertel 7790: my %returnhash;
7791: if (!$publicuser) {
7792: %returnhash=&userenvironment($udom,$uname,
7793: $qualifierrest);
7794: }
1.218 albertel 7795: return $returnhash{$qualifierrest};
7796: }
1.48 www 7797: # ----------------------------------------------------------------- user.course
7798: } elsif ($space eq 'course') {
1.218 albertel 7799: # FIXME - not supporting calls for a specific user
1.620 albertel 7800: return $env{join('.',('request.course',$qualifier))};
1.48 www 7801: # ------------------------------------------------------------------- user.role
7802: } elsif ($space eq 'role') {
1.218 albertel 7803: # FIXME - not supporting calls for a specific user
1.620 albertel 7804: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7805: if ($qualifier eq 'value') {
7806: return $role;
7807: } elsif ($qualifier eq 'extent') {
7808: return $where;
7809: }
7810: # ----------------------------------------------------------------- user.domain
7811: } elsif ($space eq 'domain') {
1.218 albertel 7812: return $udom;
1.48 www 7813: # ------------------------------------------------------------------- user.name
7814: } elsif ($space eq 'name') {
1.218 albertel 7815: return $uname;
1.48 www 7816: # ---------------------------------------------------- Any other user namespace
1.29 www 7817: } else {
1.359 albertel 7818: my %reply;
7819: if (!$publicuser) {
7820: %reply=&get($space,[$qualifierrest],$udom,$uname);
7821: }
7822: return $reply{$qualifierrest};
1.48 www 7823: }
1.236 www 7824: } elsif ($realm eq 'query') {
7825: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7826: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7827: [$spacequalifierrest]);
1.620 albertel 7828: return $env{'form.'.$spacequalifierrest};
1.236 www 7829: } elsif ($realm eq 'request') {
1.48 www 7830: # ------------------------------------------------------------- request.browser
7831: if ($space eq 'browser') {
1.430 www 7832: if ($qualifier eq 'textremote') {
1.676 albertel 7833: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7834: return 1;
7835: } else {
7836: return 0;
7837: }
7838: } else {
1.620 albertel 7839: return $env{'browser.'.$qualifier};
1.430 www 7840: }
1.57 www 7841: # ------------------------------------------------------------ request.filename
7842: } else {
1.620 albertel 7843: return $env{'request.'.$spacequalifierrest};
1.29 www 7844: }
1.28 www 7845: } elsif ($realm eq 'course') {
1.48 www 7846: # ---------------------------------------------------------- course.description
1.620 albertel 7847: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7848: } elsif ($realm eq 'resource') {
1.165 www 7849:
1.620 albertel 7850: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7851: if (!$symbparm) { $symbparm=&symbread(); }
7852: }
1.693 albertel 7853:
7854: if ($space eq 'title') {
7855: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7856: return &gettitle($symbparm);
7857: }
7858:
7859: if ($space eq 'map') {
7860: my ($map) = &decode_symb($symbparm);
7861: return &symbread($map);
7862: }
1.905 albertel 7863: if ($space eq 'filename') {
7864: if ($symbparm) {
7865: return &clutter((&decode_symb($symbparm))[2]);
7866: }
7867: return &hreflocation('',$env{'request.filename'});
7868: }
1.693 albertel 7869:
7870: my ($section, $group, @groups);
1.593 albertel 7871: my ($courselevelm,$courselevel);
1.539 albertel 7872: if ($symbparm && defined($courseid) &&
1.620 albertel 7873: $courseid eq $env{'request.course.id'}) {
1.165 www 7874:
1.218 albertel 7875: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7876:
1.60 www 7877: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7878: my $symbp=$symbparm;
1.735 albertel 7879: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7880:
7881: my $symbparm=$symbp.'.'.$spacequalifierrest;
7882: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7883:
1.620 albertel 7884: if (($env{'user.name'} eq $uname) &&
7885: ($env{'user.domain'} eq $udom)) {
7886: $section=$env{'request.course.sec'};
1.733 raeburn 7887: @groups = split(/:/,$env{'request.course.groups'});
7888: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7889: } else {
1.539 albertel 7890: if (! defined($usection)) {
1.551 albertel 7891: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7892: } else {
7893: $section = $usection;
7894: }
1.733 raeburn 7895: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7896: }
7897:
7898: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7899: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7900: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7901:
1.593 albertel 7902: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7903: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7904: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7905:
1.60 www 7906: # ----------------------------------------------------------- first, check user
1.624 albertel 7907:
7908: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7909: ([$courselevelr,'resource'],
7910: [$courselevelm,'map' ],
7911: [$courselevel, 'course' ]));
1.931 albertel 7912: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7913:
1.594 albertel 7914: # ------------------------------------------------ second, check some of course
1.684 raeburn 7915: my $coursereply;
1.691 raeburn 7916: if (@groups > 0) {
7917: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7918: $mapparm,$spacequalifierrest);
1.927 albertel 7919: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7920: }
1.96 www 7921:
1.684 raeburn 7922: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7923: $env{'course.'.$courseid.'.domain'},
7924: 'course',
7925: ([$seclevelr, 'resource'],
7926: [$seclevelm, 'map' ],
7927: [$seclevel, 'course' ],
7928: [$courselevelr,'resource']));
7929: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7930:
1.60 www 7931: # ------------------------------------------------------ third, check map parms
1.218 albertel 7932: my %parmhash=();
7933: my $thisparm='';
7934: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7935: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7936: &GDBM_READER(),0640)) {
1.218 albertel 7937: $thisparm=$parmhash{$symbparm};
7938: untie(%parmhash);
7939: }
1.927 albertel 7940: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7941: }
1.594 albertel 7942: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7943:
1.218 albertel 7944: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7945: my $filename;
7946: if (!$symbparm) { $symbparm=&symbread(); }
7947: if ($symbparm) {
1.409 www 7948: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7949: } else {
1.620 albertel 7950: $filename=$env{'request.filename'};
1.282 albertel 7951: }
7952: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7953: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7954: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7955: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7956:
1.927 albertel 7957: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7958: if ($symbparm && defined($courseid) &&
1.620 albertel 7959: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7960: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7961: $env{'course.'.$courseid.'.domain'},
7962: 'course',
1.927 albertel 7963: ([$courselevelm,'map' ],
7964: [$courselevel, 'course']));
7965: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7966: }
1.145 www 7967: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7968: unless ($space eq '0') {
1.336 albertel 7969: my @parts=split(/_/,$space);
7970: my $id=pop(@parts);
7971: my $part=join('_',@parts);
7972: if ($part eq '') { $part='0'; }
1.927 albertel 7973: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7974: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7975: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7976: }
1.395 albertel 7977: if ($recurse) { return undef; }
7978: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 7979: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 7980: # ---------------------------------------------------- Any other user namespace
7981: } elsif ($realm eq 'environment') {
7982: # ----------------------------------------------------------------- environment
1.620 albertel 7983: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7984: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 7985: } else {
1.770 albertel 7986: if ($uname eq 'anonymous' && $udom eq '') {
7987: return '';
7988: }
1.219 albertel 7989: my %returnhash=&userenvironment($udom,$uname,
7990: $spacequalifierrest);
7991: return $returnhash{$spacequalifierrest};
7992: }
1.28 www 7993: } elsif ($realm eq 'system') {
1.48 www 7994: # ----------------------------------------------------------------- system.time
7995: if ($space eq 'time') {
7996: return time;
7997: }
1.696 albertel 7998: } elsif ($realm eq 'server') {
7999: # ----------------------------------------------------------------- system.time
8000: if ($space eq 'name') {
8001: return $ENV{'SERVER_NAME'};
8002: }
1.28 www 8003: }
1.48 www 8004: return '';
1.61 www 8005: }
8006:
1.927 albertel 8007: sub get_reply {
8008: my ($reply_value) = @_;
1.940 raeburn 8009: if (ref($reply_value) eq 'ARRAY') {
8010: if (wantarray) {
8011: return @$reply_value;
8012: }
8013: return $reply_value->[0];
8014: } else {
8015: return $reply_value;
1.927 albertel 8016: }
8017: }
8018:
1.691 raeburn 8019: sub check_group_parms {
8020: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8021: my @groupitems = ();
8022: my $resultitem;
1.927 albertel 8023: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8024: foreach my $group (@{$groups}) {
8025: foreach my $level (@levels) {
1.927 albertel 8026: my $item = $courseid.'.['.$group.'].'.$level->[0];
8027: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8028: }
8029: }
8030: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8031: $env{'course.'.$courseid.'.domain'},
8032: 'course',@groupitems);
8033: return $coursereply;
8034: }
8035:
8036: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8037: my ($courseid,@groups) = @_;
8038: @groups = sort(@groups);
1.691 raeburn 8039: return @groups;
8040: }
8041:
1.395 albertel 8042: sub packages_tab_default {
8043: my ($uri,$varname)=@_;
8044: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8045:
8046: my (@extension,@specifics,$do_default);
8047: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8048: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8049: if ($pack_type eq 'default') {
8050: $do_default=1;
8051: } elsif ($pack_type eq 'extension') {
8052: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8053: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8054: # only look at packages defaults for packages that this id is
1.738 albertel 8055: push(@specifics,[$package,$pack_type,$pack_part]);
8056: }
8057: }
8058: # first look for a package that matches the requested part id
8059: foreach my $package (@specifics) {
8060: my (undef,$pack_type,$pack_part)=@{$package};
8061: next if ($pack_part ne $part);
8062: if (defined($packagetab{"$pack_type&$name&default"})) {
8063: return $packagetab{"$pack_type&$name&default"};
8064: }
8065: }
8066: # look for any possible matching non extension_ package
8067: foreach my $package (@specifics) {
8068: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8069: if (defined($packagetab{"$pack_type&$name&default"})) {
8070: return $packagetab{"$pack_type&$name&default"};
8071: }
1.585 albertel 8072: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8073: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8074: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8075: }
8076: }
1.738 albertel 8077: # look for any posible extension_ match
8078: foreach my $package (@extension) {
8079: my ($package,$pack_type)=@{$package};
8080: if (defined($packagetab{"$pack_type&$name&default"})) {
8081: return $packagetab{"$pack_type&$name&default"};
8082: }
8083: if (defined($packagetab{$package."&$name&default"})) {
8084: return $packagetab{$package."&$name&default"};
8085: }
8086: }
8087: # look for a global default setting
8088: if ($do_default && defined($packagetab{"default&$name&default"})) {
8089: return $packagetab{"default&$name&default"};
8090: }
1.395 albertel 8091: return undef;
8092: }
8093:
1.334 albertel 8094: sub add_prefix_and_part {
8095: my ($prefix,$part)=@_;
8096: my $keyroot;
8097: if (defined($prefix) && $prefix !~ /^__/) {
8098: # prefix that has a part already
8099: $keyroot=$prefix;
8100: } elsif (defined($prefix)) {
8101: # prefix that is missing a part
8102: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8103: } else {
8104: # no prefix at all
8105: if (defined($part)) { $keyroot='_'.$part; }
8106: }
8107: return $keyroot;
8108: }
8109:
1.71 www 8110: # ---------------------------------------------------------------- Get metadata
8111:
1.599 albertel 8112: my %metaentry;
1.71 www 8113: sub metadata {
1.176 www 8114: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8115: $uri=&declutter($uri);
1.288 albertel 8116: # if it is a non metadata possible uri return quickly
1.529 albertel 8117: if (($uri eq '') ||
8118: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8119: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8120: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8121: return undef;
8122: }
8123: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8124: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8125: return undef;
1.288 albertel 8126: }
1.73 www 8127: my $filename=$uri;
8128: $uri=~s/\.meta$//;
1.172 www 8129: #
8130: # Is the metadata already cached?
1.177 www 8131: # Look at timestamp of caching
1.172 www 8132: # Everything is cached by the main uri, libraries are never directly cached
8133: #
1.428 albertel 8134: if (!defined($liburi)) {
1.599 albertel 8135: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8136: if (defined($cached)) { return $result->{':'.$what}; }
8137: }
8138: {
1.172 www 8139: #
8140: # Is this a recursive call for a library?
8141: #
1.599 albertel 8142: # if (! exists($metacache{$uri})) {
8143: # $metacache{$uri}={};
8144: # }
1.924 albertel 8145: my $cachetime = 60*60;
1.171 www 8146: if ($liburi) {
8147: $liburi=&declutter($liburi);
8148: $filename=$liburi;
1.401 bowersj2 8149: } else {
1.599 albertel 8150: &devalidate_cache_new('meta',$uri);
8151: undef(%metaentry);
1.401 bowersj2 8152: }
1.140 www 8153: my %metathesekeys=();
1.73 www 8154: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8155: my $metastring;
1.924 albertel 8156: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8157: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8158: $metastring =
1.929 albertel 8159: &Apache::lonnet::ssi_body($which,
1.924 albertel 8160: ('grade_target' => 'meta'));
8161: $cachetime = 1; # only want this cached in the child not long term
8162: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8163: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8164: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8165: $metastring=&getfile($file);
1.489 albertel 8166: }
1.208 albertel 8167: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8168: my $token;
1.140 www 8169: undef %metathesekeys;
1.71 www 8170: while ($token=$parser->get_token) {
1.339 albertel 8171: if ($token->[0] eq 'S') {
8172: if (defined($token->[2]->{'package'})) {
1.172 www 8173: #
8174: # This is a package - get package info
8175: #
1.339 albertel 8176: my $package=$token->[2]->{'package'};
8177: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8178: if (defined($token->[2]->{'id'})) {
8179: $keyroot.='_'.$token->[2]->{'id'};
8180: }
1.599 albertel 8181: if ($metaentry{':packages'}) {
8182: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8183: } else {
1.599 albertel 8184: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8185: }
1.736 albertel 8186: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8187: my $part=$keyroot;
8188: $part=~s/^\_//;
1.736 albertel 8189: if ($pack_entry=~/^\Q$package\E\&/ ||
8190: $pack_entry=~/^\Q$package\E_0\&/) {
8191: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8192: # ignore package.tab specified default values
8193: # here &package_tab_default() will fetch those
8194: if ($subp eq 'default') { next; }
1.736 albertel 8195: my $value=$packagetab{$pack_entry};
1.432 albertel 8196: my $unikey;
8197: if ($pack =~ /_0$/) {
8198: $unikey='parameter_0_'.$name;
8199: $part=0;
8200: } else {
8201: $unikey='parameter'.$keyroot.'_'.$name;
8202: }
1.339 albertel 8203: if ($subp eq 'display') {
8204: $value.=' [Part: '.$part.']';
8205: }
1.599 albertel 8206: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8207: $metathesekeys{$unikey}=1;
1.599 albertel 8208: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8209: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8210: }
1.599 albertel 8211: if (defined($metaentry{':'.$unikey.'.default'})) {
8212: $metaentry{':'.$unikey}=
8213: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8214: }
1.339 albertel 8215: }
8216: }
8217: } else {
1.172 www 8218: #
8219: # This is not a package - some other kind of start tag
1.339 albertel 8220: #
8221: my $entry=$token->[1];
8222: my $unikey;
8223: if ($entry eq 'import') {
8224: $unikey='';
8225: } else {
8226: $unikey=$entry;
8227: }
8228: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8229:
8230: if (defined($token->[2]->{'id'})) {
8231: $unikey.='_'.$token->[2]->{'id'};
8232: }
1.175 www 8233:
1.339 albertel 8234: if ($entry eq 'import') {
1.175 www 8235: #
8236: # Importing a library here
1.339 albertel 8237: #
8238: if ($depthcount<20) {
8239: my $location=$parser->get_text('/import');
8240: my $dir=$filename;
8241: $dir=~s|[^/]*$||;
8242: $location=&filelocation($dir,$location);
1.736 albertel 8243: my $metadata =
8244: &metadata($uri,'keys', $location,$unikey,
8245: $depthcount+1);
8246: foreach my $meta (split(',',$metadata)) {
8247: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8248: $metathesekeys{$meta}=1;
1.339 albertel 8249: }
8250: }
8251: } else {
8252:
8253: if (defined($token->[2]->{'name'})) {
8254: $unikey.='_'.$token->[2]->{'name'};
8255: }
8256: $metathesekeys{$unikey}=1;
1.736 albertel 8257: foreach my $param (@{$token->[3]}) {
8258: $metaentry{':'.$unikey.'.'.$param} =
8259: $token->[2]->{$param};
1.339 albertel 8260: }
8261: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8262: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8263: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8264: # only ws inside the tag, and not in default, so use default
8265: # as value
1.599 albertel 8266: $metaentry{':'.$unikey}=$default;
1.908 albertel 8267: } elsif ( $internaltext =~ /\S/ ) {
8268: # something interesting inside the tag
8269: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8270: } else {
1.908 albertel 8271: # no interesting values, don't set a default
1.339 albertel 8272: }
1.172 www 8273: # end of not-a-package not-a-library import
1.339 albertel 8274: }
1.172 www 8275: # end of not-a-package start tag
1.339 albertel 8276: }
1.172 www 8277: # the next is the end of "start tag"
1.339 albertel 8278: }
8279: }
1.483 albertel 8280: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8281: $extension = lc($extension);
8282: if ($extension eq 'htm') { $extension='html'; }
8283:
1.737 albertel 8284: foreach my $key (keys(%packagetab)) {
1.483 albertel 8285: #no specific packages #how's our extension
8286: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8287: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8288: \%metathesekeys);
8289: }
1.883 albertel 8290:
8291: if (!exists($metaentry{':packages'})
8292: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8293: foreach my $key (keys(%packagetab)) {
1.483 albertel 8294: #no specific packages well let's get default then
8295: if ($key!~/^default&/) { next; }
1.488 albertel 8296: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8297: \%metathesekeys);
8298: }
8299: }
1.338 www 8300: # are there custom rights to evaluate
1.599 albertel 8301: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8302:
1.338 www 8303: #
8304: # Importing a rights file here
1.339 albertel 8305: #
8306: unless ($depthcount) {
1.599 albertel 8307: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8308: my $dir=$filename;
8309: $dir=~s|[^/]*$||;
8310: $location=&filelocation($dir,$location);
1.736 albertel 8311: my $rights_metadata =
8312: &metadata($uri,'keys',$location,'_rights',
8313: $depthcount+1);
8314: foreach my $rights (split(',',$rights_metadata)) {
8315: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8316: $metathesekeys{$rights}=1;
1.339 albertel 8317: }
8318: }
8319: }
1.737 albertel 8320: # uniqifiy package listing
8321: my %seen;
8322: my @uniq_packages =
8323: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8324: $metaentry{':packages'} = join(',',@uniq_packages);
8325:
8326: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8327: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8328: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8329: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8330: # this is the end of "was not already recently cached
1.71 www 8331: }
1.599 albertel 8332: return $metaentry{':'.$what};
1.261 albertel 8333: }
8334:
1.488 albertel 8335: sub metadata_create_package_def {
1.483 albertel 8336: my ($uri,$key,$package,$metathesekeys)=@_;
8337: my ($pack,$name,$subp)=split(/\&/,$key);
8338: if ($subp eq 'default') { next; }
8339:
1.599 albertel 8340: if (defined($metaentry{':packages'})) {
8341: $metaentry{':packages'}.=','.$package;
1.483 albertel 8342: } else {
1.599 albertel 8343: $metaentry{':packages'}=$package;
1.483 albertel 8344: }
8345: my $value=$packagetab{$key};
8346: my $unikey;
8347: $unikey='parameter_0_'.$name;
1.599 albertel 8348: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8349: $$metathesekeys{$unikey}=1;
1.599 albertel 8350: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8351: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8352: }
1.599 albertel 8353: if (defined($metaentry{':'.$unikey.'.default'})) {
8354: $metaentry{':'.$unikey}=
8355: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8356: }
8357: }
8358:
1.261 albertel 8359: sub metadata_generate_part0 {
8360: my ($metadata,$metacache,$uri) = @_;
8361: my %allnames;
1.737 albertel 8362: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8363: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8364: my $part=$$metacache{':'.$metakey.'.part'};
8365: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8366: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8367: $allnames{$name}=$part;
8368: }
8369: }
8370: }
8371: foreach my $name (keys(%allnames)) {
8372: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8373: my $key=":parameter_0_$name";
1.261 albertel 8374: $$metacache{"$key.part"}='0';
8375: $$metacache{"$key.name"}=$name;
1.428 albertel 8376: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8377: $allnames{$name}.'_'.$name.
8378: '.type'};
1.428 albertel 8379: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8380: '.display'};
1.644 www 8381: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8382: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8383: $$metacache{"$key.display"}=$olddis;
8384: }
1.71 www 8385: }
8386:
1.764 albertel 8387: # ------------------------------------------------------ Devalidate title cache
8388:
8389: sub devalidate_title_cache {
8390: my ($url)=@_;
8391: if (!$env{'request.course.id'}) { return; }
8392: my $symb=&symbread($url);
8393: if (!$symb) { return; }
8394: my $key=$env{'request.course.id'}."\0".$symb;
8395: &devalidate_cache_new('title',$key);
8396: }
8397:
1.1014 droeschl 8398: # ------------------------------------------------- Get the title of a course
8399:
8400: sub current_course_title {
8401: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8402: }
1.301 www 8403: # ------------------------------------------------- Get the title of a resource
8404:
8405: sub gettitle {
8406: my $urlsymb=shift;
8407: my $symb=&symbread($urlsymb);
1.534 albertel 8408: if ($symb) {
1.620 albertel 8409: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8410: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8411: if (defined($cached)) {
8412: return $result;
8413: }
1.534 albertel 8414: my ($map,$resid,$url)=&decode_symb($symb);
8415: my $title='';
1.907 albertel 8416: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8417: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8418: } else {
8419: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8420: &GDBM_READER(),0640)) {
8421: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8422: $title=$bighash{'title_'.$mapid.'.'.$resid};
8423: untie(%bighash);
8424: }
1.534 albertel 8425: }
8426: $title=~s/\&colon\;/\:/gs;
8427: if ($title) {
1.599 albertel 8428: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8429: }
8430: $urlsymb=$url;
8431: }
8432: my $title=&metadata($urlsymb,'title');
8433: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8434: return $title;
1.301 www 8435: }
1.613 albertel 8436:
1.614 albertel 8437: sub get_slot {
8438: my ($which,$cnum,$cdom)=@_;
8439: if (!$cnum || !$cdom) {
1.790 albertel 8440: (undef,my $courseid)=&whichuser();
1.620 albertel 8441: $cdom=$env{'course.'.$courseid.'.domain'};
8442: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8443: }
1.703 albertel 8444: my $key=join("\0",'slots',$cdom,$cnum,$which);
8445: my %slotinfo;
8446: if (exists($remembered{$key})) {
8447: $slotinfo{$which} = $remembered{$key};
8448: } else {
8449: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8450: &Apache::lonhomework::showhash(%slotinfo);
8451: my ($tmp)=keys(%slotinfo);
8452: if ($tmp=~/^error:/) { return (); }
8453: $remembered{$key} = $slotinfo{$which};
8454: }
1.616 albertel 8455: if (ref($slotinfo{$which}) eq 'HASH') {
8456: return %{$slotinfo{$which}};
8457: }
8458: return $slotinfo{$which};
1.614 albertel 8459: }
1.31 www 8460: # ------------------------------------------------- Update symbolic store links
8461:
8462: sub symblist {
8463: my ($mapname,%newhash)=@_;
1.438 www 8464: $mapname=&deversion(&declutter($mapname));
1.31 www 8465: my %hash;
1.620 albertel 8466: if (($env{'request.course.fn'}) && (%newhash)) {
8467: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8468: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8469: foreach my $url (keys(%newhash)) {
1.711 albertel 8470: next if ($url eq 'last_known'
8471: && $env{'form.no_update_last_known'});
8472: $hash{declutter($url)}=&encode_symb($mapname,
8473: $newhash{$url}->[1],
8474: $newhash{$url}->[0]);
1.191 harris41 8475: }
1.31 www 8476: if (untie(%hash)) {
8477: return 'ok';
8478: }
8479: }
8480: }
8481: return 'error';
1.212 www 8482: }
8483:
8484: # --------------------------------------------------------------- Verify a symb
8485:
8486: sub symbverify {
1.510 www 8487: my ($symb,$thisurl)=@_;
8488: my $thisfn=$thisurl;
1.439 www 8489: $thisfn=&declutter($thisfn);
1.215 www 8490: # direct jump to resource in page or to a sequence - will construct own symbs
8491: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8492: # check URL part
1.409 www 8493: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8494:
1.431 www 8495: unless ($url eq $thisfn) { return 0; }
1.213 www 8496:
1.216 www 8497: $symb=&symbclean($symb);
1.510 www 8498: $thisurl=&deversion($thisurl);
1.439 www 8499: $thisfn=&deversion($thisfn);
1.213 www 8500:
8501: my %bighash;
8502: my $okay=0;
1.431 www 8503:
1.620 albertel 8504: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8505: &GDBM_READER(),0640)) {
1.1032 raeburn 8506: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8507: $thisurl =~ s/\?.+$//;
8508: }
1.510 www 8509: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8510: unless ($ids) {
1.510 www 8511: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8512: }
8513: if ($ids) {
8514: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8515: foreach my $id (split(/\,/,$ids)) {
8516: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8517: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8518: $symb =~ s/\?.+$//;
8519: }
1.216 www 8520: if (
8521: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8522: eq $symb) {
1.620 albertel 8523: if (($env{'request.role.adv'}) ||
1.800 albertel 8524: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8525: $okay=1;
8526: }
8527: }
1.216 www 8528: }
8529: }
1.213 www 8530: untie(%bighash);
8531: }
8532: return $okay;
1.31 www 8533: }
8534:
1.210 www 8535: # --------------------------------------------------------------- Clean-up symb
8536:
8537: sub symbclean {
8538: my $symb=shift;
1.568 albertel 8539: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8540: # remove version from map
8541: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8542:
1.210 www 8543: # remove version from URL
8544: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8545:
1.507 www 8546: # remove wrapper
8547:
1.510 www 8548: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8549: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8550: return $symb;
1.409 www 8551: }
8552:
8553: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8554:
8555: sub encode_symb {
8556: my ($map,$resid,$url)=@_;
8557: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8558: }
1.409 www 8559:
8560: sub decode_symb {
1.568 albertel 8561: my $symb=shift;
8562: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8563: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8564: return (&fixversion($map),$resid,&fixversion($url));
8565: }
8566:
8567: sub fixversion {
8568: my $fn=shift;
1.609 banghart 8569: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8570: my %bighash;
8571: my $uri=&clutter($fn);
1.620 albertel 8572: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8573: # is this cached?
1.599 albertel 8574: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8575: if (defined($cached)) { return $result; }
8576: # unfortunately not cached, or expired
1.620 albertel 8577: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8578: &GDBM_READER(),0640)) {
8579: if ($bighash{'version_'.$uri}) {
8580: my $version=$bighash{'version_'.$uri};
1.444 www 8581: unless (($version eq 'mostrecent') ||
8582: ($version==&getversion($uri))) {
1.440 www 8583: $uri=~s/\.(\w+)$/\.$version\.$1/;
8584: }
8585: }
8586: untie %bighash;
1.413 www 8587: }
1.599 albertel 8588: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8589: }
8590:
8591: sub deversion {
8592: my $url=shift;
8593: $url=~s/\.\d+\.(\w+)$/\.$1/;
8594: return $url;
1.210 www 8595: }
8596:
1.31 www 8597: # ------------------------------------------------------ Return symb list entry
8598:
8599: sub symbread {
1.249 www 8600: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8601: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8602: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8603: # no filename provided? try from environment
1.44 www 8604: unless ($thisfn) {
1.620 albertel 8605: if ($env{'request.symb'}) {
8606: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8607: }
1.620 albertel 8608: $thisfn=$env{'request.filename'};
1.44 www 8609: }
1.569 albertel 8610: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8611: # is that filename actually a symb? Verify, clean, and return
8612: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8613: if (&symbverify($thisfn,$1)) {
1.620 albertel 8614: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8615: }
1.242 www 8616: }
1.44 www 8617: $thisfn=declutter($thisfn);
1.31 www 8618: my %hash;
1.37 www 8619: my %bighash;
8620: my $syval='';
1.620 albertel 8621: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8622: my $targetfn = $thisfn;
1.609 banghart 8623: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8624: $targetfn = 'adm/wrapper/'.$thisfn;
8625: }
1.687 albertel 8626: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8627: $targetfn=$1;
8628: }
1.620 albertel 8629: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8630: &GDBM_READER(),0640)) {
1.481 raeburn 8631: $syval=$hash{$targetfn};
1.37 www 8632: untie(%hash);
8633: }
8634: # ---------------------------------------------------------- There was an entry
8635: if ($syval) {
1.601 albertel 8636: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8637: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8638: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8639: #return $env{$cache_str}='';
1.601 albertel 8640: #}
8641: #$syval.=$1;
8642: #}
1.37 www 8643: } else {
8644: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8645: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8646: &GDBM_READER(),0640)) {
1.37 www 8647: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8648: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8649: unless ($ids) {
8650: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8651: }
8652: unless ($ids) {
8653: # alias?
8654: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8655: }
1.37 www 8656: if ($ids) {
8657: # ------------------------------------------------------------------- Has ID(s)
8658: my @possibilities=split(/\,/,$ids);
1.39 www 8659: if ($#possibilities==0) {
8660: # ----------------------------------------------- There is only one possibility
1.37 www 8661: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8662: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8663: $resid,$thisfn);
1.249 www 8664: } elsif (!$donotrecurse) {
1.39 www 8665: # ------------------------------------------ There is more than one possibility
8666: my $realpossible=0;
1.800 albertel 8667: foreach my $id (@possibilities) {
8668: my $file=$bighash{'src_'.$id};
1.39 www 8669: if (&allowed('bre',$file)) {
1.800 albertel 8670: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8671: if ($bighash{'map_type_'.$mapid} ne 'page') {
8672: $realpossible++;
1.626 albertel 8673: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8674: $resid,$thisfn);
1.39 www 8675: }
8676: }
1.191 harris41 8677: }
1.39 www 8678: if ($realpossible!=1) { $syval=''; }
1.249 www 8679: } else {
8680: $syval='';
1.37 www 8681: }
8682: }
8683: untie(%bighash)
1.481 raeburn 8684: }
1.31 www 8685: }
1.62 www 8686: if ($syval) {
1.620 albertel 8687: return $env{$cache_str}=$syval;
1.62 www 8688: }
1.31 www 8689: }
1.949 raeburn 8690: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8691: return $env{$cache_str}='';
1.31 www 8692: }
8693:
8694: # ---------------------------------------------------------- Return random seed
8695:
1.32 www 8696: sub numval {
8697: my $txt=shift;
8698: $txt=~tr/A-J/0-9/;
8699: $txt=~tr/a-j/0-9/;
8700: $txt=~tr/K-T/0-9/;
8701: $txt=~tr/k-t/0-9/;
8702: $txt=~tr/U-Z/0-5/;
8703: $txt=~tr/u-z/0-5/;
8704: $txt=~s/\D//g;
1.564 albertel 8705: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8706: return int($txt);
1.368 albertel 8707: }
8708:
1.484 albertel 8709: sub numval2 {
8710: my $txt=shift;
8711: $txt=~tr/A-J/0-9/;
8712: $txt=~tr/a-j/0-9/;
8713: $txt=~tr/K-T/0-9/;
8714: $txt=~tr/k-t/0-9/;
8715: $txt=~tr/U-Z/0-5/;
8716: $txt=~tr/u-z/0-5/;
8717: $txt=~s/\D//g;
8718: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8719: my $total;
8720: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8721: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 8722: return int($total);
8723: }
8724:
1.575 albertel 8725: sub numval3 {
8726: use integer;
8727: my $txt=shift;
8728: $txt=~tr/A-J/0-9/;
8729: $txt=~tr/a-j/0-9/;
8730: $txt=~tr/K-T/0-9/;
8731: $txt=~tr/k-t/0-9/;
8732: $txt=~tr/U-Z/0-5/;
8733: $txt=~tr/u-z/0-5/;
8734: $txt=~s/\D//g;
8735: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8736: my $total;
8737: foreach my $val (@txts) { $total+=$val; }
8738: if ($_64bit) { $total=(($total<<32)>>32); }
8739: return $total;
8740: }
8741:
1.675 albertel 8742: sub digest {
8743: my ($data)=@_;
8744: my $digest=&Digest::MD5::md5($data);
8745: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8746: my ($e,$f);
8747: {
8748: use integer;
8749: $e=($a+$b);
8750: $f=($c+$d);
8751: if ($_64bit) {
8752: $e=(($e<<32)>>32);
8753: $f=(($f<<32)>>32);
8754: }
8755: }
8756: if (wantarray) {
8757: return ($e,$f);
8758: } else {
8759: my $g;
8760: {
8761: use integer;
8762: $g=($e+$f);
8763: if ($_64bit) {
8764: $g=(($g<<32)>>32);
8765: }
8766: }
8767: return $g;
8768: }
8769: }
8770:
1.368 albertel 8771: sub latest_rnd_algorithm_id {
1.675 albertel 8772: return '64bit5';
1.366 albertel 8773: }
1.32 www 8774:
1.503 albertel 8775: sub get_rand_alg {
8776: my ($courseid)=@_;
1.790 albertel 8777: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 8778: if ($courseid) {
1.620 albertel 8779: return $env{"course.$courseid.rndseed"};
1.503 albertel 8780: }
8781: return &latest_rnd_algorithm_id();
8782: }
8783:
1.562 albertel 8784: sub validCODE {
8785: my ($CODE)=@_;
8786: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8787: return 0;
8788: }
8789:
1.491 albertel 8790: sub getCODE {
1.620 albertel 8791: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 8792: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8793: defined($Apache::lonhomework::parsing_a_task) ) &&
8794: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 8795: return $Apache::lonhomework::history{'resource.CODE'};
8796: }
8797: return undef;
8798: }
8799:
1.31 www 8800: sub rndseed {
1.155 albertel 8801: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8802: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8803: if (!defined($symb)) {
1.366 albertel 8804: unless ($symb=$wsymb) { return time; }
8805: }
8806: if (!$courseid) { $courseid=$wcourseid; }
8807: if (!$domain) { $domain=$wdomain; }
8808: if (!$username) { $username=$wusername }
1.503 albertel 8809: my $which=&get_rand_alg();
1.803 albertel 8810:
1.491 albertel 8811: if (defined(&getCODE())) {
1.675 albertel 8812: if ($which eq '64bit5') {
8813: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8814: } elsif ($which eq '64bit4') {
1.575 albertel 8815: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8816: } else {
8817: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8818: }
1.675 albertel 8819: } elsif ($which eq '64bit5') {
8820: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8821: } elsif ($which eq '64bit4') {
8822: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8823: } elsif ($which eq '64bit3') {
8824: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8825: } elsif ($which eq '64bit2') {
8826: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8827: } elsif ($which eq '64bit') {
8828: return &rndseed_64bit($symb,$courseid,$domain,$username);
8829: }
8830: return &rndseed_32bit($symb,$courseid,$domain,$username);
8831: }
8832:
8833: sub rndseed_32bit {
8834: my ($symb,$courseid,$domain,$username)=@_;
8835: {
8836: use integer;
8837: my $symbchck=unpack("%32C*",$symb) << 27;
8838: my $symbseed=numval($symb) << 22;
8839: my $namechck=unpack("%32C*",$username) << 17;
8840: my $nameseed=numval($username) << 12;
8841: my $domainseed=unpack("%32C*",$domain) << 7;
8842: my $courseseed=unpack("%32C*",$courseid);
8843: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8844: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8845: #&logthis("rndseed :$num:$symb");
1.564 albertel 8846: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8847: return $num;
8848: }
8849: }
8850:
8851: sub rndseed_64bit {
8852: my ($symb,$courseid,$domain,$username)=@_;
8853: {
8854: use integer;
8855: my $symbchck=unpack("%32S*",$symb) << 21;
8856: my $symbseed=numval($symb) << 10;
8857: my $namechck=unpack("%32S*",$username);
8858:
8859: my $nameseed=numval($username) << 21;
8860: my $domainseed=unpack("%32S*",$domain) << 10;
8861: my $courseseed=unpack("%32S*",$courseid);
8862:
8863: my $num1=$symbchck+$symbseed+$namechck;
8864: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8865: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8866: #&logthis("rndseed :$num:$symb");
1.564 albertel 8867: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8868: return "$num1,$num2";
1.155 albertel 8869: }
1.366 albertel 8870: }
8871:
1.443 albertel 8872: sub rndseed_64bit2 {
8873: my ($symb,$courseid,$domain,$username)=@_;
8874: {
8875: use integer;
8876: # strings need to be an even # of cahracters long, it it is odd the
8877: # last characters gets thrown away
8878: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8879: my $symbseed=numval($symb) << 10;
8880: my $namechck=unpack("%32S*",$username.' ');
8881:
8882: my $nameseed=numval($username) << 21;
1.501 albertel 8883: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8884: my $courseseed=unpack("%32S*",$courseid.' ');
8885:
8886: my $num1=$symbchck+$symbseed+$namechck;
8887: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8888: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8889: #&logthis("rndseed :$num:$symb");
1.803 albertel 8890: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8891: return "$num1,$num2";
8892: }
8893: }
8894:
8895: sub rndseed_64bit3 {
8896: my ($symb,$courseid,$domain,$username)=@_;
8897: {
8898: use integer;
8899: # strings need to be an even # of cahracters long, it it is odd the
8900: # last characters gets thrown away
8901: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8902: my $symbseed=numval2($symb) << 10;
8903: my $namechck=unpack("%32S*",$username.' ');
8904:
8905: my $nameseed=numval2($username) << 21;
1.443 albertel 8906: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8907: my $courseseed=unpack("%32S*",$courseid.' ');
8908:
8909: my $num1=$symbchck+$symbseed+$namechck;
8910: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8911: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8912: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8913: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8914:
1.503 albertel 8915: return "$num1:$num2";
1.443 albertel 8916: }
8917: }
8918:
1.575 albertel 8919: sub rndseed_64bit4 {
8920: my ($symb,$courseid,$domain,$username)=@_;
8921: {
8922: use integer;
8923: # strings need to be an even # of cahracters long, it it is odd the
8924: # last characters gets thrown away
8925: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8926: my $symbseed=numval3($symb) << 10;
8927: my $namechck=unpack("%32S*",$username.' ');
8928:
8929: my $nameseed=numval3($username) << 21;
8930: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8931: my $courseseed=unpack("%32S*",$courseid.' ');
8932:
8933: my $num1=$symbchck+$symbseed+$namechck;
8934: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8935: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8936: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 8937: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8938:
8939: return "$num1:$num2";
8940: }
8941: }
8942:
1.675 albertel 8943: sub rndseed_64bit5 {
8944: my ($symb,$courseid,$domain,$username)=@_;
8945: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8946: return "$num1:$num2";
8947: }
8948:
1.366 albertel 8949: sub rndseed_CODE_64bit {
8950: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 8951: {
1.366 albertel 8952: use integer;
1.443 albertel 8953: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 8954: my $symbseed=numval2($symb);
1.491 albertel 8955: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8956: my $CODEseed=numval(&getCODE());
1.443 albertel 8957: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 8958: my $num1=$symbseed+$CODEchck;
8959: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8960: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8961: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 8962: if ($_64bit) { $num1=(($num1<<32)>>32); }
8963: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 8964: return "$num1:$num2";
1.366 albertel 8965: }
8966: }
8967:
1.575 albertel 8968: sub rndseed_CODE_64bit4 {
8969: my ($symb,$courseid,$domain,$username)=@_;
8970: {
8971: use integer;
8972: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8973: my $symbseed=numval3($symb);
8974: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8975: my $CODEseed=numval3(&getCODE());
8976: my $courseseed=unpack("%32S*",$courseid.' ');
8977: my $num1=$symbseed+$CODEchck;
8978: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8979: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8980: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 8981: if ($_64bit) { $num1=(($num1<<32)>>32); }
8982: if ($_64bit) { $num2=(($num2<<32)>>32); }
8983: return "$num1:$num2";
8984: }
8985: }
8986:
1.675 albertel 8987: sub rndseed_CODE_64bit5 {
8988: my ($symb,$courseid,$domain,$username)=@_;
8989: my $code = &getCODE();
8990: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8991: return "$num1:$num2";
8992: }
8993:
1.366 albertel 8994: sub setup_random_from_rndseed {
8995: my ($rndseed)=@_;
1.503 albertel 8996: if ($rndseed =~/([,:])/) {
8997: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 8998: &Math::Random::random_set_seed(abs($num1),abs($num2));
8999: } else {
9000: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9001: }
1.36 albertel 9002: }
9003:
1.474 albertel 9004: sub latest_receipt_algorithm_id {
1.835 albertel 9005: return 'receipt3';
1.474 albertel 9006: }
9007:
1.480 www 9008: sub recunique {
9009: my $fucourseid=shift;
9010: my $unique;
1.835 albertel 9011: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9012: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9013: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9014: } else {
9015: $unique=$perlvar{'lonReceipt'};
9016: }
9017: return unpack("%32C*",$unique);
9018: }
9019:
9020: sub recprefix {
9021: my $fucourseid=shift;
9022: my $prefix;
1.835 albertel 9023: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9024: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9025: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9026: } else {
9027: $prefix=$perlvar{'lonHostID'};
9028: }
9029: return unpack("%32C*",$prefix);
9030: }
9031:
1.76 www 9032: sub ireceipt {
1.474 albertel 9033: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9034:
9035: my $return =&recprefix($fucourseid).'-';
9036:
9037: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9038: $env{'request.state'} eq 'construct') {
9039: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9040: return $return;
9041: }
9042:
1.76 www 9043: my $cuname=unpack("%32C*",$funame);
9044: my $cudom=unpack("%32C*",$fudom);
9045: my $cucourseid=unpack("%32C*",$fucourseid);
9046: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9047: my $cunique=&recunique($fucourseid);
1.474 albertel 9048: my $cpart=unpack("%32S*",$part);
1.835 albertel 9049: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9050:
1.790 albertel 9051: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9052:
9053: $return.= ($cunique%$cuname+
9054: $cunique%$cudom+
9055: $cusymb%$cuname+
9056: $cusymb%$cudom+
9057: $cucourseid%$cuname+
9058: $cucourseid%$cudom+
9059: $cpart%$cuname+
9060: $cpart%$cudom);
9061: } else {
9062: $return.= ($cunique%$cuname+
9063: $cunique%$cudom+
9064: $cusymb%$cuname+
9065: $cusymb%$cudom+
9066: $cucourseid%$cuname+
9067: $cucourseid%$cudom);
9068: }
9069: return $return;
1.76 www 9070: }
9071:
9072: sub receipt {
1.474 albertel 9073: my ($part)=@_;
1.790 albertel 9074: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9075: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9076: }
1.260 ng 9077:
1.790 albertel 9078: sub whichuser {
9079: my ($passedsymb)=@_;
9080: my ($symb,$courseid,$domain,$name,$publicuser);
9081: if (defined($env{'form.grade_symb'})) {
9082: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9083: my $allowed=&allowed('vgr',$tmp_courseid);
9084: if (!$allowed &&
9085: exists($env{'request.course.sec'}) &&
9086: $env{'request.course.sec'} !~ /^\s*$/) {
9087: $allowed=&allowed('vgr',$tmp_courseid.
9088: '/'.$env{'request.course.sec'});
9089: }
9090: if ($allowed) {
9091: ($symb)=&get_env_multiple('form.grade_symb');
9092: $courseid=$tmp_courseid;
9093: ($domain)=&get_env_multiple('form.grade_domain');
9094: ($name)=&get_env_multiple('form.grade_username');
9095: return ($symb,$courseid,$domain,$name,$publicuser);
9096: }
9097: }
9098: if (!$passedsymb) {
9099: $symb=&symbread();
9100: } else {
9101: $symb=$passedsymb;
9102: }
9103: $courseid=$env{'request.course.id'};
9104: $domain=$env{'user.domain'};
9105: $name=$env{'user.name'};
9106: if ($name eq 'public' && $domain eq 'public') {
9107: if (!defined($env{'form.username'})) {
9108: $env{'form.username'}.=time.rand(10000000);
9109: }
9110: $name.=$env{'form.username'};
9111: }
9112: return ($symb,$courseid,$domain,$name,$publicuser);
9113:
9114: }
9115:
1.36 albertel 9116: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9117: # returns either the contents of the file or
9118: # -1 if the file doesn't exist
1.481 raeburn 9119: #
9120: # if the target is a file that was uploaded via DOCS,
9121: # a check will be made to see if a current copy exists on the local server,
9122: # if it does this will be served, otherwise a copy will be retrieved from
9123: # the home server for the course and stored in /home/httpd/html/userfiles on
9124: # the local server.
1.472 albertel 9125:
1.36 albertel 9126: sub getfile {
1.538 albertel 9127: my ($file) = @_;
1.609 banghart 9128: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9129: &repcopy($file);
9130: return &readfile($file);
9131: }
9132:
9133: sub repcopy_userfile {
9134: my ($file)=@_;
1.609 banghart 9135: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9136: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9137: my ($cdom,$cnum,$filename) =
1.811 albertel 9138: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9139: my $uri="/uploaded/$cdom/$cnum/$filename";
9140: if (-e "$file") {
1.828 www 9141: # we already have a local copy, check it out
1.538 albertel 9142: my @fileinfo = stat($file);
1.828 www 9143: my $rtncode;
9144: my $info;
1.538 albertel 9145: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9146: if ($lwpresp ne 'ok') {
1.828 www 9147: # there is no such file anymore, even though we had a local copy
1.482 albertel 9148: if ($rtncode eq '404') {
1.538 albertel 9149: unlink($file);
1.482 albertel 9150: }
9151: return -1;
9152: }
9153: if ($info < $fileinfo[9]) {
1.828 www 9154: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9155: return 'ok';
1.828 www 9156: } else {
9157: # the file is outdated, get rid of it
9158: unlink($file);
1.482 albertel 9159: }
1.828 www 9160: }
9161: # one way or the other, at this point, we don't have the file
9162: # construct the correct path for the file
9163: my @parts = ($cdom,$cnum);
9164: if ($filename =~ m|^(.+)/[^/]+$|) {
9165: push @parts, split(/\//,$1);
9166: }
9167: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9168: foreach my $part (@parts) {
9169: $path .= '/'.$part;
9170: if (!-e $path) {
9171: mkdir($path,0770);
1.482 albertel 9172: }
9173: }
1.828 www 9174: # now the path exists for sure
9175: # get a user agent
9176: my $ua=new LWP::UserAgent;
9177: my $transferfile=$file.'.in.transfer';
9178: # FIXME: this should flock
9179: if (-e $transferfile) { return 'ok'; }
9180: my $request;
9181: $uri=~s/^\///;
1.980 raeburn 9182: my $homeserver = &homeserver($cnum,$cdom);
9183: my $protocol = $protocol{$homeserver};
9184: $protocol = 'http' if ($protocol ne 'https');
9185: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9186: my $response=$ua->request($request,$transferfile);
9187: # did it work?
9188: if ($response->is_error()) {
9189: unlink($transferfile);
9190: &logthis("Userfile repcopy failed for $uri");
9191: return -1;
9192: }
9193: # worked, rename the transfer file
9194: rename($transferfile,$file);
1.607 raeburn 9195: return 'ok';
1.481 raeburn 9196: }
9197:
1.517 albertel 9198: sub tokenwrapper {
9199: my $uri=shift;
1.980 raeburn 9200: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9201: $uri=~s|^/||;
1.620 albertel 9202: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9203: my $token=$1;
1.552 albertel 9204: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9205: if ($udom && $uname && $file) {
9206: $file=~s|(\?\.*)*$||;
1.949 raeburn 9207: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9208: my $homeserver = &homeserver($uname,$udom);
9209: my $protocol = $protocol{$homeserver};
9210: $protocol = 'http' if ($protocol ne 'https');
9211: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9212: (($uri=~/\?/)?'&':'?').'token='.$token.
9213: '&tokenissued='.$perlvar{'lonHostID'};
9214: } else {
9215: return '/adm/notfound.html';
9216: }
9217: }
9218:
1.828 www 9219: # call with reqtype HEAD: get last modification time
9220: # call with reqtype GET: get the file contents
9221: # Do not call this with reqtype GET for large files! It loads everything into memory
9222: #
1.481 raeburn 9223: sub getuploaded {
9224: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9225: $uri=~s/^\///;
1.980 raeburn 9226: my $homeserver = &homeserver($cnum,$cdom);
9227: my $protocol = $protocol{$homeserver};
9228: $protocol = 'http' if ($protocol ne 'https');
9229: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9230: my $ua=new LWP::UserAgent;
9231: my $request=new HTTP::Request($reqtype,$uri);
9232: my $response=$ua->request($request);
9233: $$rtncode = $response->code;
1.482 albertel 9234: if (! $response->is_success()) {
9235: return 'failed';
9236: }
9237: if ($reqtype eq 'HEAD') {
1.486 www 9238: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9239: } elsif ($reqtype eq 'GET') {
9240: $$info = $response->content;
1.472 albertel 9241: }
1.482 albertel 9242: return 'ok';
1.36 albertel 9243: }
9244:
1.481 raeburn 9245: sub readfile {
9246: my $file = shift;
9247: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9248: my $fh;
9249: open($fh,"<$file");
9250: my $a='';
1.800 albertel 9251: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9252: return $a;
9253: }
9254:
1.36 albertel 9255: sub filelocation {
1.590 banghart 9256: my ($dir,$file) = @_;
9257: my $location;
9258: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9259:
9260: if ($file =~ m-^/adm/-) {
9261: $file=~s-^/adm/wrapper/-/-;
9262: $file=~s-^/adm/coursedocs/showdoc/-/-;
9263: }
1.882 albertel 9264:
1.590 banghart 9265: if ($file=~m:^/~:) { # is a contruction space reference
9266: $location = $file;
9267: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9268: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9269: # is a correct contruction space reference
9270: $location = $file;
1.956 raeburn 9271: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9272: $location = $file;
1.609 banghart 9273: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9274: my ($udom,$uname,$filename)=
1.811 albertel 9275: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9276: my $home=&homeserver($uname,$udom);
9277: my $is_me=0;
9278: my @ids=¤t_machine_ids();
9279: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9280: if ($is_me) {
1.955 raeburn 9281: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9282: } else {
9283: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9284: $udom.'/'.$uname.'/'.$filename;
9285: }
1.882 albertel 9286: } elsif ($file =~ m-^/adm/-) {
9287: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9288: } else {
9289: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9290: $file=~s:^/res/:/:;
9291: if ( !( $file =~ m:^/:) ) {
9292: $location = $dir. '/'.$file;
9293: } else {
9294: $location = '/home/httpd/html/res'.$file;
9295: }
1.59 albertel 9296: }
1.590 banghart 9297: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9298: while ($location=~m{/\.\./}) {
9299: if ($location =~ m{/[^/]+/\.\./}) {
9300: $location=~ s{/[^/]+/\.\./}{/}g;
9301: } else {
9302: $location=~ s{/\.\./}{/}g;
9303: }
9304: } #remove dir/..
1.590 banghart 9305: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9306: return $location;
1.46 www 9307: }
1.36 albertel 9308:
1.46 www 9309: sub hreflocation {
9310: my ($dir,$file)=@_;
1.980 raeburn 9311: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9312: $file=filelocation($dir,$file);
1.700 albertel 9313: } elsif ($file=~m-^/adm/-) {
9314: $file=~s-^/adm/wrapper/-/-;
9315: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9316: }
9317: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9318: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9319: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9320: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9321: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9322: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9323: -/uploaded/$1/$2/-x;
1.46 www 9324: }
1.913 albertel 9325: if ($file=~ m{^/userfiles/}) {
9326: $file =~ s{^/userfiles/}{/uploaded/};
9327: }
1.462 albertel 9328: return $file;
1.465 albertel 9329: }
9330:
9331: sub current_machine_domains {
1.853 albertel 9332: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9333: }
9334:
9335: sub machine_domains {
9336: my ($hostname) = @_;
1.465 albertel 9337: my @domains;
1.838 albertel 9338: my %hostname = &all_hostnames();
1.465 albertel 9339: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9340: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9341: if ($hostname eq $name) {
1.844 albertel 9342: push(@domains,&host_domain($id));
1.465 albertel 9343: }
9344: }
9345: return @domains;
9346: }
9347:
9348: sub current_machine_ids {
1.853 albertel 9349: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9350: }
9351:
9352: sub machine_ids {
9353: my ($hostname) = @_;
9354: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9355: my @ids;
1.888 albertel 9356: my %name_to_host = &all_names();
1.889 albertel 9357: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9358: return @{ $name_to_host{$hostname} };
9359: }
9360: return;
1.31 www 9361: }
9362:
1.824 raeburn 9363: sub additional_machine_domains {
9364: my @domains;
9365: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9366: while( my $line = <$fh>) {
9367: $line =~ s/\s//g;
9368: push(@domains,$line);
9369: }
9370: return @domains;
9371: }
9372:
9373: sub default_login_domain {
9374: my $domain = $perlvar{'lonDefDomain'};
9375: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9376: foreach my $posdom (¤t_machine_domains(),
9377: &additional_machine_domains()) {
9378: if (lc($posdom) eq lc($testdomain)) {
9379: $domain=$posdom;
9380: last;
9381: }
9382: }
9383: return $domain;
9384: }
9385:
1.31 www 9386: # ------------------------------------------------------------- Declutters URLs
9387:
9388: sub declutter {
9389: my $thisfn=shift;
1.569 albertel 9390: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9391: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9392: $thisfn=~s/^\///;
1.697 albertel 9393: $thisfn=~s|^adm/wrapper/||;
9394: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9395: $thisfn=~s/^res\///;
1.1032 raeburn 9396: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9397: $thisfn=~s/\?.+$//;
9398: }
1.268 www 9399: return $thisfn;
9400: }
9401:
9402: # ------------------------------------------------------------- Clutter up URLs
9403:
9404: sub clutter {
9405: my $thisfn='/'.&declutter(shift);
1.887 albertel 9406: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9407: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9408: $thisfn='/res'.$thisfn;
9409: }
1.1031 raeburn 9410: if ($thisfn !~m|^/adm|) {
9411: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9412: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9413: } else {
9414: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9415: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9416: if ($embstyle eq 'ssi'
9417: || ($embstyle eq 'hdn')
9418: || ($embstyle eq 'rat')
9419: || ($embstyle eq 'prv')
9420: || ($embstyle eq 'ign')) {
9421: #do nothing with these
9422: } elsif (($embstyle eq 'img')
1.695 albertel 9423: || ($embstyle eq 'emb')
9424: || ($embstyle eq 'wrp')) {
9425: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9426: } elsif ($embstyle eq 'unk'
9427: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9428: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9429: } else {
1.718 www 9430: # &logthis("Got a blank emb style");
1.695 albertel 9431: }
1.694 albertel 9432: }
9433: }
1.31 www 9434: return $thisfn;
1.12 www 9435: }
9436:
1.787 albertel 9437: sub clutter_with_no_wrapper {
9438: my $uri = &clutter(shift);
9439: if ($uri =~ m-^/adm/-) {
9440: $uri =~ s-^/adm/wrapper/-/-;
9441: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9442: }
9443: return $uri;
9444: }
9445:
1.557 albertel 9446: sub freeze_escape {
9447: my ($value)=@_;
9448: if (ref($value)) {
9449: $value=&nfreeze($value);
9450: return '__FROZEN__'.&escape($value);
9451: }
9452: return &escape($value);
9453: }
9454:
1.11 www 9455:
1.557 albertel 9456: sub thaw_unescape {
9457: my ($value)=@_;
9458: if ($value =~ /^__FROZEN__/) {
9459: substr($value,0,10,undef);
9460: $value=&unescape($value);
9461: return &thaw($value);
9462: }
9463: return &unescape($value);
9464: }
9465:
1.436 albertel 9466: sub correct_line_ends {
9467: my ($result)=@_;
9468: $$result =~s/\r\n/\n/mg;
9469: $$result =~s/\r/\n/mg;
1.415 albertel 9470: }
1.1 albertel 9471: # ================================================================ Main Program
9472:
1.184 www 9473: sub goodbye {
1.204 albertel 9474: &logthis("Starting Shut down");
1.443 albertel 9475: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9476: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9477: #converted
1.599 albertel 9478: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9479: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9480: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9481: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9482: #1.1 only
1.870 albertel 9483: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9484: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9485: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9486: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9487: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9488: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9489: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9490: &flushcourselogs();
9491: &logthis("Shutting down");
9492: }
9493:
1.852 albertel 9494: sub get_dns {
1.869 albertel 9495: my ($url,$func,$ignore_cache) = @_;
9496: if (!$ignore_cache) {
9497: my ($content,$cached)=
9498: &Apache::lonnet::is_cached_new('dns',$url);
9499: if ($cached) {
9500: &$func($content);
9501: return;
9502: }
9503: }
9504:
9505: my %alldns;
1.852 albertel 9506: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9507: foreach my $dns (<$config>) {
9508: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9509: my $line = $1;
9510: my ($host,$protocol) = split(/:/,$line);
9511: if ($protocol ne 'https') {
9512: $protocol = 'http';
9513: }
9514: $alldns{$host} = $protocol;
1.869 albertel 9515: }
9516: while (%alldns) {
9517: my ($dns) = keys(%alldns);
1.852 albertel 9518: my $ua=new LWP::UserAgent;
1.979 raeburn 9519: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9520: my $response=$ua->request($request);
1.979 raeburn 9521: delete($alldns{$dns});
1.852 albertel 9522: next if ($response->is_error());
9523: my @content = split("\n",$response->content);
1.869 albertel 9524: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9525: &$func(\@content);
1.869 albertel 9526: return;
1.852 albertel 9527: }
9528: close($config);
1.871 albertel 9529: my $which = (split('/',$url))[3];
9530: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9531: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9532: my @content = <$config>;
9533: &$func(\@content);
9534: return;
1.852 albertel 9535: }
1.327 albertel 9536: # ------------------------------------------------------------ Read domain file
9537: {
1.852 albertel 9538: my $loaded;
1.846 albertel 9539: my %domain;
9540:
1.852 albertel 9541: sub parse_domain_tab {
9542: my ($lines) = @_;
9543: foreach my $line (@$lines) {
9544: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9545:
1.846 albertel 9546: chomp($line);
1.852 albertel 9547: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9548: my %this_domain;
9549: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9550: 'lang_def', 'city', 'longi', 'lati',
9551: 'primary') {
9552: $this_domain{$field} = shift(@elements);
9553: }
9554: $domain{$name} = \%this_domain;
1.852 albertel 9555: }
9556: }
1.864 albertel 9557:
9558: sub reset_domain_info {
9559: undef($loaded);
9560: undef(%domain);
9561: }
9562:
1.852 albertel 9563: sub load_domain_tab {
1.869 albertel 9564: my ($ignore_cache) = @_;
9565: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9566: my $fh;
9567: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9568: my @lines = <$fh>;
9569: &parse_domain_tab(\@lines);
1.448 albertel 9570: }
1.852 albertel 9571: close($fh);
9572: $loaded = 1;
1.327 albertel 9573: }
1.846 albertel 9574:
9575: sub domain {
1.852 albertel 9576: &load_domain_tab() if (!$loaded);
9577:
1.846 albertel 9578: my ($name,$what) = @_;
9579: return if ( !exists($domain{$name}) );
9580:
9581: if (!$what) {
9582: return $domain{$name}{'description'};
9583: }
9584: return $domain{$name}{$what};
9585: }
1.974 raeburn 9586:
9587: sub domain_info {
9588: &load_domain_tab() if (!$loaded);
9589: return %domain;
9590: }
9591:
1.327 albertel 9592: }
9593:
9594:
1.1 albertel 9595: # ------------------------------------------------------------- Read hosts file
9596: {
1.838 albertel 9597: my %hostname;
1.844 albertel 9598: my %hostdom;
1.845 albertel 9599: my %libserv;
1.852 albertel 9600: my $loaded;
1.888 albertel 9601: my %name_to_host;
1.852 albertel 9602:
9603: sub parse_hosts_tab {
9604: my ($file) = @_;
9605: foreach my $configline (@$file) {
9606: next if ($configline =~ /^(\#|\s*$ )/x);
9607: next if ($configline =~ /^\^/);
9608: chomp($configline);
1.968 raeburn 9609: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 9610: $name=~s/\s//g;
9611: if ($id && $domain && $role && $name) {
9612: $hostname{$id}=$name;
1.888 albertel 9613: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9614: $hostdom{$id}=$domain;
9615: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9616: if (defined($protocol)) {
9617: if ($protocol eq 'https') {
9618: $protocol{$id} = $protocol;
9619: } else {
9620: $protocol{$id} = 'http';
9621: }
1.968 raeburn 9622: } else {
1.969 raeburn 9623: $protocol{$id} = 'http';
1.968 raeburn 9624: }
1.852 albertel 9625: }
9626: }
9627: }
1.864 albertel 9628:
9629: sub reset_hosts_info {
1.897 albertel 9630: &purge_remembered();
1.864 albertel 9631: &reset_domain_info();
9632: &reset_hosts_ip_info();
1.892 albertel 9633: undef(%name_to_host);
1.864 albertel 9634: undef(%hostname);
9635: undef(%hostdom);
9636: undef(%libserv);
9637: undef($loaded);
9638: }
1.1 albertel 9639:
1.852 albertel 9640: sub load_hosts_tab {
1.869 albertel 9641: my ($ignore_cache) = @_;
9642: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9643: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9644: my @config = <$config>;
9645: &parse_hosts_tab(\@config);
9646: close($config);
9647: $loaded=1;
1.1 albertel 9648: }
1.852 albertel 9649:
1.838 albertel 9650: sub hostname {
1.852 albertel 9651: &load_hosts_tab() if (!$loaded);
9652:
1.838 albertel 9653: my ($lonid) = @_;
9654: return $hostname{$lonid};
9655: }
1.845 albertel 9656:
1.838 albertel 9657: sub all_hostnames {
1.852 albertel 9658: &load_hosts_tab() if (!$loaded);
9659:
1.838 albertel 9660: return %hostname;
9661: }
1.845 albertel 9662:
1.888 albertel 9663: sub all_names {
9664: &load_hosts_tab() if (!$loaded);
9665:
9666: return %name_to_host;
9667: }
9668:
1.974 raeburn 9669: sub all_host_domain {
9670: &load_hosts_tab() if (!$loaded);
9671: return %hostdom;
9672: }
9673:
1.845 albertel 9674: sub is_library {
1.852 albertel 9675: &load_hosts_tab() if (!$loaded);
9676:
1.845 albertel 9677: return exists($libserv{$_[0]});
9678: }
9679:
9680: sub all_library {
1.852 albertel 9681: &load_hosts_tab() if (!$loaded);
9682:
1.845 albertel 9683: return %libserv;
9684: }
9685:
1.841 albertel 9686: sub get_servers {
1.852 albertel 9687: &load_hosts_tab() if (!$loaded);
9688:
1.841 albertel 9689: my ($domain,$type) = @_;
9690: my %possible_hosts = ($type eq 'library') ? %libserv
9691: : %hostname;
9692: my %result;
1.842 albertel 9693: if (ref($domain) eq 'ARRAY') {
9694: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9695: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9696: $result{$host} = $hostname;
9697: }
9698: }
9699: } else {
9700: while ( my ($host,$hostname) = each(%possible_hosts)) {
9701: if ($hostdom{$host} eq $domain) {
9702: $result{$host} = $hostname;
9703: }
1.841 albertel 9704: }
9705: }
9706: return %result;
9707: }
1.845 albertel 9708:
1.844 albertel 9709: sub host_domain {
1.852 albertel 9710: &load_hosts_tab() if (!$loaded);
9711:
1.844 albertel 9712: my ($lonid) = @_;
9713: return $hostdom{$lonid};
9714: }
9715:
1.841 albertel 9716: sub all_domains {
1.852 albertel 9717: &load_hosts_tab() if (!$loaded);
9718:
1.841 albertel 9719: my %seen;
9720: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9721: return @uniq;
9722: }
1.1 albertel 9723: }
9724:
1.847 albertel 9725: {
9726: my %iphost;
1.856 albertel 9727: my %name_to_ip;
9728: my %lonid_to_ip;
1.869 albertel 9729:
1.847 albertel 9730: sub get_hosts_from_ip {
9731: my ($ip) = @_;
9732: my %iphosts = &get_iphost();
9733: if (ref($iphosts{$ip})) {
9734: return @{$iphosts{$ip}};
9735: }
9736: return;
1.839 albertel 9737: }
1.864 albertel 9738:
9739: sub reset_hosts_ip_info {
9740: undef(%iphost);
9741: undef(%name_to_ip);
9742: undef(%lonid_to_ip);
9743: }
1.856 albertel 9744:
9745: sub get_host_ip {
9746: my ($lonid) = @_;
9747: if (exists($lonid_to_ip{$lonid})) {
9748: return $lonid_to_ip{$lonid};
9749: }
9750: my $name=&hostname($lonid);
9751: my $ip = gethostbyname($name);
9752: return if (!$ip || length($ip) ne 4);
9753: $ip=inet_ntoa($ip);
9754: $name_to_ip{$name} = $ip;
9755: $lonid_to_ip{$lonid} = $ip;
9756: return $ip;
9757: }
1.847 albertel 9758:
9759: sub get_iphost {
1.869 albertel 9760: my ($ignore_cache) = @_;
1.894 albertel 9761:
1.869 albertel 9762: if (!$ignore_cache) {
9763: if (%iphost) {
9764: return %iphost;
9765: }
9766: my ($ip_info,$cached)=
9767: &Apache::lonnet::is_cached_new('iphost','iphost');
9768: if ($cached) {
9769: %iphost = %{$ip_info->[0]};
9770: %name_to_ip = %{$ip_info->[1]};
9771: %lonid_to_ip = %{$ip_info->[2]};
9772: return %iphost;
9773: }
9774: }
1.894 albertel 9775:
9776: # get yesterday's info for fallback
9777: my %old_name_to_ip;
9778: my ($ip_info,$cached)=
9779: &Apache::lonnet::is_cached_new('iphost','iphost');
9780: if ($cached) {
9781: %old_name_to_ip = %{$ip_info->[1]};
9782: }
9783:
1.888 albertel 9784: my %name_to_host = &all_names();
9785: foreach my $name (keys(%name_to_host)) {
1.847 albertel 9786: my $ip;
9787: if (!exists($name_to_ip{$name})) {
9788: $ip = gethostbyname($name);
9789: if (!$ip || length($ip) ne 4) {
1.894 albertel 9790: if (defined($old_name_to_ip{$name})) {
9791: $ip = $old_name_to_ip{$name};
9792: &logthis("Can't find $name defaulting to old $ip");
9793: } else {
9794: &logthis("Name $name no IP found");
9795: next;
9796: }
9797: } else {
9798: $ip=inet_ntoa($ip);
1.847 albertel 9799: }
9800: $name_to_ip{$name} = $ip;
9801: } else {
9802: $ip = $name_to_ip{$name};
1.653 albertel 9803: }
1.888 albertel 9804: foreach my $id (@{ $name_to_host{$name} }) {
9805: $lonid_to_ip{$id} = $ip;
9806: }
9807: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9808: }
1.869 albertel 9809: &Apache::lonnet::do_cache_new('iphost','iphost',
9810: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9811: 48*60*60);
1.869 albertel 9812:
1.847 albertel 9813: return %iphost;
1.598 albertel 9814: }
9815:
1.992 raeburn 9816: #
9817: # Given a DNS returns the loncapa host name for that DNS
9818: #
9819: sub host_from_dns {
9820: my ($dns) = @_;
9821: my @hosts;
9822: my $ip;
9823:
1.993 raeburn 9824: if (exists($name_to_ip{$dns})) {
1.992 raeburn 9825: $ip = $name_to_ip{$dns};
9826: }
9827: if (!$ip) {
9828: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9829: if (length($ip) == 4) {
9830: $ip = &IO::Socket::inet_ntoa($ip);
9831: }
9832: }
9833: if ($ip) {
9834: @hosts = get_hosts_from_ip($ip);
9835: return $hosts[0];
9836: }
9837: return undef;
1.986 foxr 9838: }
1.992 raeburn 9839:
1.986 foxr 9840: }
9841:
1.862 albertel 9842: BEGIN {
9843:
9844: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9845: unless ($readit) {
9846: {
9847: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9848: %perlvar = (%perlvar,%{$configvars});
9849: }
9850:
9851:
1.1 albertel 9852: # ------------------------------------------------------ Read spare server file
9853: {
1.448 albertel 9854: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9855:
9856: while (my $configline=<$config>) {
9857: chomp($configline);
1.284 matthew 9858: if ($configline) {
1.784 albertel 9859: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9860: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9861: push(@{ $spareid{$type} }, $host);
1.1 albertel 9862: }
9863: }
1.448 albertel 9864: close($config);
1.1 albertel 9865: }
1.11 www 9866: # ------------------------------------------------------------ Read permissions
9867: {
1.448 albertel 9868: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9869:
9870: while (my $configline=<$config>) {
1.448 albertel 9871: chomp($configline);
9872: if ($configline) {
9873: my ($role,$perm)=split(/ /,$configline);
9874: if ($perm ne '') { $pr{$role}=$perm; }
9875: }
1.11 www 9876: }
1.448 albertel 9877: close($config);
1.11 www 9878: }
9879:
9880: # -------------------------------------------- Read plain texts for permissions
9881: {
1.448 albertel 9882: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9883:
9884: while (my $configline=<$config>) {
1.448 albertel 9885: chomp($configline);
9886: if ($configline) {
1.742 raeburn 9887: my ($short,@plain)=split(/:/,$configline);
9888: %{$prp{$short}} = ();
9889: if (@plain > 0) {
9890: $prp{$short}{'std'} = $plain[0];
9891: for (my $i=1; $i<@plain; $i++) {
9892: $prp{$short}{'alt'.$i} = $plain[$i];
9893: }
9894: }
1.448 albertel 9895: }
1.135 www 9896: }
1.448 albertel 9897: close($config);
1.135 www 9898: }
9899:
9900: # ---------------------------------------------------------- Read package table
9901: {
1.448 albertel 9902: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9903:
9904: while (my $configline=<$config>) {
1.483 albertel 9905: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9906: chomp($configline);
9907: my ($short,$plain)=split(/:/,$configline);
9908: my ($pack,$name)=split(/\&/,$short);
9909: if ($plain ne '') {
9910: $packagetab{$pack.'&'.$name.'&name'}=$name;
9911: $packagetab{$short}=$plain;
9912: }
1.11 www 9913: }
1.448 albertel 9914: close($config);
1.329 matthew 9915: }
9916:
9917: # ------------- set up temporary directory
9918: {
9919: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9920:
1.11 www 9921: }
9922:
1.794 albertel 9923: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9924: 'compress_threshold'=> 20_000,
9925: });
1.185 www 9926:
1.281 www 9927: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 9928: $dumpcount=0;
1.958 www 9929: $locknum=0;
1.22 www 9930:
1.163 harris41 9931: &logtouch();
1.672 albertel 9932: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 9933: $readit=1;
1.564 albertel 9934: {
9935: use integer;
9936: my $test=(2**32)+1;
1.568 albertel 9937: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 9938: &logthis(" Detected 64bit platform ($_64bit)");
9939: }
1.195 www 9940: }
1.1 albertel 9941: }
1.179 www 9942:
1.1 albertel 9943: 1;
1.191 harris41 9944: __END__
9945:
1.243 albertel 9946: =pod
9947:
1.191 harris41 9948: =head1 NAME
9949:
1.243 albertel 9950: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 9951:
9952: =head1 SYNOPSIS
9953:
1.243 albertel 9954: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 9955:
9956: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9957:
1.243 albertel 9958: Common parameters:
9959:
9960: =over 4
9961:
9962: =item *
9963:
9964: $uname : an internal username (if $cname expecting a course Id specifically)
9965:
9966: =item *
9967:
9968: $udom : a domain (if $cdom expecting a course's domain specifically)
9969:
9970: =item *
9971:
9972: $symb : a resource instance identifier
9973:
9974: =item *
9975:
9976: $namespace : the name of a .db file that contains the data needed or
9977: being set.
9978:
9979: =back
9980:
1.394 bowersj2 9981: =head1 OVERVIEW
1.191 harris41 9982:
1.394 bowersj2 9983: lonnet provides subroutines which interact with the
9984: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9985: about classes, users, and resources.
1.243 albertel 9986:
9987: For many of these objects you can also use this to store data about
9988: them or modify them in various ways.
1.191 harris41 9989:
1.394 bowersj2 9990: =head2 Symbs
1.191 harris41 9991:
1.394 bowersj2 9992: To identify a specific instance of a resource, LON-CAPA uses symbols
9993: or "symbs"X<symb>. These identifiers are built from the URL of the
9994: map, the resource number of the resource in the map, and the URL of
9995: the resource itself. The latter is somewhat redundant, but might help
9996: if maps change.
9997:
9998: An example is
9999:
10000: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10001:
10002: The respective map entry is
10003:
10004: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10005: title="Problem 2">
10006: </resource>
10007:
10008: Symbs are used by the random number generator, as well as to store and
10009: restore data specific to a certain instance of for example a problem.
10010:
10011: =head2 Storing And Retrieving Data
10012:
10013: X<store()>X<cstore()>X<restore()>Three of the most important functions
10014: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10015: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10016: is is the non-critical message twin of cstore. These functions are for
10017: handlers to store a perl hash to a user's permanent data space in an
10018: easy manner, and to retrieve it again on another call. It is expected
10019: that a handler would use this once at the beginning to retrieve data,
10020: and then again once at the end to send only the new data back.
10021:
10022: The data is stored in the user's data directory on the user's
10023: homeserver under the ID of the course.
10024:
10025: The hash that is returned by restore will have all of the previous
10026: value for all of the elements of the hash.
10027:
10028: Example:
10029:
10030: #creating a hash
10031: my %hash;
10032: $hash{'foo'}='bar';
10033:
10034: #storing it
10035: &Apache::lonnet::cstore(\%hash);
10036:
10037: #changing a value
10038: $hash{'foo'}='notbar';
10039:
10040: #adding a new value
10041: $hash{'bar'}='foo';
10042: &Apache::lonnet::cstore(\%hash);
10043:
10044: #retrieving the hash
10045: my %history=&Apache::lonnet::restore();
10046:
10047: #print the hash
10048: foreach my $key (sort(keys(%history))) {
10049: print("\%history{$key} = $history{$key}");
10050: }
10051:
10052: Will print out:
1.191 harris41 10053:
1.394 bowersj2 10054: %history{1:foo} = bar
10055: %history{1:keys} = foo:timestamp
10056: %history{1:timestamp} = 990455579
10057: %history{2:bar} = foo
10058: %history{2:foo} = notbar
10059: %history{2:keys} = foo:bar:timestamp
10060: %history{2:timestamp} = 990455580
10061: %history{bar} = foo
10062: %history{foo} = notbar
10063: %history{timestamp} = 990455580
10064: %history{version} = 2
10065:
10066: Note that the special hash entries C<keys>, C<version> and
10067: C<timestamp> were added to the hash. C<version> will be equal to the
10068: total number of versions of the data that have been stored. The
10069: C<timestamp> attribute will be the UNIX time the hash was
10070: stored. C<keys> is available in every historical section to list which
10071: keys were added or changed at a specific historical revision of a
10072: hash.
10073:
10074: B<Warning>: do not store the hash that restore returns directly. This
10075: will cause a mess since it will restore the historical keys as if the
10076: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10077:
1.394 bowersj2 10078: Calling convention:
1.191 harris41 10079:
1.394 bowersj2 10080: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10081: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10082:
1.394 bowersj2 10083: For more detailed information, see lonnet specific documentation.
1.191 harris41 10084:
1.394 bowersj2 10085: =head1 RETURN MESSAGES
1.191 harris41 10086:
1.394 bowersj2 10087: =over 4
1.191 harris41 10088:
1.394 bowersj2 10089: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10090:
1.394 bowersj2 10091: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10092: when the connection is brought back up
1.191 harris41 10093:
1.394 bowersj2 10094: =item * B<con_failed>: unable to contact remote host and unable to save message
10095: for later delivery
1.191 harris41 10096:
1.967 bisitz 10097: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10098:
1.394 bowersj2 10099: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10100: that was requested
1.191 harris41 10101:
1.243 albertel 10102: =back
1.191 harris41 10103:
1.243 albertel 10104: =head1 PUBLIC SUBROUTINES
1.191 harris41 10105:
1.243 albertel 10106: =head2 Session Environment Functions
1.191 harris41 10107:
1.243 albertel 10108: =over 4
1.191 harris41 10109:
1.394 bowersj2 10110: =item *
10111: X<appenv()>
1.949 raeburn 10112: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10113: the user envirnoment file, and will be restored for each access this
1.620 albertel 10114: user makes during this session, also modifies the %env for the current
1.949 raeburn 10115: process. Optional rolesarrayref - if defined contains a reference to an array
10116: of roles which are exempt from the restriction on modifying user.role entries
10117: in the user's environment.db and in %env.
1.191 harris41 10118:
10119: =item *
1.394 bowersj2 10120: X<delenv()>
1.987 raeburn 10121: B<delenv($delthis,$regexp)>: removes all items from the session
10122: environment file that begin with $delthis. If the
10123: optional second arg - $regexp - is true, $delthis is treated as a
10124: regular expression, otherwise \Q$delthis\E is used.
10125: The values are also deleted from the current processes %env.
1.191 harris41 10126:
1.795 albertel 10127: =item * get_env_multiple($name)
10128:
10129: gets $name from the %env hash, it seemlessly handles the cases where multiple
10130: values may be defined and end up as an array ref.
10131:
10132: returns an array of values
10133:
1.243 albertel 10134: =back
10135:
10136: =head2 User Information
1.191 harris41 10137:
1.243 albertel 10138: =over 4
1.191 harris41 10139:
10140: =item *
1.394 bowersj2 10141: X<queryauthenticate()>
10142: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10143: authentication scheme
10144:
10145: =item *
1.394 bowersj2 10146: X<authenticate()>
10147: B<authenticate($uname,$upass,$udom)>: try to
10148: authenticate user from domain's lib servers (first use the current
10149: one). C<$upass> should be the users password.
1.191 harris41 10150:
10151: =item *
1.394 bowersj2 10152: X<homeserver()>
10153: B<homeserver($uname,$udom)>: find the server which has
10154: the user's directory and files (there must be only one), this caches
10155: the answer, and also caches if there is a borken connection.
1.191 harris41 10156:
10157: =item *
1.394 bowersj2 10158: X<idget()>
10159: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10160: (IDs are a unique resource in a domain, there must be only 1 ID per
10161: username, and only 1 username per ID in a specific domain) (returns
10162: hash: id=>name,id=>name)
1.191 harris41 10163:
10164: =item *
1.394 bowersj2 10165: X<idrget()>
10166: B<idrget($udom,@unames)>: find the IDs behind a list of
10167: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10168:
10169: =item *
1.394 bowersj2 10170: X<idput()>
10171: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10172:
10173: =item *
1.394 bowersj2 10174: X<rolesinit()>
10175: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10176:
10177: =item *
1.551 albertel 10178: X<getsection()>
10179: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10180: course $cname, return section name/number or '' for "not in course"
10181: and '-1' for "no section"
10182:
10183: =item *
1.394 bowersj2 10184: X<userenvironment()>
10185: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10186: passed in @what from the requested user's environment, returns a hash
10187:
1.858 raeburn 10188: =item *
10189: X<userlog_query()>
1.859 albertel 10190: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10191: activity.log file. %filters defines filters applied when parsing the
10192: log file. These can be start or end timestamps, or the type of action
10193: - log to look for Login or Logout events, check for Checkin or
10194: Checkout, role for role selection. The response is in the form
10195: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10196: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10197:
1.243 albertel 10198: =back
10199:
10200: =head2 User Roles
10201:
10202: =over 4
10203:
10204: =item *
10205:
1.810 raeburn 10206: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10207: F: full access
10208: U,I,K: authentication modes (cxx only)
10209: '': forbidden
10210: 1: user needs to choose course
10211: 2: browse allowed
1.766 albertel 10212: A: passphrase authentication needed
1.243 albertel 10213:
10214: =item *
10215:
10216: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10217: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10218: and course level
10219:
10220: =item *
10221:
1.988 raeburn 10222: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10223: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10224: $type is Course (default) or Community.
1.988 raeburn 10225: If $forcedefault evaluates to true, text returned will be default
10226: text for $type. Otherwise, if this is a course, the text returned
10227: will be a custom name for the role (if defined in the course's
10228: environment). If no custom name is defined the default is returned.
10229:
1.832 raeburn 10230: =item *
10231:
1.935 raeburn 10232: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10233: All arguments are optional. Returns a hash of a roles, either for
10234: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10235: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10236: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10237: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10238: For each key, value is set to colon-separated start and end times for
10239: the role. If no username and domain are specified, will default to
1.934 raeburn 10240: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10241: of role statuses (active, future or previous), roles
10242: (e.g., cc,in, st etc.) and domains of the roles which can be used
10243: to restrict the list of roles reported. If no array ref is
10244: provided for types, will default to return only active roles.
1.834 albertel 10245:
1.243 albertel 10246: =back
10247:
10248: =head2 User Modification
10249:
10250: =over 4
10251:
10252: =item *
10253:
1.957 raeburn 10254: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10255: user for the level given by URL. Optional start and end dates (leave empty
10256: string or zero for "no date")
1.191 harris41 10257:
10258: =item *
10259:
1.243 albertel 10260: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10261: change a users, password, possible return values are: ok,
10262: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10263: refused
1.191 harris41 10264:
10265: =item *
10266:
1.243 albertel 10267: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10268:
10269: =item *
10270:
1.1058 raeburn 10271: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10272: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10273:
10274: will update user information (firstname,middlename,lastname,generation,
10275: permanentemail), and if forceid is true, student/employee ID also.
10276: A user's institutional affiliation(s) can also be updated.
10277: User information fields will not be overwritten with empty entries
10278: unless the field is included in the $candelete array reference.
10279: This array is included when a single user is modified via "Manage Users",
10280: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10281:
10282: =item *
10283:
1.286 matthew 10284: modifystudent
10285:
1.957 raeburn 10286: modify a student's enrollment and identification information.
1.286 matthew 10287: The course id is resolved based on the current users environment.
10288: This means the envoking user must be a course coordinator or otherwise
10289: associated with a course.
10290:
1.297 matthew 10291: This call is essentially a wrapper for lonnet::modifyuser and
10292: lonnet::modify_student_enrollment
1.286 matthew 10293:
10294: Inputs:
10295:
10296: =over 4
10297:
1.957 raeburn 10298: =item B<$udom> Student's loncapa domain
1.286 matthew 10299:
1.957 raeburn 10300: =item B<$uname> Student's loncapa login name
1.286 matthew 10301:
1.964 bisitz 10302: =item B<$uid> Student/Employee ID
1.286 matthew 10303:
1.957 raeburn 10304: =item B<$umode> Student's authentication mode
1.286 matthew 10305:
1.957 raeburn 10306: =item B<$upass> Student's password
1.286 matthew 10307:
1.957 raeburn 10308: =item B<$first> Student's first name
1.286 matthew 10309:
1.957 raeburn 10310: =item B<$middle> Student's middle name
1.286 matthew 10311:
1.957 raeburn 10312: =item B<$last> Student's last name
1.286 matthew 10313:
1.957 raeburn 10314: =item B<$gene> Student's generation
1.286 matthew 10315:
1.957 raeburn 10316: =item B<$usec> Student's section in course
1.286 matthew 10317:
10318: =item B<$end> Unix time of the roles expiration
10319:
10320: =item B<$start> Unix time of the roles start date
10321:
10322: =item B<$forceid> If defined, allow $uid to be changed
10323:
10324: =item B<$desiredhome> server to use as home server for student
10325:
1.957 raeburn 10326: =item B<$email> Student's permanent e-mail address
10327:
10328: =item B<$type> Type of enrollment (auto or manual)
10329:
1.963 raeburn 10330: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10331:
10332: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10333:
1.963 raeburn 10334: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10335:
1.963 raeburn 10336: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10337:
1.963 raeburn 10338: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10339:
1.286 matthew 10340: =back
1.297 matthew 10341:
10342: =item *
10343:
10344: modify_student_enrollment
10345:
10346: Change a students enrollment status in a class. The environment variable
10347: 'role.request.course' must be defined for this function to proceed.
10348:
10349: Inputs:
10350:
10351: =over 4
10352:
10353: =item $udom, students domain
10354:
10355: =item $uname, students name
10356:
10357: =item $uid, students user id
10358:
10359: =item $first, students first name
10360:
10361: =item $middle
10362:
10363: =item $last
10364:
10365: =item $gene
10366:
10367: =item $usec
10368:
10369: =item $end
10370:
10371: =item $start
10372:
1.957 raeburn 10373: =item $type
10374:
10375: =item $locktype
10376:
10377: =item $cid
10378:
10379: =item $selfenroll
10380:
10381: =item $context
10382:
1.297 matthew 10383: =back
10384:
1.191 harris41 10385:
10386: =item *
10387:
1.243 albertel 10388: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10389: custom role; give a custom role to a user for the level given by URL. Specify
10390: name and domain of role author, and role name
1.191 harris41 10391:
10392: =item *
10393:
1.243 albertel 10394: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10395:
10396: =item *
10397:
1.243 albertel 10398: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10399:
10400: =back
10401:
10402: =head2 Course Infomation
10403:
10404: =over 4
1.191 harris41 10405:
10406: =item *
10407:
1.631 albertel 10408: coursedescription($courseid) : returns a hash of information about the
10409: specified course id, including all environment settings for the
10410: course, the description of the course will be in the hash under the
10411: key 'description'
1.191 harris41 10412:
10413: =item *
10414:
1.624 albertel 10415: resdata($name,$domain,$type,@which) : request for current parameter
10416: setting for a specific $type, where $type is either 'course' or 'user',
10417: @what should be a list of parameters to ask about. This routine caches
10418: answers for 5 minutes.
1.243 albertel 10419:
1.877 foxr 10420: =item *
10421:
10422: get_courseresdata($courseid, $domain) : dump the entire course resource
10423: data base, returning a hash that is keyed by the resource name and has
10424: values that are the resource value. I believe that the timestamps and
10425: versions are also returned.
10426:
10427:
1.243 albertel 10428: =back
10429:
10430: =head2 Course Modification
10431:
10432: =over 4
1.191 harris41 10433:
10434: =item *
10435:
1.243 albertel 10436: writecoursepref($courseid,%prefs) : write preferences (environment
10437: database) for a course
1.191 harris41 10438:
10439: =item *
10440:
1.1011 raeburn 10441: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10442:
10443: =item *
10444:
1.1038 raeburn 10445: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10446:
10447: =back
10448:
10449: =head2 Resource Subroutines
10450:
10451: =over 4
1.191 harris41 10452:
10453: =item *
10454:
1.243 albertel 10455: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10456:
10457: =item *
10458:
1.243 albertel 10459: repcopy($filename) : subscribes to the requested file, and attempts to
10460: replicate from the owning library server, Might return
1.607 raeburn 10461: 'unavailable', 'not_found', 'forbidden', 'ok', or
10462: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10463: resource. Expects the local filesystem pathname
10464: (/home/httpd/html/res/....)
10465:
10466: =back
10467:
10468: =head2 Resource Information
10469:
10470: =over 4
1.191 harris41 10471:
10472: =item *
10473:
1.243 albertel 10474: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10475: a vairety of different possible values, $varname should be a request
10476: string, and the other parameters can be used to specify who and what
10477: one is asking about.
10478:
10479: Possible values for $varname are environment.lastname (or other item
10480: from the envirnment hash), user.name (or someother aspect about the
10481: user), resource.0.maxtries (or some other part and parameter of a
10482: resource)
1.204 albertel 10483:
10484: =item *
10485:
1.243 albertel 10486: directcondval($number) : get current value of a condition; reads from a state
10487: string
1.204 albertel 10488:
10489: =item *
10490:
1.243 albertel 10491: condval($condidx) : value of condition index based on state
1.204 albertel 10492:
10493: =item *
10494:
1.243 albertel 10495: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10496: resource's metadata, $what should be either a specific key, or either
10497: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10498: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10499:
10500: this function automatically caches all requests
1.191 harris41 10501:
10502: =item *
10503:
1.243 albertel 10504: metadata_query($query,$custom,$customshow) : make a metadata query against the
10505: network of library servers; returns file handle of where SQL and regex results
10506: will be stored for query
1.191 harris41 10507:
10508: =item *
10509:
1.243 albertel 10510: symbread($filename) : return symbolic list entry (filename argument optional);
10511: returns the data handle
1.191 harris41 10512:
10513: =item *
10514:
1.243 albertel 10515: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10516: a possible symb for the URL in $thisfn, and if is an encryypted
10517: resource that the user accessed using /enc/ returns a 1 on success, 0
10518: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10519: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10520:
1.191 harris41 10521:
10522: =item *
10523:
1.243 albertel 10524: symbclean($symb) : removes versions numbers from a symb, returns the
10525: cleaned symb
1.191 harris41 10526:
10527: =item *
10528:
1.243 albertel 10529: is_on_map($uri) : checks if the $uri is somewhere on the current
10530: course map, user must be in a course for it to work.
1.191 harris41 10531:
10532: =item *
10533:
1.243 albertel 10534: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10535:
10536: =item *
10537:
1.243 albertel 10538: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10539: a random seed, all arguments are optional, if they aren't sent it uses the
10540: environment to derive them. Note: if symb isn't sent and it can't get one
10541: from &symbread it will use the current time as its return value
1.191 harris41 10542:
10543: =item *
10544:
1.243 albertel 10545: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10546: unfakeable, receipt
1.191 harris41 10547:
10548: =item *
10549:
1.620 albertel 10550: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10551:
10552: =item *
10553:
1.243 albertel 10554: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10555:
10556: =item *
10557:
1.243 albertel 10558: 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 10559:
10560: =item *
10561:
1.243 albertel 10562: 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 10563:
10564: =item *
10565:
1.243 albertel 10566: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10567:
10568: =item *
10569:
1.243 albertel 10570: devalidate($symb) : devalidate temporary spreadsheet calculations,
10571: forcing spreadsheet to reevaluate the resource scores next time.
10572:
10573: =back
10574:
10575: =head2 Storing/Retreiving Data
10576:
10577: =over 4
1.191 harris41 10578:
10579: =item *
10580:
1.243 albertel 10581: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10582: for this url; hashref needs to be given and should be a \%hashname; the
10583: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10584: be derived from the env
1.191 harris41 10585:
10586: =item *
10587:
1.243 albertel 10588: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10589: uses critical subroutine
1.191 harris41 10590:
10591: =item *
10592:
1.243 albertel 10593: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10594: all args are optional
1.191 harris41 10595:
10596: =item *
10597:
1.717 albertel 10598: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10599: dumps the complete (or key matching regexp) namespace into a hash
10600: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10601: normally &store()ed into
10602:
10603: $range should be either an integer '100' (give me the first 100
10604: matching records)
10605: or be two integers sperated by a - with no spaces
10606: '30-50' (give me the 30th through the 50th matching
10607: records)
10608:
10609:
10610: =item *
10611:
10612: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10613: replaces a &store() version of data with a replacement set of data
10614: for a particular resource in a namespace passed in the $storehash hash
10615: reference
10616:
10617: =item *
10618:
1.243 albertel 10619: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10620: works very similar to store/cstore, but all data is stored in a
10621: temporary location and can be reset using tmpreset, $storehash should
10622: be a hash reference, returns nothing on success
1.191 harris41 10623:
10624: =item *
10625:
1.243 albertel 10626: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10627: similar to restore, but all data is stored in a temporary location and
10628: can be reset using tmpreset. Returns a hash of values on success,
10629: error string otherwise.
1.191 harris41 10630:
10631: =item *
10632:
1.243 albertel 10633: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10634: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 10635:
10636: =item *
10637:
1.243 albertel 10638: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10639: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 10640:
10641: =item *
10642:
1.243 albertel 10643: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10644: namesp ($udom and $uname are optional)
1.191 harris41 10645:
10646: =item *
10647:
1.702 albertel 10648: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 10649: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 10650: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 10651:
1.702 albertel 10652: $range should be either an integer '100' (give me the first 100
10653: matching records)
10654: or be two integers sperated by a - with no spaces
10655: '30-50' (give me the 30th through the 50th matching
10656: records)
1.449 matthew 10657: =item *
10658:
10659: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10660: $store can be a scalar, an array reference, or if the amount to be
10661: incremented is > 1, a hash reference.
10662:
10663: ($udom and $uname are optional)
1.191 harris41 10664:
10665: =item *
10666:
1.243 albertel 10667: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10668: ($udom and $uname are optional)
1.191 harris41 10669:
10670: =item *
10671:
1.243 albertel 10672: cput($namespace,$storehash,$udom,$uname) : critical put
10673: ($udom and $uname are optional)
1.191 harris41 10674:
10675: =item *
10676:
1.748 albertel 10677: newput($namespace,$storehash,$udom,$uname) :
10678:
10679: Attempts to store the items in the $storehash, but only if they don't
10680: currently exist, if this succeeds you can be certain that you have
10681: successfully created a new key value pair in the $namespace db.
10682:
10683:
10684: Args:
10685: $namespace: name of database to store values to
10686: $storehash: hashref to store to the db
10687: $udom: (optional) domain of user containing the db
10688: $uname: (optional) name of user caontaining the db
10689:
10690: Returns:
10691: 'ok' -> succeeded in storing all keys of $storehash
10692: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10693: least <key> already existed in the db (other
10694: requested keys may also already exist)
1.967 bisitz 10695: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 10696: 'con_lost' -> unable to contact request server
10697: 'refused' -> action was not allowed by remote machine
10698:
10699:
10700: =item *
10701:
1.243 albertel 10702: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10703: reference filled in from namesp (encrypts the return communication)
10704: ($udom and $uname are optional)
1.191 harris41 10705:
10706: =item *
10707:
1.243 albertel 10708: log($udom,$name,$home,$message) : write to permanent log for user; use
10709: critical subroutine
10710:
1.806 raeburn 10711: =item *
10712:
1.860 raeburn 10713: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10714: array reference filled in from namespace found in domain level on either
10715: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 10716:
10717: =item *
10718:
1.860 raeburn 10719: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10720: domain level either on specified domain server ($uhome) or primary domain
10721: server ($udom and $uhome are optional)
1.806 raeburn 10722:
1.943 raeburn 10723: =item *
10724:
10725: get_domain_defaults($target_domain) : returns hash with defaults for
10726: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10727: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10728: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10729: Values are retrieved from cache (if current), or from domain's configuration.db
10730: (if available), or lastly from values in lonTabs/dns_domain,tab,
10731: or lonTabs/domain.tab.
10732:
10733: %domdefaults = &get_auth_defaults($target_domain);
10734:
1.243 albertel 10735: =back
10736:
10737: =head2 Network Status Functions
10738:
10739: =over 4
1.191 harris41 10740:
10741: =item *
10742:
10743: dirlist($uri) : return directory list based on URI
10744:
10745: =item *
10746:
1.243 albertel 10747: spareserver() : find server with least workload from spare.tab
10748:
1.986 foxr 10749:
10750: =item *
10751:
10752: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10753: if there is no corresponding loncapa host.
10754:
1.243 albertel 10755: =back
10756:
1.986 foxr 10757:
1.243 albertel 10758: =head2 Apache Request
10759:
10760: =over 4
1.191 harris41 10761:
10762: =item *
10763:
1.243 albertel 10764: ssi($url,%hash) : server side include, does a complete request cycle on url to
10765: localhost, posts hash
10766:
10767: =back
10768:
10769: =head2 Data to String to Data
10770:
10771: =over 4
1.191 harris41 10772:
10773: =item *
10774:
1.243 albertel 10775: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10776: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 10777:
10778: =item *
10779:
1.243 albertel 10780: hashref2str($hashref) : convert a hashref into a string complete with
10781: escaping and '=' and '&' separators, supports elements that are
10782: arrayrefs and hashrefs
1.191 harris41 10783:
10784: =item *
10785:
1.243 albertel 10786: arrayref2str($arrayref) : convert an arrayref into a string complete
10787: with escaping and '&' separators, supports elements that are arrayrefs
10788: and hashrefs
1.191 harris41 10789:
10790: =item *
10791:
1.243 albertel 10792: str2hash($string) : convert string to hash using unescaping and
10793: splitting on '=' and '&', supports elements that are arrayrefs and
10794: hashrefs
1.191 harris41 10795:
10796: =item *
10797:
1.243 albertel 10798: str2array($string) : convert string to hash using unescaping and
10799: splitting on '&', supports elements that are arrayrefs and hashrefs
10800:
10801: =back
10802:
10803: =head2 Logging Routines
10804:
10805: =over 4
10806:
10807: These routines allow one to make log messages in the lonnet.log and
10808: lonnet.perm logfiles.
1.191 harris41 10809:
10810: =item *
10811:
1.243 albertel 10812: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 10813:
10814: =item *
10815:
1.243 albertel 10816: logthis() : append message to the normal lonnet.log file, it gets
10817: preiodically rolled over and deleted.
1.191 harris41 10818:
10819: =item *
10820:
1.243 albertel 10821: logperm() : append a permanent message to lonnet.perm.log, this log
10822: file never gets deleted by any automated portion of the system, only
10823: messages of critical importance should go in here.
10824:
10825: =back
10826:
10827: =head2 General File Helper Routines
10828:
10829: =over 4
1.191 harris41 10830:
10831: =item *
10832:
1.481 raeburn 10833: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10834: (a) files in /uploaded
10835: (i) If a local copy of the file exists -
10836: compares modification date of local copy with last-modified date for
10837: definitive version stored on home server for course. If local copy is
10838: stale, requests a new version from the home server and stores it.
10839: If the original has been removed from the home server, then local copy
10840: is unlinked.
10841: (ii) If local copy does not exist -
10842: requests the file from the home server and stores it.
10843:
10844: If $caller is 'uploadrep':
10845: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10846: for request for files originally uploaded via DOCS.
10847: - returns 'ok' if fresh local copy now available, -1 otherwise.
10848:
10849: Otherwise:
10850: This indicates a call from the content generation phase of the request.
10851: - returns the entire contents of the file or -1.
10852:
10853: (b) files in /res
10854: - returns the entire contents of a file or -1;
10855: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 10856:
1.712 albertel 10857:
10858: =item *
10859:
10860: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10861: reference
10862:
10863: returns either a stat() list of data about the file or an empty list
10864: if the file doesn't exist or couldn't find out about it (connection
10865: problems or user unknown)
10866:
1.191 harris41 10867: =item *
10868:
1.243 albertel 10869: filelocation($dir,$file) : returns file system location of a file
10870: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10871: directory that relative $file lookups are to looked in ($dir of /a/dir
10872: and a file of ../bob will become /a/bob)
1.191 harris41 10873:
10874: =item *
10875:
10876: hreflocation($dir,$file) : returns file system location or a URL; same as
10877: filelocation except for hrefs
10878:
10879: =item *
10880:
10881: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10882:
1.243 albertel 10883: =back
10884:
1.608 albertel 10885: =head2 Usererfile file routines (/uploaded*)
10886:
10887: =over 4
10888:
10889: =item *
10890:
10891: userfileupload(): main rotine for putting a file in a user or course's
10892: filespace, arguments are,
10893:
1.620 albertel 10894: formname - required - this is the name of the element in $env where the
1.608 albertel 10895: filename, and the contents of the file to create/modifed exist
1.620 albertel 10896: the filename is in $env{'form.'.$formname.'.filename'} and the
10897: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10898: coursedoc - if true, store the file in the course of the active role
10899: of the current user
10900: subdir - required - subdirectory to put the file in under ../userfiles/
10901: if undefined, it will be placed in "unknown"
10902:
10903: (This routine calls clean_filename() to remove any dangerous
10904: characters from the filename, and then calls finuserfileupload() to
10905: complete the transaction)
10906:
10907: returns either the url of the uploaded file (/uploaded/....) if successful
10908: and /adm/notfound.html if unsuccessful
10909:
10910: =item *
10911:
10912: clean_filename(): routine for cleaing a filename up for storage in
10913: userfile space, argument is:
10914:
10915: filename - proposed filename
10916:
10917: returns: the new clean filename
10918:
10919: =item *
10920:
10921: finishuserfileupload(): routine that creaes and sends the file to
10922: userspace, probably shouldn't be called directly
10923:
10924: docuname: username or courseid of destination for the file
10925: docudom: domain of user/course of destination for the file
10926: formname: same as for userfileupload()
10927: fname: filename (inculding subdirectories) for the file
10928:
10929: returns either the url of the uploaded file (/uploaded/....) if successful
10930: and /adm/notfound.html if unsuccessful
10931:
10932: =item *
10933:
10934: renameuserfile(): renames an existing userfile to a new name
10935:
10936: Args:
10937: docuname: username or courseid of destination for the file
10938: docudom: domain of user/course of destination for the file
10939: old: current file name (including any subdirs under userfiles)
10940: new: desired file name (including any subdirs under userfiles)
10941:
10942: =item *
10943:
10944: mkdiruserfile(): creates a directory is a userfiles dir
10945:
10946: Args:
10947: docuname: username or courseid of destination for the file
10948: docudom: domain of user/course of destination for the file
10949: dir: dir to create (including any subdirs under userfiles)
10950:
10951: =item *
10952:
10953: removeuserfile(): removes a file that exists in userfiles
10954:
10955: Args:
10956: docuname: username or courseid of destination for the file
10957: docudom: domain of user/course of destination for the file
10958: fname: filname to delete (including any subdirs under userfiles)
10959:
10960: =item *
10961:
10962: removeuploadedurl(): convience function for removeuserfile()
10963:
10964: Args:
10965: url: a full /uploaded/... url to delete
10966:
1.747 albertel 10967: =item *
10968:
10969: get_portfile_permissions():
10970: Args:
10971: domain: domain of user or course contain the portfolio files
10972: user: name of user or num of course contain the portfolio files
10973: Returns:
10974: hashref of a dump of the proper file_permissions.db
10975:
10976:
10977: =item *
10978:
10979: get_access_controls():
10980:
10981: Args:
10982: current_permissions: the hash ref returned from get_portfile_permissions()
10983: group: (optional) the group you want the files associated with
10984: file: (optional) the file you want access info on
10985:
10986: Returns:
1.749 raeburn 10987: a hash (keys are file names) of hashes containing
10988: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10989: values are XML containing access control settings (see below)
1.747 albertel 10990:
10991: Internal notes:
10992:
1.749 raeburn 10993: access controls are stored in file_permissions.db as key=value pairs.
10994: key -> path to file/file_name\0uniqueID:scope_end_start
10995: where scope -> public,guest,course,group,domains or users.
10996: end -> UNIX time for end of access (0 -> no end date)
10997: start -> UNIX time for start of access
10998:
10999: value -> XML description of access control
11000: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11001: <start></start>
11002: <end></end>
11003:
11004: <password></password> for scope type = guest
11005:
11006: <domain></domain> for scope type = course or group
11007: <number></number>
11008: <roles id="">
11009: <role></role>
11010: <access></access>
11011: <section></section>
11012: <group></group>
11013: </roles>
11014:
11015: <dom></dom> for scope type = domains
11016:
11017: <users> for scope type = users
11018: <user>
11019: <uname></uname>
11020: <udom></udom>
11021: </user>
11022: </users>
11023: </scope>
11024:
11025: Access data is also aggregated for each file in an additional key=value pair:
11026: key -> path to file/file_name\0accesscontrol
11027: value -> reference to hash
11028: hash contains key = value pairs
11029: where key = uniqueID:scope_end_start
11030: value = UNIX time record was last updated
11031:
11032: Used to improve speed of look-ups of access controls for each file.
11033:
11034: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11035:
11036: modify_access_controls():
11037:
11038: Modifies access controls for a portfolio file
11039: Args
11040: 1. file name
11041: 2. reference to hash of required changes,
11042: 3. domain
11043: 4. username
11044: where domain,username are the domain of the portfolio owner
11045: (either a user or a course)
11046:
11047: Returns:
11048: 1. result of additions or updates ('ok' or 'error', with error message).
11049: 2. result of deletions ('ok' or 'error', with error message).
11050: 3. reference to hash of any new or updated access controls.
11051: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11052: key = integer (inbound ID)
11053: value = uniqueID
1.747 albertel 11054:
1.608 albertel 11055: =back
11056:
1.243 albertel 11057: =head2 HTTP Helper Routines
11058:
11059: =over 4
11060:
1.191 harris41 11061: =item *
11062:
11063: escape() : unpack non-word characters into CGI-compatible hex codes
11064:
11065: =item *
11066:
11067: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11068:
1.243 albertel 11069: =back
11070:
11071: =head1 PRIVATE SUBROUTINES
11072:
11073: =head2 Underlying communication routines (Shouldn't call)
11074:
11075: =over 4
11076:
11077: =item *
11078:
11079: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11080:
11081: =item *
11082:
11083: reply() : uses subreply to send a message to remote machine, logs all failures
11084:
11085: =item *
11086:
11087: critical() : passes a critical message to another server; if cannot
11088: get through then place message in connection buffer directory and
11089: returns con_delayed, if incapable of saving message, returns
11090: con_failed
11091:
11092: =item *
11093:
11094: reconlonc() : tries to reconnect lonc client processes.
11095:
11096: =back
11097:
11098: =head2 Resource Access Logging
11099:
11100: =over 4
11101:
11102: =item *
11103:
11104: flushcourselogs() : flush (save) buffer logs and access logs
11105:
11106: =item *
11107:
11108: courselog($what) : save message for course in hash
11109:
11110: =item *
11111:
11112: courseacclog($what) : save message for course using &courselog(). Perform
11113: special processing for specific resource types (problems, exams, quizzes, etc).
11114:
1.191 harris41 11115: =item *
11116:
11117: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11118: as a PerlChildExitHandler
1.243 albertel 11119:
11120: =back
11121:
11122: =head2 Other
11123:
11124: =over 4
11125:
11126: =item *
11127:
11128: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11129:
11130: =back
11131:
11132: =cut
1.877 foxr 11133:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>