Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1068
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1068 ! www 4: # $Id: lonnet.pm,v 1.1067 2010/06/03 00:07:17 www Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968 raeburn 79: $_64bit %env %protocol);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.676 albertel 98:
1.195 www 99: my $readit;
1.550 foxr 100: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 101:
1.619 albertel 102: require Exporter;
103:
104: our @ISA = qw (Exporter);
105: our @EXPORT = qw(%env);
106:
1.449 matthew 107:
1.1 albertel 108: # --------------------------------------------------------------------- Logging
1.729 www 109: {
110: my $logid;
111: sub instructor_log {
1.957 raeburn 112: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
113: if (($cnum eq '') || ($cdom eq '')) {
114: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
115: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
116: }
1.729 www 117: $logid++;
1.957 raeburn 118: my $now = time();
119: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 120: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 121: { $id => {
122: 'exe_uname' => $env{'user.name'},
123: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 124: 'exe_time' => $now,
1.730 www 125: 'exe_ip' => $ENV{'REMOTE_ADDR'},
126: 'delflag' => $delflag,
127: 'logentry' => $storehash,
128: 'uname' => $uname,
129: 'udom' => $udom,
130: }
1.957 raeburn 131: },$cdom,$cnum);
1.729 www 132: }
133: }
1.1 albertel 134:
1.163 harris41 135: sub logtouch {
136: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 137: unless (-e "$execdir/logs/lonnet.log") {
138: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 139: close $fh;
140: }
141: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
142: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
143: }
144:
1.1 albertel 145: sub logthis {
146: my $message=shift;
147: my $execdir=$perlvar{'lonDaemons'};
148: my $now=time;
149: my $local=localtime($now);
1.448 albertel 150: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 151: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
152: print $fh $logstring;
1.448 albertel 153: close($fh);
154: }
1.1 albertel 155: return 1;
156: }
157:
158: sub logperm {
159: my $message=shift;
160: my $execdir=$perlvar{'lonDaemons'};
161: my $now=time;
162: my $local=localtime($now);
1.448 albertel 163: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
164: print $fh "$now:$message:$local\n";
165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
1.850 albertel 170: sub create_connection {
1.853 albertel 171: my ($hostname,$lonid) = @_;
1.851 albertel 172: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 173: Type => SOCK_STREAM,
174: Timeout => 10);
175: return 0 if (!$client);
1.890 albertel 176: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 177: my $result = <$client>;
178: chomp($result);
179: return 1 if ($result eq 'done');
180: return 0;
181: }
182:
1.983 raeburn 183: sub get_server_timezone {
184: my ($cnum,$cdom) = @_;
185: my $home=&homeserver($cnum,$cdom);
186: if ($home ne 'no_host') {
187: my $cachetime = 24*3600;
188: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
189: if (defined($cached)) {
190: return $timezone;
191: } else {
192: my $timezone = &reply('servertimezone',$home);
193: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
194: }
195: }
196: }
1.850 albertel 197:
1.993 raeburn 198: sub get_server_loncaparev {
199: my ($dom,$lonhost) = @_;
200: if (defined($lonhost)) {
201: if (!defined(&hostname($lonhost))) {
202: undef($lonhost);
203: }
204: }
205: if (!defined($lonhost)) {
206: if (defined(&domain($dom,'primary'))) {
207: $lonhost=&domain($dom,'primary');
208: if ($lonhost eq 'no_host') {
209: undef($lonhost);
210: }
211: }
212: }
213: if (defined($lonhost)) {
214: my $cachetime = 24*3600;
215: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
216: if (defined($cached)) {
217: return $loncaparev;
218: } else {
219: my $loncaparev = &reply('serverloncaparev',$lonhost);
220: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
221: }
222: }
223: }
224:
1.1 albertel 225: # -------------------------------------------------- Non-critical communication
226: sub subreply {
227: my ($cmd,$server)=@_;
1.838 albertel 228: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 229: #
230: # With loncnew process trimming, there's a timing hole between lonc server
231: # process exit and the master server picking up the listen on the AF_UNIX
232: # socket. In that time interval, a lock file will exist:
233:
234: my $lockfile=$peerfile.".lock";
235: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
236: sleep(1);
237: }
238: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 239: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 240: #
1.550 foxr 241: # We'll give the connection a few tries before abandoning it. If
242: # connection is not possible, we'll con_lost back to the client.
243: #
244: my $client;
245: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
246: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
247: Type => SOCK_STREAM,
248: Timeout => 10);
1.869 albertel 249: if ($client) {
1.550 foxr 250: last; # Connected!
1.850 albertel 251: } else {
1.853 albertel 252: &create_connection(&hostname($server),$server);
1.550 foxr 253: }
1.850 albertel 254: sleep(1); # Try again later if failed connection.
1.550 foxr 255: }
256: my $answer;
257: if ($client) {
1.704 albertel 258: print $client "sethost:$server:$cmd\n";
1.550 foxr 259: $answer=<$client>;
260: if (!$answer) { $answer="con_lost"; }
261: chomp($answer);
262: } else {
263: $answer = 'con_lost'; # Failed connection.
264: }
1.1 albertel 265: return $answer;
266: }
267:
268: sub reply {
269: my ($cmd,$server)=@_;
1.838 albertel 270: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 271: my $answer=subreply($cmd,$server);
1.65 www 272: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 273: &logthis("<font color=\"blue\">WARNING:".
1.12 www 274: " $cmd to $server returned $answer</font>");
275: }
1.1 albertel 276: return $answer;
277: }
278:
279: # ----------------------------------------------------------- Send USR1 to lonc
280:
281: sub reconlonc {
1.891 albertel 282: my ($lonid) = @_;
283: my $hostname = &hostname($lonid);
284: if ($lonid) {
285: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
286: if ($hostname && -e $peerfile) {
287: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
288: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
289: Type => SOCK_STREAM,
290: Timeout => 10);
291: if ($client) {
292: print $client ("reset_retries\n");
293: my $answer=<$client>;
294: #reset just this one.
295: }
296: }
297: return;
298: }
299:
1.836 www 300: &logthis("Trying to reconnect lonc");
1.1 albertel 301: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 302: if (open(my $fh,"<$loncfile")) {
1.1 albertel 303: my $loncpid=<$fh>;
304: chomp($loncpid);
305: if (kill 0 => $loncpid) {
306: &logthis("lonc at pid $loncpid responding, sending USR1");
307: kill USR1 => $loncpid;
308: sleep 1;
1.836 www 309: } else {
1.12 www 310: &logthis(
1.672 albertel 311: "<font color=\"blue\">WARNING:".
1.12 www 312: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 313: }
314: } else {
1.836 www 315: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 316: }
317: }
318:
319: # ------------------------------------------------------ Critical communication
1.12 www 320:
1.1 albertel 321: sub critical {
322: my ($cmd,$server)=@_;
1.838 albertel 323: unless (&hostname($server)) {
1.672 albertel 324: &logthis("<font color=\"blue\">WARNING:".
1.89 www 325: " Critical message to unknown server ($server)</font>");
326: return 'no_such_host';
327: }
1.1 albertel 328: my $answer=reply($cmd,$server);
329: if ($answer eq 'con_lost') {
330: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 331: my $answer=reply($cmd,$server);
1.1 albertel 332: if ($answer eq 'con_lost') {
333: my $now=time;
334: my $middlename=$cmd;
1.5 www 335: $middlename=substr($middlename,0,16);
1.1 albertel 336: $middlename=~s/\W//g;
337: my $dfilename=
1.305 www 338: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
339: $dumpcount++;
1.1 albertel 340: {
1.448 albertel 341: my $dfh;
342: if (open($dfh,">$dfilename")) {
343: print $dfh "$cmd\n";
344: close($dfh);
345: }
1.1 albertel 346: }
347: sleep 2;
348: my $wcmd='';
349: {
1.448 albertel 350: my $dfh;
351: if (open($dfh,"<$dfilename")) {
352: $wcmd=<$dfh>;
353: close($dfh);
354: }
1.1 albertel 355: }
356: chomp($wcmd);
1.7 www 357: if ($wcmd eq $cmd) {
1.672 albertel 358: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 359: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 360: &logperm("D:$server:$cmd");
361: return 'con_delayed';
362: } else {
1.672 albertel 363: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 364: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 365: &logperm("F:$server:$cmd");
366: return 'con_failed';
367: }
368: }
369: }
370: return $answer;
1.405 albertel 371: }
372:
1.755 albertel 373: # ------------------------------------------- check if return value is an error
374:
375: sub error {
376: my ($result) = @_;
1.756 albertel 377: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 378: if ($2 == 2) { return undef; }
379: return $1;
380: }
381: return undef;
382: }
383:
1.783 albertel 384: sub convert_and_load_session_env {
385: my ($lonidsdir,$handle)=@_;
386: my @profile;
387: {
1.917 albertel 388: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
389: if (!$opened) {
1.915 albertel 390: return 0;
391: }
1.783 albertel 392: flock($idf,LOCK_SH);
393: @profile=<$idf>;
394: close($idf);
395: }
396: my %temp_env;
397: foreach my $line (@profile) {
1.786 albertel 398: if ($line !~ m/=/) {
399: return 0;
400: }
1.783 albertel 401: chomp($line);
402: my ($envname,$envvalue)=split(/=/,$line,2);
403: $temp_env{&unescape($envname)} = &unescape($envvalue);
404: }
405: unlink("$lonidsdir/$handle.id");
406: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
407: 0640)) {
408: %disk_env = %temp_env;
409: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
410: untie(%disk_env);
411: }
1.786 albertel 412: return 1;
1.783 albertel 413: }
414:
1.374 www 415: # ------------------------------------------- Transfer profile into environment
1.780 albertel 416: my $env_loaded;
417: sub transfer_profile_to_env {
1.788 albertel 418: my ($lonidsdir,$handle,$force_transfer) = @_;
419: if (!$force_transfer && $env_loaded) { return; }
1.374 www 420:
1.720 albertel 421: if (!defined($lonidsdir)) {
422: $lonidsdir = $perlvar{'lonIDsDir'};
423: }
424: if (!defined($handle)) {
425: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
426: }
427:
1.786 albertel 428: my $convert;
429: {
1.917 albertel 430: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
431: if (!$opened) {
1.915 albertel 432: return;
433: }
1.786 albertel 434: flock($idf,LOCK_SH);
435: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
436: &GDBM_READER(),0640)) {
437: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
438: untie(%disk_env);
439: } else {
440: $convert = 1;
441: }
442: }
443: if ($convert) {
444: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
445: &logthis("Failed to load session, or convert session.");
446: }
1.374 www 447: }
1.783 albertel 448:
1.786 albertel 449: my %remove;
1.783 albertel 450: while ( my $envname = each(%env) ) {
1.433 matthew 451: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
452: if ($time < time-300) {
1.783 albertel 453: $remove{$key}++;
1.433 matthew 454: }
455: }
456: }
1.783 albertel 457:
1.619 albertel 458: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 459: $env_loaded=1;
1.783 albertel 460: foreach my $expired_key (keys(%remove)) {
1.433 matthew 461: &delenv($expired_key);
1.374 www 462: }
1.1 albertel 463: }
464:
1.916 albertel 465: # ---------------------------------------------------- Check for valid session
466: sub check_for_valid_session {
467: my ($r) = @_;
468: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
469: my $lonid=$cookies{'lonID'};
470: return undef if (!$lonid);
471:
472: my $handle=&LONCAPA::clean_handle($lonid->value);
473: my $lonidsdir=$r->dir_config('lonIDsDir');
474: return undef if (!-e "$lonidsdir/$handle.id");
475:
1.917 albertel 476: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
477: return undef if (!$opened);
1.916 albertel 478:
479: flock($idf,LOCK_SH);
480: my %disk_env;
481: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
482: &GDBM_READER(),0640)) {
483: return undef;
484: }
485:
486: if (!defined($disk_env{'user.name'})
487: || !defined($disk_env{'user.domain'})) {
488: return undef;
489: }
490: return $handle;
491: }
492:
1.830 albertel 493: sub timed_flock {
494: my ($file,$lock_type) = @_;
495: my $failed=0;
496: eval {
497: local $SIG{__DIE__}='DEFAULT';
498: local $SIG{ALRM}=sub {
499: $failed=1;
500: die("failed lock");
501: };
502: alarm(13);
503: flock($file,$lock_type);
504: alarm(0);
505: };
506: if ($failed) {
507: return undef;
508: } else {
509: return 1;
510: }
511: }
512:
1.5 www 513: # ---------------------------------------------------------- Append Environment
514:
515: sub appenv {
1.949 raeburn 516: my ($newenv,$roles) = @_;
517: if (ref($newenv) eq 'HASH') {
518: foreach my $key (keys(%{$newenv})) {
519: my $refused = 0;
520: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
521: $refused = 1;
522: if (ref($roles) eq 'ARRAY') {
523: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
524: if (grep(/^\Q$role\E$/,@{$roles})) {
525: $refused = 0;
526: }
527: }
528: }
529: if ($refused) {
530: &logthis("<font color=\"blue\">WARNING: ".
531: "Attempt to modify environment ".$key." to ".$newenv->{$key}
532: .'</font>');
533: delete($newenv->{$key});
534: } else {
535: $env{$key}=$newenv->{$key};
536: }
537: }
538: my $opened = open(my $env_file,'+<',$env{'user.environment'});
539: if ($opened
540: && &timed_flock($env_file,LOCK_EX)
541: &&
542: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
543: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
544: while (my ($key,$value) = each(%{$newenv})) {
545: $disk_env{$key} = $value;
546: }
547: untie(%disk_env);
1.35 www 548: }
1.191 harris41 549: }
1.56 www 550: return 'ok';
551: }
552: # ----------------------------------------------------- Delete from Environment
553:
554: sub delenv {
1.987 raeburn 555: my ($delthis,$regexp) = @_;
1.56 www 556: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 557: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 558: "Attempt to delete from environment ".$delthis);
559: return 'error';
560: }
1.917 albertel 561: my $opened = open(my $env_file,'+<',$env{'user.environment'});
562: if ($opened
1.915 albertel 563: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 564: &&
565: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
566: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 567: foreach my $key (keys(%disk_env)) {
1.987 raeburn 568: if ($regexp) {
569: if ($key=~/^$delthis/) {
570: delete($env{$key});
571: delete($disk_env{$key});
572: }
573: } else {
574: if ($key=~/^\Q$delthis\E/) {
575: delete($env{$key});
576: delete($disk_env{$key});
577: }
578: }
1.448 albertel 579: }
1.783 albertel 580: untie(%disk_env);
1.5 www 581: }
582: return 'ok';
1.369 albertel 583: }
584:
1.790 albertel 585: sub get_env_multiple {
586: my ($name) = @_;
587: my @values;
588: if (defined($env{$name})) {
589: # exists is it an array
590: if (ref($env{$name})) {
591: @values=@{ $env{$name} };
592: } else {
593: $values[0]=$env{$name};
594: }
595: }
596: return(@values);
597: }
598:
1.958 www 599: # ------------------------------------------------------------------- Locking
600:
601: sub set_lock {
602: my ($text)=@_;
603: $locknum++;
604: my $id=$$.'-'.$locknum;
605: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
606: 'session.lock.'.$id => $text});
607: return $id;
608: }
609:
610: sub get_locks {
611: my $num=0;
612: my %texts=();
613: foreach my $lock (split(/\,/,$env{'session.locks'})) {
614: if ($lock=~/\w/) {
615: $num++;
616: $texts{$lock}=$env{'session.lock.'.$lock};
617: }
618: }
619: return ($num,%texts);
620: }
621:
622: sub remove_lock {
623: my ($id)=@_;
624: my $newlocks='';
625: foreach my $lock (split(/\,/,$env{'session.locks'})) {
626: if (($lock=~/\w/) && ($lock ne $id)) {
627: $newlocks.=','.$lock;
628: }
629: }
630: &appenv({'session.locks' => $newlocks});
631: &delenv('session.lock.'.$id);
632: }
633:
634: sub remove_all_locks {
635: my $activelocks=$env{'session.locks'};
636: foreach my $lock (split(/\,/,$env{'session.locks'})) {
637: if ($lock=~/\w/) {
638: &remove_lock($lock);
639: }
640: }
641: }
642:
643:
1.369 albertel 644: # ------------------------------------------ Find out current server userload
645: sub userload {
646: my $numusers=0;
647: {
648: opendir(LONIDS,$perlvar{'lonIDsDir'});
649: my $filename;
650: my $curtime=time;
651: while ($filename=readdir(LONIDS)) {
1.925 albertel 652: next if ($filename eq '.' || $filename eq '..');
653: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 654: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 655: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 656: }
657: closedir(LONIDS);
658: }
659: my $userloadpercent=0;
660: my $maxuserload=$perlvar{'lonUserLoadLim'};
661: if ($maxuserload) {
1.371 albertel 662: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 663: }
1.372 albertel 664: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 665: return $userloadpercent;
1.283 www 666: }
667:
1.1 albertel 668: # ------------------------------ Find server with least workload from spare.tab
1.11 www 669:
1.1 albertel 670: sub spareserver {
1.670 albertel 671: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 672: my $spare_server;
1.370 albertel 673: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 674: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
675: : $userloadpercent;
676:
677: foreach my $try_server (@{ $spareid{'primary'} }) {
678: ($spare_server, $lowest_load) =
679: &compare_server_load($try_server, $spare_server, $lowest_load);
680: }
681:
682: my $found_server = ($spare_server ne '' && $lowest_load < 100);
683:
684: if (!$found_server) {
685: foreach my $try_server (@{ $spareid{'default'} }) {
686: ($spare_server, $lowest_load) =
687: &compare_server_load($try_server, $spare_server, $lowest_load);
688: }
689: }
690:
691: if (!$want_server_name) {
1.968 raeburn 692: my $protocol = 'http';
693: if ($protocol{$spare_server} eq 'https') {
694: $protocol = $protocol{$spare_server};
695: }
1.1001 raeburn 696: if (defined($spare_server)) {
697: my $hostname = &hostname($spare_server);
698: if (defined($hostname)) {
699: $spare_server = $protocol.'://'.$hostname;
700: }
701: }
1.784 albertel 702: }
703: return $spare_server;
704: }
705:
706: sub compare_server_load {
707: my ($try_server, $spare_server, $lowest_load) = @_;
708:
709: my $loadans = &reply('load', $try_server);
710: my $userloadans = &reply('userload',$try_server);
711:
712: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
713: next; #didn't get a number from the server
714: }
715:
716: my $load;
717: if ($loadans =~ /\d/) {
718: if ($userloadans =~ /\d/) {
719: #both are numbers, pick the bigger one
720: $load = ($loadans > $userloadans) ? $loadans
721: : $userloadans;
1.411 albertel 722: } else {
1.784 albertel 723: $load = $loadans;
1.411 albertel 724: }
1.784 albertel 725: } else {
726: $load = $userloadans;
727: }
728:
729: if (($load =~ /\d/) && ($load < $lowest_load)) {
730: $spare_server = $try_server;
731: $lowest_load = $load;
1.370 albertel 732: }
1.784 albertel 733: return ($spare_server,$lowest_load);
1.202 matthew 734: }
1.914 albertel 735:
736: # --------------------------- ask offload servers if user already has a session
737: sub find_existing_session {
738: my ($udom,$uname) = @_;
739: foreach my $try_server (@{ $spareid{'primary'} },
740: @{ $spareid{'default'} }) {
741: return $try_server if (&has_user_session($try_server, $udom, $uname));
742: }
743: return;
744: }
745:
746: # -------------------------------- ask if server already has a session for user
747: sub has_user_session {
748: my ($lonid,$udom,$uname) = @_;
749: my $result = &reply(join(':','userhassession',
750: map {&escape($_)} ($udom,$uname)),$lonid);
751: return 1 if ($result eq 'ok');
752:
753: return 0;
754: }
755:
1.202 matthew 756: # --------------------------------------------- Try to change a user's password
757:
758: sub changepass {
1.799 raeburn 759: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 760: $currentpass = &escape($currentpass);
761: $newpass = &escape($newpass);
1.1030 raeburn 762: my $lonhost = $perlvar{'lonHostID'};
763: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 764: $server);
765: if (! $answer) {
766: &logthis("No reply on password change request to $server ".
767: "by $uname in domain $udom.");
768: } elsif ($answer =~ "^ok") {
769: &logthis("$uname in $udom successfully changed their password ".
770: "on $server.");
771: } elsif ($answer =~ "^pwchange_failure") {
772: &logthis("$uname in $udom was unable to change their password ".
773: "on $server. The action was blocked by either lcpasswd ".
774: "or pwchange");
775: } elsif ($answer =~ "^non_authorized") {
776: &logthis("$uname in $udom did not get their password correct when ".
777: "attempting to change it on $server.");
778: } elsif ($answer =~ "^auth_mode_error") {
779: &logthis("$uname in $udom attempted to change their password despite ".
780: "not being locally or internally authenticated on $server.");
781: } elsif ($answer =~ "^unknown_user") {
782: &logthis("$uname in $udom attempted to change their password ".
783: "on $server but were unable to because $server is not ".
784: "their home server.");
785: } elsif ($answer =~ "^refused") {
786: &logthis("$server refused to change $uname in $udom password because ".
787: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 788: } elsif ($answer =~ "invalid_client") {
789: &logthis("$server refused to change $uname in $udom password because ".
790: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 791: }
792: return $answer;
1.1 albertel 793: }
794:
1.169 harris41 795: # ----------------------- Try to determine user's current authentication scheme
796:
797: sub queryauthenticate {
798: my ($uname,$udom)=@_;
1.456 albertel 799: my $uhome=&homeserver($uname,$udom);
800: if (!$uhome) {
801: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
802: return 'no_host';
803: }
804: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
805: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
806: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 807: }
1.456 albertel 808: return $answer;
1.169 harris41 809: }
810:
1.1 albertel 811: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 812:
1.1 albertel 813: sub authenticate {
1.952 raeburn 814: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 815: $upass=&escape($upass);
816: $uname= &LONCAPA::clean_username($uname);
1.836 www 817: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 818: my $newhome;
1.836 www 819: if ((!$uhome) || ($uhome eq 'no_host')) {
820: # Maybe the machine was offline and only re-appeared again recently?
821: &reconlonc();
822: # One more
1.952 raeburn 823: $uhome=&homeserver($uname,$udom,1);
824: if (($uhome eq 'no_host') && $checkdefauth) {
825: if (defined(&domain($udom,'primary'))) {
826: $newhome=&domain($udom,'primary');
827: }
828: if ($newhome ne '') {
829: $uhome = $newhome;
830: }
831: }
1.836 www 832: if ((!$uhome) || ($uhome eq 'no_host')) {
833: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 834: return 'no_host';
835: }
1.1 albertel 836: }
1.952 raeburn 837: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 838: if ($answer eq 'authorized') {
1.952 raeburn 839: if ($newhome) {
840: &logthis("User $uname at $udom authorized by $uhome, but needs account");
841: return 'no_account_on_host';
842: } else {
843: &logthis("User $uname at $udom authorized by $uhome");
844: return $uhome;
845: }
1.471 albertel 846: }
847: if ($answer eq 'non_authorized') {
848: &logthis("User $uname at $udom rejected by $uhome");
849: return 'no_host';
1.9 www 850: }
1.471 albertel 851: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 852: return 'no_host';
853: }
854:
855: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 856:
1.599 albertel 857: my %homecache;
1.1 albertel 858: sub homeserver {
1.230 stredwic 859: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 860: my $index="$uname:$udom";
1.426 albertel 861:
1.599 albertel 862: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 863:
864: my %servers = &get_servers($udom,'library');
865: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 866: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 867: exists($badServerCache{$tryserver}));
1.841 albertel 868:
869: my $answer=reply("home:$udom:$uname",$tryserver);
870: if ($answer eq 'found') {
871: delete($badServerCache{$tryserver});
872: return $homecache{$index}=$tryserver;
873: } elsif ($answer eq 'no_host') {
874: $badServerCache{$tryserver}=1;
875: }
1.1 albertel 876: }
877: return 'no_host';
1.70 www 878: }
879:
880: # ------------------------------------- Find the usernames behind a list of IDs
881:
882: sub idget {
883: my ($udom,@ids)=@_;
884: my %returnhash=();
885:
1.841 albertel 886: my %servers = &get_servers($udom,'library');
887: foreach my $tryserver (keys(%servers)) {
888: my $idlist=join('&',@ids);
889: $idlist=~tr/A-Z/a-z/;
890: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
891: my @answer=();
892: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
893: @answer=split(/\&/,$reply);
894: } ;
895: my $i;
896: for ($i=0;$i<=$#ids;$i++) {
897: if ($answer[$i]) {
898: $returnhash{$ids[$i]}=$answer[$i];
899: }
900: }
901: }
1.70 www 902: return %returnhash;
903: }
904:
905: # ------------------------------------- Find the IDs behind a list of usernames
906:
907: sub idrget {
908: my ($udom,@unames)=@_;
909: my %returnhash=();
1.800 albertel 910: foreach my $uname (@unames) {
911: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 912: }
1.70 www 913: return %returnhash;
914: }
915:
916: # ------------------------------- Store away a list of names and associated IDs
917:
918: sub idput {
919: my ($udom,%ids)=@_;
920: my %servers=();
1.800 albertel 921: foreach my $uname (keys(%ids)) {
922: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
923: my $uhom=&homeserver($uname,$udom);
1.70 www 924: if ($uhom ne 'no_host') {
1.800 albertel 925: my $id=&escape($ids{$uname});
1.70 www 926: $id=~tr/A-Z/a-z/;
1.800 albertel 927: my $esc_unam=&escape($uname);
1.70 www 928: if ($servers{$uhom}) {
1.800 albertel 929: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 930: } else {
1.800 albertel 931: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 932: }
933: }
1.191 harris41 934: }
1.800 albertel 935: foreach my $server (keys(%servers)) {
936: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 937: }
1.344 www 938: }
939:
1.1023 raeburn 940: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 941: sub dump_dom {
1.1023 raeburn 942: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 943: if (!$udom) {
944: $udom=$env{'user.domain'};
945: }
946: my %returnhash;
1.1023 raeburn 947: if ($udom) {
948: my $uname = &get_domainconfiguser($udom);
949: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 950: }
951: return %returnhash;
952: }
953:
1.1023 raeburn 954: # ------------------------------------------ get items from domain db files
1.806 raeburn 955:
956: sub get_dom {
1.860 raeburn 957: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 958: my $items='';
959: foreach my $item (@$storearr) {
960: $items.=&escape($item).'&';
961: }
962: $items=~s/\&$//;
1.860 raeburn 963: if (!$udom) {
964: $udom=$env{'user.domain'};
965: if (defined(&domain($udom,'primary'))) {
966: $uhome=&domain($udom,'primary');
967: } else {
1.874 albertel 968: undef($uhome);
1.860 raeburn 969: }
970: } else {
971: if (!$uhome) {
972: if (defined(&domain($udom,'primary'))) {
973: $uhome=&domain($udom,'primary');
974: }
975: }
976: }
977: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 978: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 979: my %returnhash;
1.875 albertel 980: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 981: return %returnhash;
982: }
1.806 raeburn 983: my @pairs=split(/\&/,$rep);
984: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
985: return @pairs;
986: }
987: my $i=0;
988: foreach my $item (@$storearr) {
989: $returnhash{$item}=&thaw_unescape($pairs[$i]);
990: $i++;
991: }
992: return %returnhash;
993: } else {
1.880 banghart 994: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 995: }
996: }
997:
998: # -------------------------------------------- put items in domain db files
999:
1000: sub put_dom {
1.860 raeburn 1001: my ($namespace,$storehash,$udom,$uhome)=@_;
1002: if (!$udom) {
1003: $udom=$env{'user.domain'};
1004: if (defined(&domain($udom,'primary'))) {
1005: $uhome=&domain($udom,'primary');
1006: } else {
1.874 albertel 1007: undef($uhome);
1.860 raeburn 1008: }
1009: } else {
1010: if (!$uhome) {
1011: if (defined(&domain($udom,'primary'))) {
1012: $uhome=&domain($udom,'primary');
1013: }
1014: }
1015: }
1016: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1017: my $items='';
1018: foreach my $item (keys(%$storehash)) {
1019: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1020: }
1021: $items=~s/\&$//;
1022: return &reply("putdom:$udom:$namespace:$items",$uhome);
1023: } else {
1.860 raeburn 1024: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1025: }
1026: }
1027:
1.1023 raeburn 1028: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1029: sub newput_dom {
1.1023 raeburn 1030: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1031: my $result;
1032: if (!$udom) {
1033: $udom=$env{'user.domain'};
1034: }
1.1023 raeburn 1035: if ($udom) {
1036: my $uname = &get_domainconfiguser($udom);
1037: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1038: }
1039: return $result;
1040: }
1041:
1.1023 raeburn 1042: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1043: sub del_dom {
1.1023 raeburn 1044: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1045: if (ref($storearr) eq 'ARRAY') {
1046: if (!$udom) {
1047: $udom=$env{'user.domain'};
1048: }
1.1023 raeburn 1049: if ($udom) {
1050: my $uname = &get_domainconfiguser($udom);
1051: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1052: }
1053: }
1054: }
1055:
1.1023 raeburn 1056: # ----------------------------------construct domainconfig user for a domain
1057: sub get_domainconfiguser {
1058: my ($udom) = @_;
1059: return $udom.'-domainconfig';
1060: }
1061:
1.837 raeburn 1062: sub retrieve_inst_usertypes {
1063: my ($udom) = @_;
1064: my (%returnhash,@order);
1.989 raeburn 1065: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1066: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1067: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1068: %returnhash = %{$domdefs{'inststatustypes'}};
1069: @order = @{$domdefs{'inststatusorder'}};
1070: } else {
1071: if (defined(&domain($udom,'primary'))) {
1072: my $uhome=&domain($udom,'primary');
1073: my $rep=&reply("inst_usertypes:$udom",$uhome);
1074: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1075: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1076: return (\%returnhash,\@order);
1077: }
1078: my ($hashitems,$orderitems) = split(/:/,$rep);
1079: my @pairs=split(/\&/,$hashitems);
1080: foreach my $item (@pairs) {
1081: my ($key,$value)=split(/=/,$item,2);
1082: $key = &unescape($key);
1083: next if ($key =~ /^error: 2 /);
1084: $returnhash{$key}=&thaw_unescape($value);
1085: }
1086: my @esc_order = split(/\&/,$orderitems);
1087: foreach my $item (@esc_order) {
1088: push(@order,&unescape($item));
1089: }
1090: } else {
1091: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1092: }
1093: }
1094: return (\%returnhash,\@order);
1095: }
1096:
1.868 raeburn 1097: sub is_domainimage {
1098: my ($url) = @_;
1099: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1100: if (&domain($1) ne '') {
1101: return '1';
1102: }
1103: }
1104: return;
1105: }
1106:
1.899 raeburn 1107: sub inst_directory_query {
1108: my ($srch) = @_;
1109: my $udom = $srch->{'srchdomain'};
1110: my %results;
1111: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1112: my $outcome;
1.899 raeburn 1113: if ($homeserver ne '') {
1.904 albertel 1114: my $queryid=&reply("querysend:instdirsearch:".
1115: &escape($srch->{'srchby'}).':'.
1116: &escape($srch->{'srchterm'}).':'.
1117: &escape($srch->{'srchtype'}),$homeserver);
1118: my $host=&hostname($homeserver);
1119: if ($queryid !~/^\Q$host\E\_/) {
1120: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1121: return;
1122: }
1123: my $response = &get_query_reply($queryid);
1124: my $maxtries = 5;
1125: my $tries = 1;
1126: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1127: $response = &get_query_reply($queryid);
1128: $tries ++;
1129: }
1130:
1131: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1132: if ($response eq 'unavailable') {
1133: $outcome = $response;
1134: } else {
1135: $outcome = 'ok';
1136: my @matches = split(/\n/,$response);
1137: foreach my $match (@matches) {
1138: my ($key,$value) = split(/=/,$match);
1139: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1140: }
1.899 raeburn 1141: }
1142: }
1143: }
1.909 raeburn 1144: return ($outcome,%results);
1.899 raeburn 1145: }
1146:
1147: sub usersearch {
1148: my ($srch) = @_;
1149: my $dom = $srch->{'srchdomain'};
1150: my %results;
1151: my %libserv = &all_library();
1152: my $query = 'usersearch';
1153: foreach my $tryserver (keys(%libserv)) {
1154: if (&host_domain($tryserver) eq $dom) {
1155: my $host=&hostname($tryserver);
1156: my $queryid=
1.911 raeburn 1157: &reply("querysend:".&escape($query).':'.
1158: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1159: &escape($srch->{'srchtype'}).':'.
1160: &escape($srch->{'srchterm'}),$tryserver);
1161: if ($queryid !~/^\Q$host\E\_/) {
1162: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1163: next;
1.899 raeburn 1164: }
1165: my $reply = &get_query_reply($queryid);
1166: my $maxtries = 1;
1167: my $tries = 1;
1168: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1169: $reply = &get_query_reply($queryid);
1170: $tries ++;
1171: }
1172: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1173: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1174: } else {
1.911 raeburn 1175: my @matches;
1176: if ($reply =~ /\n/) {
1177: @matches = split(/\n/,$reply);
1178: } else {
1179: @matches = split(/\&/,$reply);
1180: }
1.899 raeburn 1181: foreach my $match (@matches) {
1182: my ($uname,$udom,%userhash);
1.911 raeburn 1183: foreach my $entry (split(/:/,$match)) {
1184: my ($key,$value) =
1185: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1186: $userhash{$key} = $value;
1187: if ($key eq 'username') {
1188: $uname = $value;
1189: } elsif ($key eq 'domain') {
1190: $udom = $value;
1.911 raeburn 1191: }
1.899 raeburn 1192: }
1193: $results{$uname.':'.$udom} = \%userhash;
1194: }
1195: }
1196: }
1197: }
1198: return %results;
1199: }
1200:
1.912 raeburn 1201: sub get_instuser {
1202: my ($udom,$uname,$id) = @_;
1203: my $homeserver = &domain($udom,'primary');
1204: my ($outcome,%results);
1205: if ($homeserver ne '') {
1206: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1207: &escape($id).':'.&escape($udom),$homeserver);
1208: my $host=&hostname($homeserver);
1209: if ($queryid !~/^\Q$host\E\_/) {
1210: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1211: return;
1212: }
1213: my $response = &get_query_reply($queryid);
1214: my $maxtries = 5;
1215: my $tries = 1;
1216: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1217: $response = &get_query_reply($queryid);
1218: $tries ++;
1219: }
1220: if (!&error($response) && $response ne 'refused') {
1221: if ($response eq 'unavailable') {
1222: $outcome = $response;
1223: } else {
1224: $outcome = 'ok';
1225: my @matches = split(/\n/,$response);
1226: foreach my $match (@matches) {
1227: my ($key,$value) = split(/=/,$match);
1228: $results{&unescape($key)} = &thaw_unescape($value);
1229: }
1230: }
1231: }
1232: }
1233: my %userinfo;
1234: if (ref($results{$uname}) eq 'HASH') {
1235: %userinfo = %{$results{$uname}};
1236: }
1237: return ($outcome,%userinfo);
1238: }
1239:
1240: sub inst_rulecheck {
1.923 raeburn 1241: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1242: my %returnhash;
1243: if ($udom ne '') {
1244: if (ref($rules) eq 'ARRAY') {
1245: @{$rules} = map {&escape($_);} (@{$rules});
1246: my $rulestr = join(':',@{$rules});
1247: my $homeserver=&domain($udom,'primary');
1248: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1249: my $response;
1250: if ($item eq 'username') {
1251: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1252: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1253: $homeserver));
1.923 raeburn 1254: } elsif ($item eq 'id') {
1255: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1256: ':'.&escape($id).':'.$rulestr,
1257: $homeserver));
1.945 raeburn 1258: } elsif ($item eq 'selfcreate') {
1259: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1260: &escape($udom).':'.&escape($uname).
1261: ':'.$rulestr,$homeserver));
1.923 raeburn 1262: }
1.912 raeburn 1263: if ($response ne 'refused') {
1264: my @pairs=split(/\&/,$response);
1265: foreach my $item (@pairs) {
1266: my ($key,$value)=split(/=/,$item,2);
1267: $key = &unescape($key);
1268: next if ($key =~ /^error: 2 /);
1269: $returnhash{$key}=&thaw_unescape($value);
1270: }
1271: }
1272: }
1273: }
1274: }
1275: return %returnhash;
1276: }
1277:
1278: sub inst_userrules {
1.923 raeburn 1279: my ($udom,$check) = @_;
1.912 raeburn 1280: my (%ruleshash,@ruleorder);
1281: if ($udom ne '') {
1282: my $homeserver=&domain($udom,'primary');
1283: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1284: my $response;
1285: if ($check eq 'id') {
1286: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1287: $homeserver);
1.943 raeburn 1288: } elsif ($check eq 'email') {
1289: $response=&reply('instemailrules:'.&escape($udom),
1290: $homeserver);
1.923 raeburn 1291: } else {
1292: $response=&reply('instuserrules:'.&escape($udom),
1293: $homeserver);
1294: }
1.912 raeburn 1295: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1296: ($response ne 'unknown_cmd') &&
1.912 raeburn 1297: ($response ne 'no_such_host')) {
1298: my ($hashitems,$orderitems) = split(/:/,$response);
1299: my @pairs=split(/\&/,$hashitems);
1300: foreach my $item (@pairs) {
1301: my ($key,$value)=split(/=/,$item,2);
1302: $key = &unescape($key);
1303: next if ($key =~ /^error: 2 /);
1304: $ruleshash{$key}=&thaw_unescape($value);
1305: }
1306: my @esc_order = split(/\&/,$orderitems);
1307: foreach my $item (@esc_order) {
1308: push(@ruleorder,&unescape($item));
1309: }
1310: }
1311: }
1312: }
1313: return (\%ruleshash,\@ruleorder);
1314: }
1315:
1.976 raeburn 1316: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1317:
1318: sub get_domain_defaults {
1319: my ($domain) = @_;
1320: my $cachetime = 60*60*24;
1321: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1322: if (defined($cached)) {
1323: if (ref($result) eq 'HASH') {
1324: return %{$result};
1325: }
1326: }
1327: my %domdefaults;
1328: my %domconfig =
1.989 raeburn 1329: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1330: 'requestcourses','inststatus',
1331: 'coursedefaults'],$domain);
1.943 raeburn 1332: if (ref($domconfig{'defaults'}) eq 'HASH') {
1333: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1334: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1335: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1336: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1337: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1338: } else {
1339: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1340: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1341: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1342: }
1.976 raeburn 1343: if (ref($domconfig{'quotas'}) eq 'HASH') {
1344: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1345: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1346: } else {
1347: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1348: }
1349: my @usertools = ('aboutme','blog','portfolio');
1350: foreach my $item (@usertools) {
1351: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1352: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1353: }
1354: }
1355: }
1.985 raeburn 1356: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1357: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1358: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1359: }
1360: }
1.989 raeburn 1361: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1362: foreach my $item ('inststatustypes','inststatusorder') {
1363: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1364: }
1365: }
1.1047 raeburn 1366: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1367: foreach my $item ('canuse_pdfforms') {
1368: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1369: }
1370: }
1.943 raeburn 1371: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1372: $cachetime);
1373: return %domdefaults;
1374: }
1375:
1.344 www 1376: # --------------------------------------------------- Assign a key to a student
1377:
1378: sub assign_access_key {
1.364 www 1379: #
1380: # a valid key looks like uname:udom#comments
1381: # comments are being appended
1382: #
1.498 www 1383: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1384: $kdom=
1.620 albertel 1385: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1386: $knum=
1.620 albertel 1387: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1388: $cdom=
1.620 albertel 1389: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1390: $cnum=
1.620 albertel 1391: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1392: $udom=$env{'user.name'} unless (defined($udom));
1393: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1394: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1395: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1396: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1397: # assigned to this person
1398: # - this should not happen,
1.345 www 1399: # unless something went wrong
1400: # the first time around
1401: # ready to assign
1.364 www 1402: $logentry=$1.'; '.$logentry;
1.496 www 1403: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1404: $kdom,$knum) eq 'ok') {
1.345 www 1405: # key now belongs to user
1.346 www 1406: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1407: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1408: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1409: return 'ok';
1410: } else {
1411: return
1412: 'error: Count not permanently assign key, will need to be re-entered later.';
1413: }
1414: } else {
1415: return 'error: Could not assign key, try again later.';
1416: }
1.364 www 1417: } elsif (!$existing{$ckey}) {
1.345 www 1418: # the key does not exist
1419: return 'error: The key does not exist';
1420: } else {
1421: # the key is somebody else's
1422: return 'error: The key is already in use';
1423: }
1.344 www 1424: }
1425:
1.364 www 1426: # ------------------------------------------ put an additional comment on a key
1427:
1428: sub comment_access_key {
1429: #
1430: # a valid key looks like uname:udom#comments
1431: # comments are being appended
1432: #
1433: my ($ckey,$cdom,$cnum,$logentry)=@_;
1434: $cdom=
1.620 albertel 1435: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1436: $cnum=
1.620 albertel 1437: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1438: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1439: if ($existing{$ckey}) {
1440: $existing{$ckey}.='; '.$logentry;
1441: # ready to assign
1.367 www 1442: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1443: $cdom,$cnum) eq 'ok') {
1444: return 'ok';
1445: } else {
1446: return 'error: Count not store comment.';
1447: }
1448: } else {
1449: # the key does not exist
1450: return 'error: The key does not exist';
1451: }
1452: }
1453:
1.344 www 1454: # ------------------------------------------------------ Generate a set of keys
1455:
1456: sub generate_access_keys {
1.364 www 1457: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1458: $cdom=
1.620 albertel 1459: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1460: $cnum=
1.620 albertel 1461: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1462: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1463: unless (($cdom) && ($cnum)) { return 0; }
1464: if ($number>10000) { return 0; }
1465: sleep(2); # make sure don't get same seed twice
1466: srand(time()^($$+($$<<15))); # from "Programming Perl"
1467: my $total=0;
1468: for (my $i=1;$i<=$number;$i++) {
1469: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1470: sprintf("%lx",int(100000*rand)).'-'.
1471: sprintf("%lx",int(100000*rand));
1472: $newkey=~s/1/g/g; # folks mix up 1 and l
1473: $newkey=~s/0/h/g; # and also 0 and O
1474: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1475: if ($existing{$newkey}) {
1476: $i--;
1477: } else {
1.364 www 1478: if (&put('accesskeys',
1479: { $newkey => '# generated '.localtime().
1.620 albertel 1480: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1481: '; '.$logentry },
1482: $cdom,$cnum) eq 'ok') {
1.344 www 1483: $total++;
1484: }
1485: }
1486: }
1.620 albertel 1487: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1488: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1489: return $total;
1490: }
1491:
1492: # ------------------------------------------------------- Validate an accesskey
1493:
1494: sub validate_access_key {
1495: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1496: $cdom=
1.620 albertel 1497: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1498: $cnum=
1.620 albertel 1499: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1500: $udom=$env{'user.domain'} unless (defined($udom));
1501: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1502: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1503: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1504: }
1505:
1506: # ------------------------------------- Find the section of student in a course
1.652 albertel 1507: sub devalidate_getsection_cache {
1508: my ($udom,$unam,$courseid)=@_;
1509: my $hashid="$udom:$unam:$courseid";
1510: &devalidate_cache_new('getsection',$hashid);
1511: }
1.298 matthew 1512:
1.815 albertel 1513: sub courseid_to_courseurl {
1514: my ($courseid) = @_;
1515: #already url style courseid
1516: return $courseid if ($courseid =~ m{^/});
1517:
1518: if (exists($env{'course.'.$courseid.'.num'})) {
1519: my $cnum = $env{'course.'.$courseid.'.num'};
1520: my $cdom = $env{'course.'.$courseid.'.domain'};
1521: return "/$cdom/$cnum";
1522: }
1523:
1524: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1525: if (exists($courseinfo{'num'})) {
1526: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1527: }
1528:
1529: return undef;
1530: }
1531:
1.298 matthew 1532: sub getsection {
1533: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1534: my $cachetime=1800;
1.551 albertel 1535:
1536: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1537: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1538: if (defined($cached)) { return $result; }
1539:
1.298 matthew 1540: my %Pending;
1541: my %Expired;
1542: #
1543: # Each role can either have not started yet (pending), be active,
1544: # or have expired.
1545: #
1546: # If there is an active role, we are done.
1547: #
1548: # If there is more than one role which has not started yet,
1549: # choose the one which will start sooner
1550: # If there is one role which has not started yet, return it.
1551: #
1552: # If there is more than one expired role, choose the one which ended last.
1553: # If there is a role which has expired, return it.
1554: #
1.815 albertel 1555: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1556: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1557: foreach my $key (keys(%roleshash)) {
1.479 albertel 1558: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1559: my $section=$1;
1560: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1561: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1562: my $now=time;
1.548 albertel 1563: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1564: $Expired{$end}=$section;
1565: next;
1566: }
1.548 albertel 1567: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1568: $Pending{$start}=$section;
1569: next;
1570: }
1.599 albertel 1571: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1572: }
1573: #
1574: # Presumedly there will be few matching roles from the above
1575: # loop and the sorting time will be negligible.
1576: if (scalar(keys(%Pending))) {
1577: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1578: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1579: }
1580: if (scalar(keys(%Expired))) {
1581: my @sorted = sort {$a <=> $b} keys(%Expired);
1582: my $time = pop(@sorted);
1.599 albertel 1583: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1584: }
1.599 albertel 1585: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1586: }
1.70 www 1587:
1.599 albertel 1588: sub save_cache {
1589: &purge_remembered();
1.722 albertel 1590: #&Apache::loncommon::validate_page();
1.620 albertel 1591: undef(%env);
1.780 albertel 1592: undef($env_loaded);
1.599 albertel 1593: }
1.452 albertel 1594:
1.599 albertel 1595: my $to_remember=-1;
1596: my %remembered;
1597: my %accessed;
1598: my $kicks=0;
1599: my $hits=0;
1.849 albertel 1600: sub make_key {
1601: my ($name,$id) = @_;
1.872 albertel 1602: if (length($id) > 65
1603: && length(&escape($id)) > 200) {
1604: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1605: }
1.849 albertel 1606: return &escape($name.':'.$id);
1607: }
1608:
1.599 albertel 1609: sub devalidate_cache_new {
1610: my ($name,$id,$debug) = @_;
1611: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1612: $id=&make_key($name,$id);
1.599 albertel 1613: $memcache->delete($id);
1614: delete($remembered{$id});
1615: delete($accessed{$id});
1616: }
1617:
1618: sub is_cached_new {
1619: my ($name,$id,$debug) = @_;
1.849 albertel 1620: $id=&make_key($name,$id);
1.599 albertel 1621: if (exists($remembered{$id})) {
1622: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1623: $accessed{$id}=[&gettimeofday()];
1624: $hits++;
1625: return ($remembered{$id},1);
1626: }
1627: my $value = $memcache->get($id);
1628: if (!(defined($value))) {
1629: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1630: return (undef,undef);
1.416 albertel 1631: }
1.599 albertel 1632: if ($value eq '__undef__') {
1633: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1634: $value=undef;
1635: }
1636: &make_room($id,$value,$debug);
1637: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1638: return ($value,1);
1639: }
1640:
1641: sub do_cache_new {
1642: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1643: $id=&make_key($name,$id);
1.599 albertel 1644: my $setvalue=$value;
1645: if (!defined($setvalue)) {
1646: $setvalue='__undef__';
1647: }
1.623 albertel 1648: if (!defined($time) ) {
1649: $time=600;
1650: }
1.599 albertel 1651: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1652: my $result = $memcache->set($id,$setvalue,$time);
1653: if (! $result) {
1.872 albertel 1654: &logthis("caching of id -> $id failed");
1.910 albertel 1655: $memcache->disconnect_all();
1.872 albertel 1656: }
1.600 albertel 1657: # need to make a copy of $value
1.919 albertel 1658: &make_room($id,$value,$debug);
1.599 albertel 1659: return $value;
1660: }
1661:
1662: sub make_room {
1663: my ($id,$value,$debug)=@_;
1.919 albertel 1664:
1665: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1666: : $value;
1.599 albertel 1667: if ($to_remember<0) { return; }
1668: $accessed{$id}=[&gettimeofday()];
1669: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1670: my $to_kick;
1671: my $max_time=0;
1672: foreach my $other (keys(%accessed)) {
1673: if (&tv_interval($accessed{$other}) > $max_time) {
1674: $to_kick=$other;
1675: $max_time=&tv_interval($accessed{$other});
1676: }
1677: }
1678: delete($remembered{$to_kick});
1679: delete($accessed{$to_kick});
1680: $kicks++;
1681: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1682: return;
1683: }
1684:
1.599 albertel 1685: sub purge_remembered {
1.604 albertel 1686: #&logthis("Tossing ".scalar(keys(%remembered)));
1687: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1688: undef(%remembered);
1689: undef(%accessed);
1.428 albertel 1690: }
1.70 www 1691: # ------------------------------------- Read an entry from a user's environment
1692:
1693: sub userenvironment {
1694: my ($udom,$unam,@what)=@_;
1.976 raeburn 1695: my $items;
1696: foreach my $item (@what) {
1697: $items.=&escape($item).'&';
1698: }
1699: $items=~s/\&$//;
1.70 www 1700: my %returnhash=();
1.1009 raeburn 1701: my $uhome = &homeserver($unam,$udom);
1702: unless ($uhome eq 'no_host') {
1703: my @answer=split(/\&/,
1704: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1705: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1706: return %returnhash;
1707: }
1.1009 raeburn 1708: my $i;
1709: for ($i=0;$i<=$#what;$i++) {
1710: $returnhash{$what[$i]}=&unescape($answer[$i]);
1711: }
1.70 www 1712: }
1713: return %returnhash;
1.1 albertel 1714: }
1715:
1.617 albertel 1716: # ---------------------------------------------------------- Get a studentphoto
1717: sub studentphoto {
1718: my ($udom,$unam,$ext) = @_;
1719: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1720: if (defined($env{'request.course.id'})) {
1.708 raeburn 1721: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1722: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1723: return(&retrievestudentphoto($udom,$unam,$ext));
1724: } else {
1725: my ($result,$perm_reqd)=
1.707 albertel 1726: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1727: if ($result eq 'ok') {
1728: if (!($perm_reqd eq 'yes')) {
1729: return(&retrievestudentphoto($udom,$unam,$ext));
1730: }
1731: }
1732: }
1733: }
1734: } else {
1735: my ($result,$perm_reqd) =
1.707 albertel 1736: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1737: if ($result eq 'ok') {
1738: if (!($perm_reqd eq 'yes')) {
1739: return(&retrievestudentphoto($udom,$unam,$ext));
1740: }
1741: }
1742: }
1743: return '/adm/lonKaputt/lonlogo_broken.gif';
1744: }
1745:
1746: sub retrievestudentphoto {
1747: my ($udom,$unam,$ext,$type) = @_;
1748: my $home=&Apache::lonnet::homeserver($unam,$udom);
1749: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1750: if ($ret eq 'ok') {
1751: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1752: if ($type eq 'thumbnail') {
1753: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1754: }
1755: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1756: return $tokenurl;
1757: } else {
1758: if ($type eq 'thumbnail') {
1759: return '/adm/lonKaputt/genericstudent_tn.gif';
1760: } else {
1761: return '/adm/lonKaputt/lonlogo_broken.gif';
1762: }
1.617 albertel 1763: }
1764: }
1765:
1.263 www 1766: # -------------------------------------------------------------------- New chat
1767:
1768: sub chatsend {
1.724 raeburn 1769: my ($newentry,$anon,$group)=@_;
1.620 albertel 1770: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1771: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1772: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1773: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1774: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1775: &escape($newentry)).':'.$group,$chome);
1.292 www 1776: }
1777:
1778: # ------------------------------------------ Find current version of a resource
1779:
1780: sub getversion {
1781: my $fname=&clutter(shift);
1782: unless ($fname=~/^\/res\//) { return -1; }
1783: return ¤tversion(&filelocation('',$fname));
1784: }
1785:
1786: sub currentversion {
1787: my $fname=shift;
1.599 albertel 1788: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1789: if (defined($cached)) { return $result; }
1.292 www 1790: my $author=$fname;
1791: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1792: my ($udom,$uname)=split(/\//,$author);
1793: my $home=homeserver($uname,$udom);
1794: if ($home eq 'no_host') {
1795: return -1;
1796: }
1797: my $answer=reply("currentversion:$fname",$home);
1798: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1799: return -1;
1800: }
1.599 albertel 1801: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1802: }
1803:
1.1 albertel 1804: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1805:
1.1 albertel 1806: sub subscribe {
1807: my $fname=shift;
1.761 raeburn 1808: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1809: $fname=~s/[\n\r]//g;
1.1 albertel 1810: my $author=$fname;
1811: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1812: my ($udom,$uname)=split(/\//,$author);
1813: my $home=homeserver($uname,$udom);
1.335 albertel 1814: if ($home eq 'no_host') {
1815: return 'not_found';
1.1 albertel 1816: }
1817: my $answer=reply("sub:$fname",$home);
1.64 www 1818: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1819: $answer.=' by '.$home;
1820: }
1.1 albertel 1821: return $answer;
1822: }
1823:
1.8 www 1824: # -------------------------------------------------------------- Replicate file
1825:
1826: sub repcopy {
1827: my $filename=shift;
1.23 www 1828: $filename=~s/\/+/\//g;
1.607 raeburn 1829: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1830: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1831: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1832: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1833: return &repcopy_userfile($filename);
1834: }
1.532 albertel 1835: $filename=~s/[\n\r]//g;
1.8 www 1836: my $transname="$filename.in.transfer";
1.828 www 1837: # FIXME: this should flock
1.607 raeburn 1838: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1839: my $remoteurl=subscribe($filename);
1.64 www 1840: if ($remoteurl =~ /^con_lost by/) {
1841: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1842: return 'unavailable';
1.8 www 1843: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1844: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1845: return 'not_found';
1.64 www 1846: } elsif ($remoteurl =~ /^rejected by/) {
1847: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1848: return 'forbidden';
1.20 www 1849: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1850: return 'ok';
1.8 www 1851: } else {
1.290 www 1852: my $author=$filename;
1853: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1854: my ($udom,$uname)=split(/\//,$author);
1855: my $home=homeserver($uname,$udom);
1856: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1857: my @parts=split(/\//,$filename);
1858: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1859: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1860: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1861: return 'bad_request';
1.8 www 1862: }
1863: my $count;
1864: for ($count=5;$count<$#parts;$count++) {
1865: $path.="/$parts[$count]";
1866: if ((-e $path)!=1) {
1867: mkdir($path,0777);
1868: }
1869: }
1870: my $ua=new LWP::UserAgent;
1871: my $request=new HTTP::Request('GET',"$remoteurl");
1872: my $response=$ua->request($request,$transname);
1873: if ($response->is_error()) {
1874: unlink($transname);
1875: my $message=$response->status_line;
1.672 albertel 1876: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1877: ." LWP get: $message: $filename</font>");
1.607 raeburn 1878: return 'unavailable';
1.8 www 1879: } else {
1.16 www 1880: if ($remoteurl!~/\.meta$/) {
1881: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1882: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1883: if ($mresponse->is_error()) {
1884: unlink($filename.'.meta');
1885: &logthis(
1.672 albertel 1886: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1887: }
1888: }
1.8 www 1889: rename($transname,$filename);
1.607 raeburn 1890: return 'ok';
1.8 www 1891: }
1.290 www 1892: }
1.8 www 1893: }
1.330 www 1894: }
1895:
1896: # ------------------------------------------------ Get server side include body
1897: sub ssi_body {
1.381 albertel 1898: my ($filelink,%form)=@_;
1.606 matthew 1899: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1900: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1901: }
1.953 www 1902: my $output='';
1903: my $response;
1.980 raeburn 1904: if ($filelink=~/^https?\:/) {
1.954 raeburn 1905: ($output,$response)=&externalssi($filelink);
1.953 www 1906: } else {
1.1004 droeschl 1907: $filelink .= $filelink=~/\?/ ? '&' : '?';
1908: $filelink .= 'inhibitmenu=yes';
1.953 www 1909: ($output,$response)=&ssi($filelink,%form);
1910: }
1.778 albertel 1911: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1912: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1913: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1914: if (wantarray) {
1915: return ($output, $response);
1916: } else {
1917: return $output;
1918: }
1.8 www 1919: }
1920:
1.15 www 1921: # --------------------------------------------------------- Server Side Include
1922:
1.782 albertel 1923: sub absolute_url {
1924: my ($host_name) = @_;
1925: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1926: if ($host_name eq '') {
1927: $host_name = $ENV{'SERVER_NAME'};
1928: }
1929: return $protocol.$host_name;
1930: }
1931:
1.942 foxr 1932: #
1933: # Server side include.
1934: # Parameters:
1935: # fn Possibly encrypted resource name/id.
1936: # form Hash that describes how the rendering should be done
1937: # and other things.
1.944 foxr 1938: # Returns:
1.950 raeburn 1939: # Scalar context: The content of the response.
1940: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1941: #
1.15 www 1942: sub ssi {
1943:
1.944 foxr 1944: my ($fn,%form)=@_;
1.15 www 1945: my $ua=new LWP::UserAgent;
1.23 www 1946: my $request;
1.711 albertel 1947:
1948: $form{'no_update_last_known'}=1;
1.895 albertel 1949: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1950: if (%form) {
1.782 albertel 1951: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 1952: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 1953: } else {
1.782 albertel 1954: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1955: }
1956:
1.15 www 1957: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1958: my $response=$ua->request($request);
1959:
1.944 foxr 1960: if (wantarray) {
1961: return ($response->content, $response);
1962: } else {
1963: return $response->content;
1.942 foxr 1964: }
1.324 www 1965: }
1966:
1967: sub externalssi {
1968: my ($url)=@_;
1969: my $ua=new LWP::UserAgent;
1970: my $request=new HTTP::Request('GET',$url);
1971: my $response=$ua->request($request);
1.954 raeburn 1972: if (wantarray) {
1973: return ($response->content, $response);
1974: } else {
1975: return $response->content;
1976: }
1.15 www 1977: }
1.254 www 1978:
1.492 albertel 1979: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1980:
1981: sub allowuploaded {
1982: my ($srcurl,$url)=@_;
1983: $url=&clutter(&declutter($url));
1984: my $dir=$url;
1985: $dir=~s/\/[^\/]+$//;
1986: my %httpref=();
1987: my $httpurl=&hreflocation('',$url);
1988: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 1989: &Apache::lonnet::appenv(\%httpref);
1.254 www 1990: }
1.477 raeburn 1991:
1.478 albertel 1992: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1993: # input: action, courseID, current domain, intended
1.637 raeburn 1994: # path to file, source of file, instruction to parse file for objects,
1995: # ref to hash for embedded objects,
1996: # ref to hash for codebase of java objects.
1997: #
1.485 raeburn 1998: # output: url to file (if action was uploaddoc),
1999: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2000: #
1.478 albertel 2001: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2002: # course.
1.477 raeburn 2003: #
1.478 albertel 2004: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2005: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2006: # course's home server.
1.477 raeburn 2007: #
1.478 albertel 2008: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2009: # be copied from $source (current location) to
2010: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2011: # and will then be copied to
2012: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2013: # course's home server.
1.485 raeburn 2014: #
1.481 raeburn 2015: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2016: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2017: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2018: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2019: # in course's home server.
1.637 raeburn 2020: #
1.477 raeburn 2021:
2022: sub process_coursefile {
1.638 albertel 2023: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2024: my $fetchresult;
1.638 albertel 2025: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2026: if ($action eq 'propagate') {
1.638 albertel 2027: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2028: $home);
1.481 raeburn 2029: } else {
1.477 raeburn 2030: my $fpath = '';
2031: my $fname = $file;
1.478 albertel 2032: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2033: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2034: my $filepath = &build_filepath($fpath);
1.481 raeburn 2035: if ($action eq 'copy') {
2036: if ($source eq '') {
2037: $fetchresult = 'no source file';
2038: return $fetchresult;
2039: } else {
2040: my $destination = $filepath.'/'.$fname;
2041: rename($source,$destination);
2042: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2043: $home);
1.481 raeburn 2044: }
2045: } elsif ($action eq 'uploaddoc') {
2046: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2047: print $fh $env{'form.'.$source};
1.481 raeburn 2048: close($fh);
1.637 raeburn 2049: if ($parser eq 'parse') {
1.1024 raeburn 2050: my $mm = new File::MMagic;
2051: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2052: if ($mime_type eq 'text/html') {
2053: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2054: unless ($parse_result eq 'ok') {
2055: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2056: }
1.637 raeburn 2057: }
2058: }
1.477 raeburn 2059: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2060: $home);
1.481 raeburn 2061: if ($fetchresult eq 'ok') {
2062: return '/uploaded/'.$fpath.'/'.$fname;
2063: } else {
2064: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2065: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2066: return '/adm/notfound.html';
2067: }
1.477 raeburn 2068: }
2069: }
1.485 raeburn 2070: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2071: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2072: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2073: }
2074: return $fetchresult;
2075: }
2076:
1.637 raeburn 2077: sub build_filepath {
2078: my ($fpath) = @_;
2079: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2080: unless ($fpath eq '') {
2081: my @parts=split('/',$fpath);
2082: foreach my $part (@parts) {
2083: $filepath.= '/'.$part;
2084: if ((-e $filepath)!=1) {
2085: mkdir($filepath,0777);
2086: }
2087: }
2088: }
2089: return $filepath;
2090: }
2091:
2092: sub store_edited_file {
1.638 albertel 2093: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2094: my $file = $primary_url;
2095: $file =~ s#^/uploaded/$docudom/$docuname/##;
2096: my $fpath = '';
2097: my $fname = $file;
2098: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2099: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2100: my $filepath = &build_filepath($fpath);
2101: open(my $fh,'>'.$filepath.'/'.$fname);
2102: print $fh $content;
2103: close($fh);
1.638 albertel 2104: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2105: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2106: $home);
1.637 raeburn 2107: if ($$fetchresult eq 'ok') {
2108: return '/uploaded/'.$fpath.'/'.$fname;
2109: } else {
1.638 albertel 2110: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2111: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2112: return '/adm/notfound.html';
2113: }
2114: }
2115:
1.531 albertel 2116: sub clean_filename {
1.831 albertel 2117: my ($fname,$args)=@_;
1.315 www 2118: # Replace Windows backslashes by forward slashes
1.257 www 2119: $fname=~s/\\/\//g;
1.831 albertel 2120: if (!$args->{'keep_path'}) {
2121: # Get rid of everything but the actual filename
2122: $fname=~s/^.*\/([^\/]+)$/$1/;
2123: }
1.315 www 2124: # Replace spaces by underscores
2125: $fname=~s/\s+/\_/g;
2126: # Replace all other weird characters by nothing
1.831 albertel 2127: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2128: # Replace all .\d. sequences with _\d. so they no longer look like version
2129: # numbers
2130: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2131: return $fname;
2132: }
1.1051 raeburn 2133: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2134: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2135: # image with the same aspect ratio as the original, but with dimensions which do
2136: # not exceed $resizewidth and $resizeheight.
2137:
1.984 neumanie 2138: sub resizeImage {
1.1051 raeburn 2139: my ($img_path,$resizewidth,$resizeheight) = @_;
2140: my $ima = Image::Magick->new;
2141: my $resized;
2142: if (-e $img_path) {
2143: $ima->Read($img_path);
2144: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2145: my $width = $ima->Get('width');
2146: my $height = $ima->Get('height');
2147: if ($width > $resizewidth) {
2148: my $factor = $width/$resizewidth;
2149: my $newheight = $height/$factor;
2150: $ima->Scale(width=>$resizewidth,height=>$newheight);
2151: $resized = 1;
2152: }
2153: }
2154: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2155: my $width = $ima->Get('width');
2156: my $height = $ima->Get('height');
2157: if ($height > $resizeheight) {
2158: my $factor = $height/$resizeheight;
2159: my $newwidth = $width/$factor;
2160: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2161: $resized = 1;
2162: }
2163: }
2164: if ($resized) {
2165: $ima->Write($img_path);
2166: }
2167: }
2168: return;
1.977 amueller 2169: }
2170:
1.608 albertel 2171: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2172: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2173: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2174: # $coursedoc - if true up to the current course
2175: # if false
2176: # $subdir - directory in userfile to store the file into
1.858 raeburn 2177: # $parser - instruction to parse file for objects ($parser = parse)
2178: # $allfiles - reference to hash for embedded objects
2179: # $codebase - reference to hash for codebase of java objects
2180: # $desuname - username for permanent storage of uploaded file
2181: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2182: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2183: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2184: # $resizewidth - width (pixels) to which to resize uploaded image
2185: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2186: #
1.686 albertel 2187: # output: url of file in userspace, or error: <message>
2188: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2189:
1.531 albertel 2190: sub userfileupload {
1.860 raeburn 2191: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2192: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2193: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2194: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2195: $fname=&clean_filename($fname);
1.315 www 2196: # See if there is anything left
1.257 www 2197: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2198: chop($env{'form.'.$formname});
1.523 raeburn 2199: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2200: my $now = time;
2201: my $filepath = 'tmp/helprequests/'.$now;
2202: my @parts=split(/\//,$filepath);
2203: my $fullpath = $perlvar{'lonDaemons'};
2204: for (my $i=0;$i<@parts;$i++) {
2205: $fullpath .= '/'.$parts[$i];
2206: if ((-e $fullpath)!=1) {
2207: mkdir($fullpath,0777);
2208: }
2209: }
2210: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2211: print $fh $env{'form.'.$formname};
1.523 raeburn 2212: close($fh);
1.741 raeburn 2213: return $fullpath.'/'.$fname;
2214: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2215: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2216: '_'.$env{'user.domain'}.'/pending';
2217: my @parts=split(/\//,$filepath);
2218: my $fullpath = $perlvar{'lonDaemons'};
2219: for (my $i=0;$i<@parts;$i++) {
2220: $fullpath .= '/'.$parts[$i];
2221: if ((-e $fullpath)!=1) {
2222: mkdir($fullpath,0777);
2223: }
2224: }
2225: open(my $fh,'>'.$fullpath.'/'.$fname);
2226: print $fh $env{'form.'.$formname};
2227: close($fh);
2228: return $fullpath.'/'.$fname;
1.523 raeburn 2229: }
1.995 raeburn 2230: if ($subdir eq 'scantron') {
2231: $fname = 'scantron_orig_'.$fname;
2232: } else {
1.258 www 2233: # Create the directory if not present
1.995 raeburn 2234: $fname="$subdir/$fname";
2235: }
1.259 www 2236: if ($coursedoc) {
1.638 albertel 2237: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2238: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2239: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2240: return &finishuserfileupload($docuname,$docudom,
2241: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2242: $codebase,$thumbwidth,$thumbheight,
2243: $resizewidth,$resizeheight);
1.481 raeburn 2244: } else {
1.620 albertel 2245: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2246: return &process_coursefile('uploaddoc',$docuname,$docudom,
2247: $fname,$formname,$parser,
2248: $allfiles,$codebase);
1.481 raeburn 2249: }
1.719 banghart 2250: } elsif (defined($destuname)) {
2251: my $docuname=$destuname;
2252: my $docudom=$destudom;
1.860 raeburn 2253: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2254: $parser,$allfiles,$codebase,
1.1051 raeburn 2255: $thumbwidth,$thumbheight,
2256: $resizewidth,$resizeheight);
1.719 banghart 2257:
1.259 www 2258: } else {
1.638 albertel 2259: my $docuname=$env{'user.name'};
2260: my $docudom=$env{'user.domain'};
1.714 raeburn 2261: if (exists($env{'form.group'})) {
2262: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2263: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2264: }
1.860 raeburn 2265: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2266: $parser,$allfiles,$codebase,
1.1051 raeburn 2267: $thumbwidth,$thumbheight,
2268: $resizewidth,$resizeheight);
1.259 www 2269: }
1.271 www 2270: }
2271:
2272: sub finishuserfileupload {
1.860 raeburn 2273: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2274: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2275: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2276: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2277:
1.860 raeburn 2278: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2279: $file=$fname;
2280: if ($fname=~m|/|) {
2281: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2282: $path.=$fnamepath.'/';
2283: }
1.259 www 2284: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2285: my $count;
2286: for ($count=4;$count<=$#parts;$count++) {
2287: $filepath.="/$parts[$count]";
2288: if ((-e $filepath)!=1) {
2289: mkdir($filepath,0777);
2290: }
2291: }
1.984 neumanie 2292:
1.258 www 2293: # Save the file
2294: {
1.701 albertel 2295: if (!open(FH,'>'.$filepath.'/'.$file)) {
2296: &logthis('Failed to create '.$filepath.'/'.$file);
2297: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2298: return '/adm/notfound.html';
2299: }
2300: if (!print FH ($env{'form.'.$formname})) {
2301: &logthis('Failed to write to '.$filepath.'/'.$file);
2302: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2303: return '/adm/notfound.html';
2304: }
1.570 albertel 2305: close(FH);
1.1051 raeburn 2306: if ($resizewidth && $resizeheight) {
2307: my $mm = new File::MMagic;
2308: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2309: if ($mime_type =~ m{^image/}) {
2310: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2311: }
1.977 amueller 2312: }
1.258 www 2313: }
1.637 raeburn 2314: if ($parser eq 'parse') {
1.1024 raeburn 2315: my $mm = new File::MMagic;
2316: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2317: if ($mime_type eq 'text/html') {
2318: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2319: $allfiles,$codebase);
2320: unless ($parse_result eq 'ok') {
2321: &logthis('Failed to parse '.$filepath.$file.
2322: ' for embedded media: '.$parse_result);
2323: }
1.637 raeburn 2324: }
2325: }
1.860 raeburn 2326: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2327: my $input = $filepath.'/'.$file;
2328: my $output = $filepath.'/'.'tn-'.$file;
2329: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2330: system("convert -sample $thumbsize $input $output");
2331: if (-e $filepath.'/'.'tn-'.$file) {
2332: $fetchthumb = 1;
2333: }
2334: }
1.858 raeburn 2335:
1.259 www 2336: # Notify homeserver to grep it
2337: #
1.984 neumanie 2338: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2339: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2340: if ($fetchresult eq 'ok') {
1.860 raeburn 2341: if ($fetchthumb) {
2342: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2343: if ($thumbresult ne 'ok') {
2344: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2345: $docuhome.': '.$thumbresult);
2346: }
2347: }
1.259 www 2348: #
1.258 www 2349: # Return the URL to it
1.494 albertel 2350: return '/uploaded/'.$path.$file;
1.263 www 2351: } else {
1.494 albertel 2352: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2353: ': '.$fetchresult);
1.263 www 2354: return '/adm/notfound.html';
1.858 raeburn 2355: }
1.493 albertel 2356: }
2357:
1.637 raeburn 2358: sub extract_embedded_items {
1.961 raeburn 2359: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2360: my @state = ();
2361: my %javafiles = (
2362: codebase => '',
2363: code => '',
2364: archive => ''
2365: );
2366: my %mediafiles = (
2367: src => '',
2368: movie => '',
2369: );
1.648 raeburn 2370: my $p;
2371: if ($content) {
2372: $p = HTML::LCParser->new($content);
2373: } else {
1.961 raeburn 2374: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2375: }
1.641 albertel 2376: while (my $t=$p->get_token()) {
1.640 albertel 2377: if ($t->[0] eq 'S') {
2378: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2379: push(@state, $tagname);
1.648 raeburn 2380: if (lc($tagname) eq 'allow') {
2381: &add_filetype($allfiles,$attr->{'src'},'src');
2382: }
1.640 albertel 2383: if (lc($tagname) eq 'img') {
2384: &add_filetype($allfiles,$attr->{'src'},'src');
2385: }
1.886 albertel 2386: if (lc($tagname) eq 'a') {
2387: &add_filetype($allfiles,$attr->{'href'},'href');
2388: }
1.645 raeburn 2389: if (lc($tagname) eq 'script') {
2390: if ($attr->{'archive'} =~ /\.jar$/i) {
2391: &add_filetype($allfiles,$attr->{'archive'},'archive');
2392: } else {
2393: &add_filetype($allfiles,$attr->{'src'},'src');
2394: }
2395: }
2396: if (lc($tagname) eq 'link') {
2397: if (lc($attr->{'rel'}) eq 'stylesheet') {
2398: &add_filetype($allfiles,$attr->{'href'},'href');
2399: }
2400: }
1.640 albertel 2401: if (lc($tagname) eq 'object' ||
2402: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2403: foreach my $item (keys(%javafiles)) {
2404: $javafiles{$item} = '';
2405: }
2406: }
2407: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2408: my $name = lc($attr->{'name'});
2409: foreach my $item (keys(%javafiles)) {
2410: if ($name eq $item) {
2411: $javafiles{$item} = $attr->{'value'};
2412: last;
2413: }
2414: }
2415: foreach my $item (keys(%mediafiles)) {
2416: if ($name eq $item) {
2417: &add_filetype($allfiles, $attr->{'value'}, 'value');
2418: last;
2419: }
2420: }
2421: }
2422: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2423: foreach my $item (keys(%javafiles)) {
2424: if ($attr->{$item}) {
2425: $javafiles{$item} = $attr->{$item};
2426: last;
2427: }
2428: }
2429: foreach my $item (keys(%mediafiles)) {
2430: if ($attr->{$item}) {
2431: &add_filetype($allfiles,$attr->{$item},$item);
2432: last;
2433: }
2434: }
2435: }
2436: } elsif ($t->[0] eq 'E') {
2437: my ($tagname) = ($t->[1]);
2438: if ($javafiles{'codebase'} ne '') {
2439: $javafiles{'codebase'} .= '/';
2440: }
2441: if (lc($tagname) eq 'applet' ||
2442: lc($tagname) eq 'object' ||
2443: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2444: ) {
2445: foreach my $item (keys(%javafiles)) {
2446: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2447: my $file=$javafiles{'codebase'}.$javafiles{$item};
2448: &add_filetype($allfiles,$file,$item);
2449: }
2450: }
2451: }
2452: pop @state;
2453: }
2454: }
1.637 raeburn 2455: return 'ok';
2456: }
2457:
1.639 albertel 2458: sub add_filetype {
2459: my ($allfiles,$file,$type)=@_;
2460: if (exists($allfiles->{$file})) {
2461: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2462: push(@{$allfiles->{$file}}, &escape($type));
2463: }
2464: } else {
2465: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2466: }
2467: }
2468:
1.493 albertel 2469: sub removeuploadedurl {
1.984 neumanie 2470: my ($url)=@_;
2471: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2472: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2473: }
2474:
2475: sub removeuserfile {
2476: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2477: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2478: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2479: if ($result eq 'ok') {
1.798 raeburn 2480: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2481: my $metafile = $fname.'.meta';
2482: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2483: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2484: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2485: my $sqlresult =
1.823 albertel 2486: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2487: 'portfolio_metadata',$group,
2488: 'delete');
1.798 raeburn 2489: }
2490: }
2491: return $result;
1.257 www 2492: }
1.15 www 2493:
1.530 albertel 2494: sub mkdiruserfile {
2495: my ($docuname,$docudom,$dir)=@_;
2496: my $home=&homeserver($docuname,$docudom);
2497: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2498: }
2499:
1.531 albertel 2500: sub renameuserfile {
2501: my ($docuname,$docudom,$old,$new)=@_;
2502: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2503: my $result = &reply("renameuserfile:$docudom:$docuname:".
2504: &escape("$old").':'.&escape("$new"),$home);
2505: if ($result eq 'ok') {
2506: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2507: my $oldmeta = $old.'.meta';
2508: my $newmeta = $new.'.meta';
2509: my $metaresult =
2510: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2511: my $url = "/uploaded/$docudom/$docuname/$old";
2512: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2513: my $sqlresult =
1.823 albertel 2514: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2515: 'portfolio_metadata',$group,
2516: 'delete');
1.798 raeburn 2517: }
2518: }
2519: return $result;
1.531 albertel 2520: }
2521:
1.14 www 2522: # ------------------------------------------------------------------------- Log
2523:
2524: sub log {
2525: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2526: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2527: }
2528:
2529: # ------------------------------------------------------------------ Course Log
1.352 www 2530: #
2531: # This routine flushes several buffers of non-mission-critical nature
2532: #
1.157 www 2533:
2534: sub flushcourselogs {
1.352 www 2535: &logthis('Flushing log buffers');
2536: #
2537: # course logs
2538: # This is a log of all transactions in a course, which can be used
2539: # for data mining purposes
2540: #
2541: # It also collects the courseid database, which lists last transaction
2542: # times and course titles for all courseids
2543: #
2544: my %courseidbuffer=();
1.921 raeburn 2545: foreach my $crsid (keys(%courselogs)) {
1.352 www 2546: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2547: &escape($courselogs{$crsid}),
2548: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2549: delete $courselogs{$crsid};
2550: } else {
2551: &logthis('Failed to flush log buffer for '.$crsid);
2552: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2553: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2554: " exceeded maximum size, deleting.</font>");
2555: delete $courselogs{$crsid};
2556: }
1.352 www 2557: }
1.920 raeburn 2558: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2559: 'description' => $coursedescrbuf{$crsid},
2560: 'inst_code' => $courseinstcodebuf{$crsid},
2561: 'type' => $coursetypebuf{$crsid},
2562: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2563: };
1.191 harris41 2564: }
1.352 www 2565: #
2566: # Write course id database (reverse lookup) to homeserver of courses
2567: # Is used in pickcourse
2568: #
1.840 albertel 2569: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2570: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2571: $courseidbuffer{$crs_home},
2572: $crs_home,'timeonly');
1.352 www 2573: }
2574: #
2575: # File accesses
2576: # Writes to the dynamic metadata of resources to get hit counts, etc.
2577: #
1.449 matthew 2578: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2579: if ($entry =~ /___count$/) {
2580: my ($dom,$name);
1.807 albertel 2581: ($dom,$name,undef)=
1.811 albertel 2582: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2583: if (! defined($dom) || $dom eq '' ||
2584: ! defined($name) || $name eq '') {
1.620 albertel 2585: my $cid = $env{'request.course.id'};
2586: $dom = $env{'request.'.$cid.'.domain'};
2587: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2588: }
1.450 matthew 2589: my $value = $accesshash{$entry};
2590: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2591: my %temphash=($url => $value);
1.449 matthew 2592: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2593: if ($result eq 'ok') {
2594: delete $accesshash{$entry};
2595: } elsif ($result eq 'unknown_cmd') {
2596: # Target server has old code running on it.
1.450 matthew 2597: my %temphash=($entry => $value);
1.449 matthew 2598: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2599: delete $accesshash{$entry};
2600: }
2601: }
2602: } else {
1.811 albertel 2603: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2604: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2605: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2606: delete $accesshash{$entry};
2607: }
1.185 www 2608: }
1.191 harris41 2609: }
1.352 www 2610: #
2611: # Roles
2612: # Reverse lookup of user roles for course faculty/staff and co-authorship
2613: #
1.800 albertel 2614: foreach my $entry (keys(%userrolehash)) {
1.351 www 2615: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2616: split(/\:/,$entry);
2617: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2618: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2619: $rudom,$runame) eq 'ok') {
2620: delete $userrolehash{$entry};
2621: }
2622: }
1.662 raeburn 2623: #
2624: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2625: #
2626: my %domrolebuffer = ();
1.1000 raeburn 2627: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2628: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2629: if ($domrolebuffer{$rudom}) {
2630: $domrolebuffer{$rudom}.='&'.&escape($entry).
2631: '='.&escape($domainrolehash{$entry});
2632: } else {
2633: $domrolebuffer{$rudom}.=&escape($entry).
2634: '='.&escape($domainrolehash{$entry});
2635: }
2636: delete $domainrolehash{$entry};
2637: }
2638: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2639: my %servers = &get_servers($dom,'library');
2640: foreach my $tryserver (keys(%servers)) {
2641: unless (&reply('domroleput:'.$dom.':'.
2642: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2643: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2644: }
1.662 raeburn 2645: }
2646: }
1.186 www 2647: $dumpcount++;
1.157 www 2648: }
2649:
2650: sub courselog {
2651: my $what=shift;
1.158 www 2652: $what=time.':'.$what;
1.620 albertel 2653: unless ($env{'request.course.id'}) { return ''; }
2654: $coursedombuf{$env{'request.course.id'}}=
2655: $env{'course.'.$env{'request.course.id'}.'.domain'};
2656: $coursenumbuf{$env{'request.course.id'}}=
2657: $env{'course.'.$env{'request.course.id'}.'.num'};
2658: $coursehombuf{$env{'request.course.id'}}=
2659: $env{'course.'.$env{'request.course.id'}.'.home'};
2660: $coursedescrbuf{$env{'request.course.id'}}=
2661: $env{'course.'.$env{'request.course.id'}.'.description'};
2662: $courseinstcodebuf{$env{'request.course.id'}}=
2663: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2664: $courseownerbuf{$env{'request.course.id'}}=
2665: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2666: $coursetypebuf{$env{'request.course.id'}}=
2667: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2668: if (defined $courselogs{$env{'request.course.id'}}) {
2669: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2670: } else {
1.620 albertel 2671: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2672: }
1.620 albertel 2673: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2674: &flushcourselogs();
2675: }
1.158 www 2676: }
2677:
2678: sub courseacclog {
2679: my $fnsymb=shift;
1.620 albertel 2680: unless ($env{'request.course.id'}) { return ''; }
2681: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2682: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2683: $what.=':POST';
1.583 matthew 2684: # FIXME: Probably ought to escape things....
1.800 albertel 2685: foreach my $key (keys(%env)) {
2686: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2687: my $formitem = $1;
2688: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2689: $what.=':'.$formitem.'='.$env{$key};
2690: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2691: $what.=':'.$formitem.'='.$env{$key};
2692: }
1.158 www 2693: }
1.191 harris41 2694: }
1.583 matthew 2695: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2696: # FIXME: We should not be depending on a form parameter that someone
2697: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2698: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2699: $what.= ':POST';
2700: # FIXME: Probably ought to escape things....
2701: foreach my $element ('courseexp','crsfulltext','crsrelated',
2702: 'crsdiscuss') {
1.620 albertel 2703: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2704: }
2705: }
1.158 www 2706: }
2707: &courselog($what);
1.149 www 2708: }
2709:
1.185 www 2710: sub countacc {
2711: my $url=&declutter(shift);
1.458 matthew 2712: return if (! defined($url) || $url eq '');
1.620 albertel 2713: unless ($env{'request.course.id'}) { return ''; }
2714: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2715: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2716: $accesshash{$key}++;
1.185 www 2717: }
1.349 www 2718:
1.361 www 2719: sub linklog {
2720: my ($from,$to)=@_;
2721: $from=&declutter($from);
2722: $to=&declutter($to);
2723: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2724: $accesshash{$to.'___'.$from.'___goto'}=1;
2725: }
2726:
1.349 www 2727: sub userrolelog {
2728: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2729: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2730: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2731: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2732: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2733: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2734: $userrolehash
2735: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2736: =$tend.':'.$tstart;
1.662 raeburn 2737: }
1.898 albertel 2738: if (($env{'request.role'} =~ /dc\./) &&
2739: (($trole=~/^au/) || ($trole=~/^in/) ||
2740: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2741: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2742: ($trole=~/^co/))) {
1.898 albertel 2743: $userrolehash
2744: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2745: =$tend.':'.$tstart;
2746: }
1.662 raeburn 2747: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2748: ($trole=~/^li/) || ($trole=~/^li/) ||
2749: ($trole=~/^au/) || ($trole=~/^dg/) ||
2750: ($trole=~/^sc/)) {
2751: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2752: $domainrolehash
2753: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2754: = $tend.':'.$tstart;
2755: }
1.351 www 2756: }
2757:
1.957 raeburn 2758: sub courserolelog {
2759: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2760: if (($trole eq 'cc') || ($trole eq 'in') ||
2761: ($trole eq 'ep') || ($trole eq 'ad') ||
2762: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2763: ($trole=~/^cr/) || ($trole eq 'gr') ||
2764: ($trole eq 'co')) {
1.957 raeburn 2765: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2766: my $cdom = $1;
2767: my $cnum = $2;
2768: my $sec = $3;
2769: my $namespace = 'rolelog';
2770: my %storehash = (
2771: role => $trole,
2772: start => $tstart,
2773: end => $tend,
2774: selfenroll => $selfenroll,
2775: context => $context,
2776: );
2777: if ($trole eq 'gr') {
2778: $namespace = 'groupslog';
2779: $storehash{'group'} = $sec;
2780: } else {
2781: $storehash{'section'} = $sec;
2782: }
2783: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2784: if (($trole ne 'st') || ($sec ne '')) {
2785: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2786: }
1.957 raeburn 2787: }
2788: }
2789: return;
2790: }
2791:
1.351 www 2792: sub get_course_adv_roles {
1.948 raeburn 2793: my ($cid,$codes) = @_;
1.620 albertel 2794: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2795: my %coursehash=&coursedescription($cid);
1.988 raeburn 2796: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2797: my %nothide=();
1.800 albertel 2798: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2799: if ($user !~ /:/) {
2800: $nothide{join(':',split(/[\@]/,$user))}=1;
2801: } else {
2802: $nothide{$user}=1;
2803: }
1.470 www 2804: }
1.351 www 2805: my %returnhash=();
2806: my %dumphash=
2807: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2808: my $now=time;
1.997 raeburn 2809: my %privileged;
1.1000 raeburn 2810: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2811: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2812: if (($tstart) && ($tstart<0)) { next; }
2813: if (($tend) && ($tend<$now)) { next; }
2814: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2815: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2816: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2817: unless (ref($privileged{$domain}) eq 'HASH') {
2818: my %dompersonnel =
1.998 raeburn 2819: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2820: $privileged{$domain} = {};
2821: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2822: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2823: foreach my $user (keys(%{$dompersonnel{$server}})) {
2824: my ($trole,$uname,$udom) = split(/:/,$user);
2825: $privileged{$udom}{$uname} = 1;
2826: }
2827: }
2828: }
2829: }
2830: if ((exists($privileged{$domain}{$username})) &&
2831: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2832: if ($role eq 'cr') { next; }
1.948 raeburn 2833: if ($codes) {
2834: if ($section) { $role .= ':'.$section; }
2835: if ($returnhash{$role}) {
2836: $returnhash{$role}.=','.$username.':'.$domain;
2837: } else {
2838: $returnhash{$role}=$username.':'.$domain;
2839: }
1.351 www 2840: } else {
1.988 raeburn 2841: my $key=&plaintext($role,$crstype);
1.973 bisitz 2842: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2843: if ($returnhash{$key}) {
2844: $returnhash{$key}.=','.$username.':'.$domain;
2845: } else {
2846: $returnhash{$key}=$username.':'.$domain;
2847: }
1.351 www 2848: }
1.948 raeburn 2849: }
1.400 www 2850: return %returnhash;
2851: }
2852:
2853: sub get_my_roles {
1.937 raeburn 2854: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2855: unless (defined($uname)) { $uname=$env{'user.name'}; }
2856: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2857: my (%dumphash,%nothide);
1.858 raeburn 2858: if ($context eq 'userroles') {
2859: %dumphash = &dump('roles',$udom,$uname);
2860: } else {
2861: %dumphash=
1.400 www 2862: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2863: if ($hidepriv) {
2864: my %coursehash=&coursedescription($udom.'_'.$uname);
2865: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2866: if ($user !~ /:/) {
2867: $nothide{join(':',split(/[\@]/,$user))} = 1;
2868: } else {
2869: $nothide{$user} = 1;
2870: }
2871: }
2872: }
1.858 raeburn 2873: }
1.400 www 2874: my %returnhash=();
2875: my $now=time;
1.999 raeburn 2876: my %privileged;
1.800 albertel 2877: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2878: my ($role,$tend,$tstart);
2879: if ($context eq 'userroles') {
2880: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2881: } else {
2882: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2883: }
1.400 www 2884: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2885: my $status = 'active';
1.939 raeburn 2886: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2887: $status = 'previous';
2888: }
2889: if (($tstart) && ($now<$tstart)) {
2890: $status = 'future';
2891: }
2892: if (ref($types) eq 'ARRAY') {
2893: if (!grep(/^\Q$status\E$/,@{$types})) {
2894: next;
2895: }
2896: } else {
2897: if ($status ne 'active') {
2898: next;
2899: }
2900: }
1.867 raeburn 2901: my ($rolecode,$username,$domain,$section,$area);
2902: if ($context eq 'userroles') {
2903: ($area,$rolecode) = split(/_/,$entry);
2904: (undef,$domain,$username,$section) = split(/\//,$area);
2905: } else {
2906: ($role,$username,$domain,$section) = split(/\:/,$entry);
2907: }
1.832 raeburn 2908: if (ref($roledoms) eq 'ARRAY') {
2909: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2910: next;
2911: }
2912: }
2913: if (ref($roles) eq 'ARRAY') {
2914: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2915: if ($role =~ /^cr\//) {
2916: if (!grep(/^cr$/,@{$roles})) {
2917: next;
2918: }
2919: } else {
2920: next;
2921: }
1.832 raeburn 2922: }
1.867 raeburn 2923: }
1.937 raeburn 2924: if ($hidepriv) {
1.999 raeburn 2925: if ($context eq 'userroles') {
2926: if ((&privileged($username,$domain)) &&
2927: (!$nothide{$username.':'.$domain})) {
2928: next;
2929: }
2930: } else {
2931: unless (ref($privileged{$domain}) eq 'HASH') {
2932: my %dompersonnel =
2933: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2934: $privileged{$domain} = {};
2935: if (keys(%dompersonnel)) {
2936: foreach my $server (keys(%dompersonnel)) {
2937: if (ref($dompersonnel{$server}) eq 'HASH') {
2938: foreach my $user (keys(%{$dompersonnel{$server}})) {
2939: my ($trole,$uname,$udom) = split(/:/,$user);
2940: $privileged{$udom}{$uname} = $trole;
2941: }
2942: }
2943: }
2944: }
2945: }
2946: if (exists($privileged{$domain}{$username})) {
2947: if (!$nothide{$username.':'.$domain}) {
2948: next;
2949: }
2950: }
1.937 raeburn 2951: }
2952: }
1.933 raeburn 2953: if ($withsec) {
2954: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2955: $tstart.':'.$tend;
2956: } else {
2957: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2958: }
1.832 raeburn 2959: }
1.373 www 2960: return %returnhash;
1.399 www 2961: }
2962:
2963: # ----------------------------------------------------- Frontpage Announcements
2964: #
2965: #
2966:
2967: sub postannounce {
2968: my ($server,$text)=@_;
1.844 albertel 2969: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2970: unless ($text=~/\w/) { $text=''; }
2971: return &reply('setannounce:'.&escape($text),$server);
2972: }
2973:
2974: sub getannounce {
1.448 albertel 2975:
2976: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2977: my $announcement='';
1.800 albertel 2978: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2979: close($fh);
1.399 www 2980: if ($announcement=~/\w/) {
2981: return
2982: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2983: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2984: } else {
2985: return '';
2986: }
2987: } else {
2988: return '';
2989: }
1.351 www 2990: }
1.353 www 2991:
2992: # ---------------------------------------------------------- Course ID routines
2993: # Deal with domain's nohist_courseid.db files
2994: #
2995:
2996: sub courseidput {
1.921 raeburn 2997: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 2998: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 2999: my $outcome;
3000: if ($caller eq 'timeonly') {
3001: my $cids = '';
3002: foreach my $item (keys(%$storehash)) {
3003: $cids.=&escape($item).'&';
3004: }
3005: $cids=~s/\&$//;
3006: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3007: $coursehome);
3008: } else {
3009: my $items = '';
3010: foreach my $item (keys(%$storehash)) {
3011: $items.= &escape($item).'='.
3012: &freeze_escape($$storehash{$item}).'&';
3013: }
3014: $items=~s/\&$//;
3015: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3016: $coursehome);
1.918 raeburn 3017: }
3018: if ($outcome eq 'unknown_cmd') {
3019: my $what;
3020: foreach my $cid (keys(%$storehash)) {
3021: $what .= &escape($cid).'=';
1.921 raeburn 3022: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3023: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3024: }
3025: $what =~ s/\:$/&/;
3026: }
3027: $what =~ s/\&$//;
3028: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3029: } else {
3030: return $outcome;
3031: }
1.353 www 3032: }
3033:
3034: sub courseiddump {
1.921 raeburn 3035: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3036: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3037: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3038: $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
1.918 raeburn 3039: my $as_hash = 1;
3040: my %returnhash;
3041: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3042: my %libserv = &all_library();
3043: foreach my $tryserver (keys(%libserv)) {
3044: if ( ( $hostidflag == 1
3045: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3046: || (!defined($hostidflag)) ) {
3047:
1.918 raeburn 3048: if (($domfilter eq '') ||
3049: (&host_domain($tryserver) eq $domfilter)) {
3050: my $rep =
3051: &reply('courseiddump:'.&host_domain($tryserver).':'.
3052: $sincefilter.':'.&escape($descfilter).':'.
3053: &escape($instcodefilter).':'.&escape($ownerfilter).
3054: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3055: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3056: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3057: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3058: &escape($cc_clone).':'.$cloneonly.':'.
3059: &escape($createdbefore).':'.&escape($createdafter).':'.
3060: &escape($creationcontext),$tryserver);
1.918 raeburn 3061: my @pairs=split(/\&/,$rep);
3062: foreach my $item (@pairs) {
3063: my ($key,$value)=split(/\=/,$item,2);
3064: $key = &unescape($key);
3065: next if ($key =~ /^error: 2 /);
3066: my $result = &thaw_unescape($value);
3067: if (ref($result) eq 'HASH') {
3068: $returnhash{$key}=$result;
3069: } else {
1.921 raeburn 3070: my @responses = split(/:/,$value);
3071: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3072: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3073: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3074: }
1.1008 raeburn 3075: }
1.353 www 3076: }
3077: }
3078: }
3079: }
3080: return %returnhash;
3081: }
3082:
1.1055 raeburn 3083: sub courselastaccess {
3084: my ($cdom,$cnum,$hostidref) = @_;
3085: my %returnhash;
3086: if ($cdom && $cnum) {
3087: my $chome = &homeserver($cnum,$cdom);
3088: if ($chome ne 'no_host') {
3089: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3090: &extract_lastaccess(\%returnhash,$rep);
3091: }
3092: } else {
3093: if (!$cdom) { $cdom=''; }
3094: my %libserv = &all_library();
3095: foreach my $tryserver (keys(%libserv)) {
3096: if (ref($hostidref) eq 'ARRAY') {
3097: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3098: }
3099: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3100: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3101: &extract_lastaccess(\%returnhash,$rep);
3102: }
3103: }
3104: }
3105: return %returnhash;
3106: }
3107:
3108: sub extract_lastaccess {
3109: my ($returnhash,$rep) = @_;
3110: if (ref($returnhash) eq 'HASH') {
3111: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3112: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3113: $rep eq '') {
3114: my @pairs=split(/\&/,$rep);
3115: foreach my $item (@pairs) {
3116: my ($key,$value)=split(/\=/,$item,2);
3117: $key = &unescape($key);
3118: next if ($key =~ /^error: 2 /);
3119: $returnhash->{$key} = &thaw_unescape($value);
3120: }
3121: }
3122: }
3123: return;
3124: }
3125:
1.658 raeburn 3126: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3127:
3128: sub dcmailput {
1.685 raeburn 3129: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3130: my $status = &Apache::lonnet::critical(
1.740 www 3131: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3132: &escape($message),$server);
1.662 raeburn 3133: return $status;
3134: }
3135:
1.658 raeburn 3136: sub dcmaildump {
3137: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3138: my %returnhash=();
1.846 albertel 3139:
3140: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3141: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3142: &escape($enddate).':';
3143: my @esc_senders=map { &escape($_)} @$senders;
3144: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3145: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3146: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3147: if (($key) && ($value)) {
3148: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3149: }
3150: }
3151: }
3152: return %returnhash;
3153: }
1.662 raeburn 3154: # ---------------------------------------------------------- Domain roles
3155:
3156: sub get_domain_roles {
3157: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3158: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3159: $startdate = '.';
3160: }
1.1018 raeburn 3161: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3162: $enddate = '.';
3163: }
1.922 raeburn 3164: my $rolelist;
3165: if (ref($roles) eq 'ARRAY') {
3166: $rolelist = join(':',@{$roles});
3167: }
1.662 raeburn 3168: my %personnel = ();
1.841 albertel 3169:
3170: my %servers = &get_servers($dom,'library');
3171: foreach my $tryserver (keys(%servers)) {
3172: %{$personnel{$tryserver}}=();
3173: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3174: &escape($startdate).':'.
3175: &escape($enddate).':'.
3176: &escape($rolelist), $tryserver))) {
3177: my ($key,$value) = split(/\=/,$line,2);
3178: if (($key) && ($value)) {
3179: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3180: }
3181: }
1.662 raeburn 3182: }
3183: return %personnel;
3184: }
1.658 raeburn 3185:
1.1057 www 3186: # ----------------------------------------------------------- Interval timing
1.149 www 3187:
1.504 albertel 3188: sub get_first_access {
3189: my ($type,$argsymb)=@_;
1.790 albertel 3190: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3191: if ($argsymb) { $symb=$argsymb; }
3192: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3193: if ($type eq 'course') {
3194: $res='course';
3195: } elsif ($type eq 'map') {
1.588 albertel 3196: $res=&symbread($map);
3197: } else {
3198: $res=$symb;
3199: }
3200: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3201: return $times{"$courseid\0$res"};
1.504 albertel 3202: }
3203:
3204: sub set_first_access {
3205: my ($type)=@_;
1.790 albertel 3206: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3207: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3208: if ($type eq 'course') {
3209: $res='course';
3210: } elsif ($type eq 'map') {
1.588 albertel 3211: $res=&symbread($map);
3212: } else {
3213: $res=$symb;
3214: }
3215: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3216: if (!$firstaccess) {
1.588 albertel 3217: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3218: }
3219: return 'already_set';
1.504 albertel 3220: }
3221:
1.110 www 3222: # --------------------------------------------- Set Expire Date for Spreadsheet
3223:
3224: sub expirespread {
3225: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3226: my $cid=$env{'request.course.id'};
1.110 www 3227: if ($cid) {
3228: my $now=time;
3229: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3230: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3231: $env{'course.'.$cid.'.num'}.
1.110 www 3232: ':nohist_expirationdates:'.
3233: &escape($key).'='.$now,
1.620 albertel 3234: $env{'course.'.$cid.'.home'})
1.110 www 3235: }
3236: return 'ok';
1.14 www 3237: }
3238:
1.109 www 3239: # ----------------------------------------------------- Devalidate Spreadsheets
3240:
3241: sub devalidate {
1.325 www 3242: my ($symb,$uname,$udom)=@_;
1.620 albertel 3243: my $cid=$env{'request.course.id'};
1.109 www 3244: if ($cid) {
1.391 matthew 3245: # delete the stored spreadsheets for
3246: # - the student level sheet of this user in course's homespace
3247: # - the assessment level sheet for this resource
3248: # for this user in user's homespace
1.553 albertel 3249: # - current conditional state info
1.325 www 3250: my $key=$uname.':'.$udom.':';
1.109 www 3251: my $status=
1.299 matthew 3252: &del('nohist_calculatedsheets',
1.391 matthew 3253: [$key.'studentcalc:'],
1.620 albertel 3254: $env{'course.'.$cid.'.domain'},
3255: $env{'course.'.$cid.'.num'})
1.133 albertel 3256: .' '.
3257: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3258: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3259: unless ($status eq 'ok ok') {
3260: &logthis('Could not devalidate spreadsheet '.
1.325 www 3261: $uname.' at '.$udom.' for '.
1.109 www 3262: $symb.': '.$status);
1.133 albertel 3263: }
1.553 albertel 3264: &delenv('user.state.'.$cid);
1.109 www 3265: }
3266: }
3267:
1.265 albertel 3268: sub get_scalar {
3269: my ($string,$end) = @_;
3270: my $value;
3271: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3272: $value = $1;
3273: } elsif ($$string =~ s/^([^&]*?)&//) {
3274: $value = $1;
3275: }
3276: return &unescape($value);
3277: }
3278:
3279: sub array2str {
3280: my (@array) = @_;
3281: my $result=&arrayref2str(\@array);
3282: $result=~s/^__ARRAY_REF__//;
3283: $result=~s/__END_ARRAY_REF__$//;
3284: return $result;
3285: }
3286:
1.204 albertel 3287: sub arrayref2str {
3288: my ($arrayref) = @_;
1.265 albertel 3289: my $result='__ARRAY_REF__';
1.204 albertel 3290: foreach my $elem (@$arrayref) {
1.265 albertel 3291: if(ref($elem) eq 'ARRAY') {
3292: $result.=&arrayref2str($elem).'&';
3293: } elsif(ref($elem) eq 'HASH') {
3294: $result.=&hashref2str($elem).'&';
3295: } elsif(ref($elem)) {
3296: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3297: } else {
3298: $result.=&escape($elem).'&';
3299: }
3300: }
3301: $result=~s/\&$//;
1.265 albertel 3302: $result .= '__END_ARRAY_REF__';
1.204 albertel 3303: return $result;
3304: }
3305:
1.168 albertel 3306: sub hash2str {
1.204 albertel 3307: my (%hash) = @_;
3308: my $result=&hashref2str(\%hash);
1.265 albertel 3309: $result=~s/^__HASH_REF__//;
3310: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3311: return $result;
3312: }
3313:
3314: sub hashref2str {
3315: my ($hashref)=@_;
1.265 albertel 3316: my $result='__HASH_REF__';
1.800 albertel 3317: foreach my $key (sort(keys(%$hashref))) {
3318: if (ref($key) eq 'ARRAY') {
3319: $result.=&arrayref2str($key).'=';
3320: } elsif (ref($key) eq 'HASH') {
3321: $result.=&hashref2str($key).'=';
3322: } elsif (ref($key)) {
1.265 albertel 3323: $result.='=';
1.800 albertel 3324: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3325: } else {
1.800 albertel 3326: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3327: }
3328:
1.800 albertel 3329: if(ref($hashref->{$key}) eq 'ARRAY') {
3330: $result.=&arrayref2str($hashref->{$key}).'&';
3331: } elsif(ref($hashref->{$key}) eq 'HASH') {
3332: $result.=&hashref2str($hashref->{$key}).'&';
3333: } elsif(ref($hashref->{$key})) {
1.265 albertel 3334: $result.='&';
1.800 albertel 3335: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3336: } else {
1.800 albertel 3337: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3338: }
3339: }
1.168 albertel 3340: $result=~s/\&$//;
1.265 albertel 3341: $result .= '__END_HASH_REF__';
1.168 albertel 3342: return $result;
3343: }
3344:
3345: sub str2hash {
1.265 albertel 3346: my ($string)=@_;
3347: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3348: return %$hash;
3349: }
3350:
3351: sub str2hashref {
1.168 albertel 3352: my ($string) = @_;
1.265 albertel 3353:
3354: my %hash;
3355:
3356: if($string !~ /^__HASH_REF__/) {
3357: if (! ($string eq '' || !defined($string))) {
3358: $hash{'error'}='Not hash reference';
3359: }
3360: return (\%hash, $string);
3361: }
3362:
3363: $string =~ s/^__HASH_REF__//;
3364:
3365: while($string !~ /^__END_HASH_REF__/) {
3366: #key
3367: my $key='';
3368: if($string =~ /^__HASH_REF__/) {
3369: ($key, $string)=&str2hashref($string);
3370: if(defined($key->{'error'})) {
3371: $hash{'error'}='Bad data';
3372: return (\%hash, $string);
3373: }
3374: } elsif($string =~ /^__ARRAY_REF__/) {
3375: ($key, $string)=&str2arrayref($string);
3376: if($key->[0] eq 'Array reference error') {
3377: $hash{'error'}='Bad data';
3378: return (\%hash, $string);
3379: }
3380: } else {
3381: $string =~ s/^(.*?)=//;
1.267 albertel 3382: $key=&unescape($1);
1.265 albertel 3383: }
3384: $string =~ s/^=//;
3385:
3386: #value
3387: my $value='';
3388: if($string =~ /^__HASH_REF__/) {
3389: ($value, $string)=&str2hashref($string);
3390: if(defined($value->{'error'})) {
3391: $hash{'error'}='Bad data';
3392: return (\%hash, $string);
3393: }
3394: } elsif($string =~ /^__ARRAY_REF__/) {
3395: ($value, $string)=&str2arrayref($string);
3396: if($value->[0] eq 'Array reference error') {
3397: $hash{'error'}='Bad data';
3398: return (\%hash, $string);
3399: }
3400: } else {
3401: $value=&get_scalar(\$string,'__END_HASH_REF__');
3402: }
3403: $string =~ s/^&//;
3404:
3405: $hash{$key}=$value;
1.204 albertel 3406: }
1.265 albertel 3407:
3408: $string =~ s/^__END_HASH_REF__//;
3409:
3410: return (\%hash, $string);
1.204 albertel 3411: }
3412:
3413: sub str2array {
1.265 albertel 3414: my ($string)=@_;
3415: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3416: return @$array;
3417: }
3418:
3419: sub str2arrayref {
1.204 albertel 3420: my ($string) = @_;
1.265 albertel 3421: my @array;
3422:
3423: if($string !~ /^__ARRAY_REF__/) {
3424: if (! ($string eq '' || !defined($string))) {
3425: $array[0]='Array reference error';
3426: }
3427: return (\@array, $string);
3428: }
3429:
3430: $string =~ s/^__ARRAY_REF__//;
3431:
3432: while($string !~ /^__END_ARRAY_REF__/) {
3433: my $value='';
3434: if($string =~ /^__HASH_REF__/) {
3435: ($value, $string)=&str2hashref($string);
3436: if(defined($value->{'error'})) {
3437: $array[0] ='Array reference error';
3438: return (\@array, $string);
3439: }
3440: } elsif($string =~ /^__ARRAY_REF__/) {
3441: ($value, $string)=&str2arrayref($string);
3442: if($value->[0] eq 'Array reference error') {
3443: $array[0] ='Array reference error';
3444: return (\@array, $string);
3445: }
3446: } else {
3447: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3448: }
3449: $string =~ s/^&//;
3450:
3451: push(@array, $value);
1.191 harris41 3452: }
1.265 albertel 3453:
3454: $string =~ s/^__END_ARRAY_REF__//;
3455:
3456: return (\@array, $string);
1.168 albertel 3457: }
3458:
1.167 albertel 3459: # -------------------------------------------------------------------Temp Store
3460:
1.168 albertel 3461: sub tmpreset {
3462: my ($symb,$namespace,$domain,$stuname) = @_;
3463: if (!$symb) {
3464: $symb=&symbread();
1.620 albertel 3465: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3466: }
3467: $symb=escape($symb);
3468:
1.620 albertel 3469: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3470: $namespace=~s/\//\_/g;
3471: $namespace=~s/\W//g;
3472:
1.620 albertel 3473: if (!$domain) { $domain=$env{'user.domain'}; }
3474: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3475: if ($domain eq 'public' && $stuname eq 'public') {
3476: $stuname=$ENV{'REMOTE_ADDR'};
3477: }
1.168 albertel 3478: my $path=$perlvar{'lonDaemons'}.'/tmp';
3479: my %hash;
3480: if (tie(%hash,'GDBM_File',
3481: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3482: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3483: foreach my $key (keys(%hash)) {
1.180 albertel 3484: if ($key=~ /:$symb/) {
1.168 albertel 3485: delete($hash{$key});
3486: }
3487: }
3488: }
3489: }
3490:
1.167 albertel 3491: sub tmpstore {
1.168 albertel 3492: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3493:
3494: if (!$symb) {
3495: $symb=&symbread();
1.620 albertel 3496: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3497: }
3498: $symb=escape($symb);
3499:
3500: if (!$namespace) {
3501: # I don't think we would ever want to store this for a course.
3502: # it seems this will only be used if we don't have a course.
1.620 albertel 3503: #$namespace=$env{'request.course.id'};
1.168 albertel 3504: #if (!$namespace) {
1.620 albertel 3505: $namespace=$env{'request.state'};
1.168 albertel 3506: #}
3507: }
3508: $namespace=~s/\//\_/g;
3509: $namespace=~s/\W//g;
1.620 albertel 3510: if (!$domain) { $domain=$env{'user.domain'}; }
3511: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3512: if ($domain eq 'public' && $stuname eq 'public') {
3513: $stuname=$ENV{'REMOTE_ADDR'};
3514: }
1.168 albertel 3515: my $now=time;
3516: my %hash;
3517: my $path=$perlvar{'lonDaemons'}.'/tmp';
3518: if (tie(%hash,'GDBM_File',
3519: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3520: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3521: $hash{"version:$symb"}++;
3522: my $version=$hash{"version:$symb"};
3523: my $allkeys='';
3524: foreach my $key (keys(%$storehash)) {
3525: $allkeys.=$key.':';
1.591 albertel 3526: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3527: }
3528: $hash{"$version:$symb:timestamp"}=$now;
3529: $allkeys.='timestamp';
3530: $hash{"$version:keys:$symb"}=$allkeys;
3531: if (untie(%hash)) {
3532: return 'ok';
3533: } else {
3534: return "error:$!";
3535: }
3536: } else {
3537: return "error:$!";
3538: }
3539: }
1.167 albertel 3540:
1.168 albertel 3541: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3542:
1.168 albertel 3543: sub tmprestore {
3544: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3545:
1.168 albertel 3546: if (!$symb) {
3547: $symb=&symbread();
1.620 albertel 3548: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3549: }
3550: $symb=escape($symb);
3551:
1.620 albertel 3552: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3553:
1.620 albertel 3554: if (!$domain) { $domain=$env{'user.domain'}; }
3555: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3556: if ($domain eq 'public' && $stuname eq 'public') {
3557: $stuname=$ENV{'REMOTE_ADDR'};
3558: }
1.168 albertel 3559: my %returnhash;
3560: $namespace=~s/\//\_/g;
3561: $namespace=~s/\W//g;
3562: my %hash;
3563: my $path=$perlvar{'lonDaemons'}.'/tmp';
3564: if (tie(%hash,'GDBM_File',
3565: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3566: &GDBM_READER(),0640)) {
1.168 albertel 3567: my $version=$hash{"version:$symb"};
3568: $returnhash{'version'}=$version;
3569: my $scope;
3570: for ($scope=1;$scope<=$version;$scope++) {
3571: my $vkeys=$hash{"$scope:keys:$symb"};
3572: my @keys=split(/:/,$vkeys);
3573: my $key;
3574: $returnhash{"$scope:keys"}=$vkeys;
3575: foreach $key (@keys) {
1.591 albertel 3576: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3577: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3578: }
3579: }
1.168 albertel 3580: if (!(untie(%hash))) {
3581: return "error:$!";
3582: }
3583: } else {
3584: return "error:$!";
3585: }
3586: return %returnhash;
1.167 albertel 3587: }
3588:
1.9 www 3589: # ----------------------------------------------------------------------- Store
3590:
3591: sub store {
1.124 www 3592: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3593: my $home='';
3594:
1.168 albertel 3595: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3596:
1.213 www 3597: $symb=&symbclean($symb);
1.122 albertel 3598: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3599:
1.620 albertel 3600: if (!$domain) { $domain=$env{'user.domain'}; }
3601: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3602:
3603: &devalidate($symb,$stuname,$domain);
1.109 www 3604:
3605: $symb=escape($symb);
1.187 www 3606: if (!$namespace) {
1.620 albertel 3607: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3608: return '';
3609: }
3610: }
1.620 albertel 3611: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3612:
3613: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3614: $$storehash{'host'}=$perlvar{'lonHostID'};
3615:
1.12 www 3616: my $namevalue='';
1.800 albertel 3617: foreach my $key (keys(%$storehash)) {
3618: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3619: }
1.12 www 3620: $namevalue=~s/\&$//;
1.187 www 3621: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3622: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3623: }
3624:
1.47 www 3625: # -------------------------------------------------------------- Critical Store
3626:
3627: sub cstore {
1.124 www 3628: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3629: my $home='';
3630:
1.168 albertel 3631: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3632:
1.213 www 3633: $symb=&symbclean($symb);
1.122 albertel 3634: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3635:
1.620 albertel 3636: if (!$domain) { $domain=$env{'user.domain'}; }
3637: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3638:
3639: &devalidate($symb,$stuname,$domain);
1.109 www 3640:
3641: $symb=escape($symb);
1.187 www 3642: if (!$namespace) {
1.620 albertel 3643: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3644: return '';
3645: }
3646: }
1.620 albertel 3647: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3648:
3649: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3650: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3651:
1.47 www 3652: my $namevalue='';
1.800 albertel 3653: foreach my $key (keys(%$storehash)) {
3654: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3655: }
1.47 www 3656: $namevalue=~s/\&$//;
1.187 www 3657: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3658: return critical
3659: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3660: }
3661:
1.9 www 3662: # --------------------------------------------------------------------- Restore
3663:
3664: sub restore {
1.124 www 3665: my ($symb,$namespace,$domain,$stuname) = @_;
3666: my $home='';
3667:
1.168 albertel 3668: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3669:
1.122 albertel 3670: if (!$symb) {
3671: unless ($symb=escape(&symbread())) { return ''; }
3672: } else {
1.213 www 3673: $symb=&escape(&symbclean($symb));
1.122 albertel 3674: }
1.188 www 3675: if (!$namespace) {
1.620 albertel 3676: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3677: return '';
3678: }
3679: }
1.620 albertel 3680: if (!$domain) { $domain=$env{'user.domain'}; }
3681: if (!$stuname) { $stuname=$env{'user.name'}; }
3682: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3683: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3684:
1.12 www 3685: my %returnhash=();
1.800 albertel 3686: foreach my $line (split(/\&/,$answer)) {
3687: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3688: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3689: }
1.75 www 3690: my $version;
3691: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3692: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3693: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3694: }
1.75 www 3695: }
1.13 www 3696: return %returnhash;
1.34 www 3697: }
3698:
3699: # ---------------------------------------------------------- Course Description
3700:
3701: sub coursedescription {
1.731 albertel 3702: my ($courseid,$args)=@_;
1.34 www 3703: $courseid=~s/^\///;
1.49 www 3704: $courseid=~s/\_/\//g;
1.34 www 3705: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3706: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3707: my $normalid=$cdomain.'_'.$cnum;
3708: # need to always cache even if we get errors otherwise we keep
3709: # trying and trying and trying to get the course description.
3710: my %envhash=();
3711: my %returnhash=();
1.731 albertel 3712:
3713: my $expiretime=600;
3714: if ($env{'request.course.id'} eq $normalid) {
3715: $expiretime=120;
3716: }
3717:
3718: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3719: if (!$args->{'freshen_cache'}
3720: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3721: foreach my $key (keys(%env)) {
3722: next if ($key !~ /^\Q$prefix\E(.*)/);
3723: my ($setting) = $1;
3724: $returnhash{$setting} = $env{$key};
3725: }
3726: return %returnhash;
3727: }
3728:
3729: # get the data agin
3730: if (!$args->{'one_time'}) {
3731: $envhash{'course.'.$normalid.'.last_cache'}=time;
3732: }
1.811 albertel 3733:
1.34 www 3734: if ($chome ne 'no_host') {
1.302 albertel 3735: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3736: if (!exists($returnhash{'con_lost'})) {
3737: $returnhash{'home'}= $chome;
3738: $returnhash{'domain'} = $cdomain;
3739: $returnhash{'num'} = $cnum;
1.741 raeburn 3740: if (!defined($returnhash{'type'})) {
3741: $returnhash{'type'} = 'Course';
3742: }
1.130 albertel 3743: while (my ($name,$value) = each %returnhash) {
1.53 www 3744: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3745: }
1.270 www 3746: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3747: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3748: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3749: $envhash{'course.'.$normalid.'.home'}=$chome;
3750: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3751: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3752: }
3753: }
1.731 albertel 3754: if (!$args->{'one_time'}) {
1.949 raeburn 3755: &appenv(\%envhash);
1.731 albertel 3756: }
1.302 albertel 3757: return %returnhash;
1.461 www 3758: }
3759:
3760: # -------------------------------------------------See if a user is privileged
3761:
3762: sub privileged {
3763: my ($username,$domain)=@_;
3764: my $rolesdump=&reply("dump:$domain:$username:roles",
3765: &homeserver($username,$domain));
1.1033 raeburn 3766: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3767: ($rolesdump =~ /^error:/)) {
3768: return 0;
3769: }
1.461 www 3770: my $now=time;
3771: if ($rolesdump ne '') {
1.800 albertel 3772: foreach my $entry (split(/&/,$rolesdump)) {
3773: if ($entry!~/^rolesdef_/) {
3774: my ($area,$role)=split(/=/,$entry);
1.461 www 3775: $area=~s/\_\w\w$//;
3776: my ($trole,$tend,$tstart)=split(/_/,$role);
3777: if (($trole eq 'dc') || ($trole eq 'su')) {
3778: my $active=1;
3779: if ($tend) {
3780: if ($tend<$now) { $active=0; }
3781: }
3782: if ($tstart) {
3783: if ($tstart>$now) { $active=0; }
3784: }
3785: if ($active) { return 1; }
3786: }
3787: }
3788: }
3789: }
3790: return 0;
1.9 www 3791: }
1.1 albertel 3792:
1.103 harris41 3793: # -------------------------------------------------------- Get user privileges
1.11 www 3794:
3795: sub rolesinit {
3796: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 3797: my $now=time;
3798: my %userroles = ('user.login.time' => $now);
1.11 www 3799: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033 raeburn 3800: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3801: ($rolesdump =~ /^error:/)) {
3802: return \%userroles;
3803: }
1.11 www 3804: my %allroles=();
1.678 raeburn 3805: my %allgroups=();
3806: my $group_privs;
1.11 www 3807:
3808: if ($rolesdump ne '') {
1.800 albertel 3809: foreach my $entry (split(/&/,$rolesdump)) {
3810: if ($entry!~/^rolesdef_/) {
3811: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3812: $area=~s/\_\w\w$//;
1.678 raeburn 3813: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3814: if ($role=~/^cr/) {
1.807 albertel 3815: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3816: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3817: ($tend,$tstart)=split('_',$trest);
3818: } else {
3819: $trole=$role;
3820: }
1.678 raeburn 3821: } elsif ($role =~ m|^gr/|) {
3822: ($trole,$tend,$tstart) = split(/_/,$role);
3823: ($trole,$group_privs) = split(/\//,$trole);
3824: $group_privs = &unescape($group_privs);
1.587 albertel 3825: } else {
3826: ($trole,$tend,$tstart)=split(/_/,$role);
3827: }
1.743 albertel 3828: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3829: $username);
3830: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3831: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3832: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3833: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3834: my $spec=$trole.'.'.$area;
3835: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3836: if ($trole =~ /^cr\//) {
1.567 raeburn 3837: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3838: } elsif ($trole eq 'gr') {
3839: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3840: } else {
1.567 raeburn 3841: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3842: }
1.12 www 3843: }
1.662 raeburn 3844: }
1.191 harris41 3845: }
1.743 albertel 3846: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3847: $userroles{'user.adv'} = $adv;
3848: $userroles{'user.author'} = $author;
1.620 albertel 3849: $env{'user.adv'}=$adv;
1.11 www 3850: }
1.743 albertel 3851: return \%userroles;
1.11 www 3852: }
3853:
1.567 raeburn 3854: sub set_arearole {
3855: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3856: # log the associated role with the area
3857: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3858: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3859: }
3860:
3861: sub custom_roleprivs {
3862: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3863: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3864: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3865: if (&hostname($homsvr) ne '') {
1.567 raeburn 3866: my ($rdummy,$roledef)=
3867: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3868: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3869: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3870: if (defined($syspriv)) {
1.1043 raeburn 3871: if ($trest =~ /^$match_community$/) {
3872: $syspriv =~ s/bre\&S//;
3873: }
1.567 raeburn 3874: $$allroles{'cm./'}.=':'.$syspriv;
3875: $$allroles{$spec.'./'}.=':'.$syspriv;
3876: }
3877: if ($tdomain ne '') {
3878: if (defined($dompriv)) {
3879: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3880: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3881: }
3882: if (($trest ne '') && (defined($coursepriv))) {
3883: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3884: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3885: }
3886: }
3887: }
3888: }
3889: }
3890:
1.678 raeburn 3891: sub group_roleprivs {
3892: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3893: my $access = 1;
3894: my $now = time;
3895: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3896: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3897: if ($access) {
1.811 albertel 3898: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3899: $$allgroups{$course}{$group} .=':'.$group_privs;
3900: }
3901: }
1.567 raeburn 3902:
3903: sub standard_roleprivs {
3904: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3905: if (defined($pr{$trole.':s'})) {
3906: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3907: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3908: }
3909: if ($tdomain ne '') {
3910: if (defined($pr{$trole.':d'})) {
3911: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3912: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3913: }
3914: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3915: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3916: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3917: }
3918: }
3919: }
3920:
3921: sub set_userprivs {
1.1064 raeburn 3922: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 3923: my $author=0;
3924: my $adv=0;
1.678 raeburn 3925: my %grouproles = ();
3926: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 3927: my @groupkeys;
1.1000 raeburn 3928: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 3929: push(@groupkeys,$role);
3930: }
3931: if (ref($groups_roles) eq 'HASH') {
3932: foreach my $key (keys(%{$groups_roles})) {
3933: unless (grep(/^\Q$key\E$/,@groupkeys)) {
3934: push(@groupkeys,$key);
3935: }
3936: }
3937: }
3938: if (@groupkeys > 0) {
3939: foreach my $role (@groupkeys) {
3940: my ($trole,$area,$sec,$extendedarea);
3941: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
3942: $trole = $1;
3943: $area = $2;
3944: $sec = $3;
3945: $extendedarea = $area.$sec;
3946: if (exists($$allgroups{$area})) {
3947: foreach my $group (keys(%{$$allgroups{$area}})) {
3948: my $spec = $trole.'.'.$extendedarea;
3949: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 3950: $$allgroups{$area}{$group};
1.1064 raeburn 3951: }
1.678 raeburn 3952: }
3953: }
3954: }
3955: }
3956: }
1.800 albertel 3957: foreach my $group (keys(%grouproles)) {
3958: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3959: }
1.800 albertel 3960: foreach my $role (keys(%{$allroles})) {
3961: my %thesepriv;
1.941 raeburn 3962: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3963: foreach my $item (split(/:/,$$allroles{$role})) {
3964: if ($item ne '') {
3965: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3966: if ($restrictions eq '') {
3967: $thesepriv{$privilege}='F';
3968: } elsif ($thesepriv{$privilege} ne 'F') {
3969: $thesepriv{$privilege}.=$restrictions;
3970: }
3971: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3972: }
3973: }
3974: my $thesestr='';
1.800 albertel 3975: foreach my $priv (keys(%thesepriv)) {
3976: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3977: }
3978: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3979: }
3980: return ($author,$adv);
3981: }
3982:
1.994 raeburn 3983: sub role_status {
1.1002 raeburn 3984: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 3985: my @pwhere = ();
3986: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
3987: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
3988: unless (!defined($$role) || $$role eq '') {
3989: $$where=join('.',@pwhere);
3990: $$trolecode=$$role.'.'.$$where;
3991: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
3992: $$tstatus='is';
3993: if ($$tstart && $$tstart>$then) {
3994: $$tstatus='future';
1.1034 raeburn 3995: if ($$tstart<$now) {
3996: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 3997: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 3998: my (%allroles,%allgroups,$group_privs,
3999: %groups_roles,@rolecodes);
1.1002 raeburn 4000: my %userroles = (
4001: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4002: );
1.1064 raeburn 4003: @rolecodes = ('cm');
1.1002 raeburn 4004: my $spec=$$role.'.'.$$where;
4005: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4006: if ($$role =~ /^cr\//) {
4007: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4008: push(@rolecodes,'cr');
1.1002 raeburn 4009: } elsif ($$role eq 'gr') {
1.1064 raeburn 4010: push(@rolecodes,$$role);
1.1002 raeburn 4011: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4012: $env{'user.name'});
1.1064 raeburn 4013: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4014: (undef,my $group_privs) = split(/\//,$trole);
4015: $group_privs = &unescape($group_privs);
4016: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4017: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4018: if (keys(%course_roles) > 0) {
4019: my ($tnum) = ($trest =~ /^($match_courseid)/);
4020: if ($tdomain ne '' && $tnum ne '') {
4021: foreach my $key (keys(%course_roles)) {
4022: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4023: my $crsrole = $1;
4024: my $crssec = $2;
4025: if ($crsrole =~ /^cr/) {
4026: unless (grep(/^cr$/,@rolecodes)) {
4027: push(@rolecodes,'cr');
4028: }
4029: } else {
4030: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4031: push(@rolecodes,$crsrole);
4032: }
4033: }
4034: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4035: if ($crssec ne '') {
4036: $rolekey .= '/'.$crssec;
4037: }
4038: $rolekey .= './';
4039: $groups_roles{$rolekey} = \@rolecodes;
4040: }
4041: }
4042: }
4043: }
1.1002 raeburn 4044: } else {
1.1064 raeburn 4045: push(@rolecodes,$$role);
1.1002 raeburn 4046: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4047: }
1.1064 raeburn 4048: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4049: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4050: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4051: }
4052: }
1.1034 raeburn 4053: $$tstatus = 'is';
1.1002 raeburn 4054: }
1.994 raeburn 4055: }
4056: if ($$tend) {
4057: if ($$tend<$then) {
4058: $$tstatus='expired';
4059: } elsif ($$tend<$now) {
4060: $$tstatus='will_not';
4061: }
4062: }
4063: }
4064: }
4065: }
4066:
4067: sub check_adhoc_privs {
1.1002 raeburn 4068: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4069: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4070: if ($env{$cckey}) {
4071: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4072: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4073: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4074: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4075: }
4076: } else {
4077: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4078: }
4079: }
4080:
4081: sub set_adhoc_privileges {
4082: # role can be cc or ca
4083: my ($dcdom,$pickedcourse,$role) = @_;
4084: my $area = '/'.$dcdom.'/'.$pickedcourse;
4085: my $spec = $role.'.'.$area;
4086: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4087: $env{'user.name'});
4088: my %ccrole = ();
4089: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4090: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4091: &appenv(\%userroles,[$role,'cm']);
4092: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4093: &appenv( {'request.role' => $spec,
4094: 'request.role.domain' => $dcdom,
4095: 'request.course.sec' => ''
4096: }
4097: );
4098: my $tadv=0;
4099: if (&allowed('adv') eq 'F') { $tadv=1; }
4100: &appenv({'request.role.adv' => $tadv});
4101: }
4102:
1.12 www 4103: # --------------------------------------------------------------- get interface
4104:
4105: sub get {
1.131 albertel 4106: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4107: my $items='';
1.800 albertel 4108: foreach my $item (@$storearr) {
4109: $items.=&escape($item).'&';
1.191 harris41 4110: }
1.12 www 4111: $items=~s/\&$//;
1.620 albertel 4112: if (!$udomain) { $udomain=$env{'user.domain'}; }
4113: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4114: my $uhome=&homeserver($uname,$udomain);
4115:
1.133 albertel 4116: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4117: my @pairs=split(/\&/,$rep);
1.273 albertel 4118: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4119: return @pairs;
4120: }
1.15 www 4121: my %returnhash=();
1.42 www 4122: my $i=0;
1.800 albertel 4123: foreach my $item (@$storearr) {
4124: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4125: $i++;
1.191 harris41 4126: }
1.15 www 4127: return %returnhash;
1.27 www 4128: }
4129:
4130: # --------------------------------------------------------------- del interface
4131:
4132: sub del {
1.133 albertel 4133: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4134: my $items='';
1.800 albertel 4135: foreach my $item (@$storearr) {
4136: $items.=&escape($item).'&';
1.191 harris41 4137: }
1.984 neumanie 4138:
1.27 www 4139: $items=~s/\&$//;
1.620 albertel 4140: if (!$udomain) { $udomain=$env{'user.domain'}; }
4141: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4142: my $uhome=&homeserver($uname,$udomain);
4143: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4144: }
4145:
4146: # -------------------------------------------------------------- dump interface
4147:
4148: sub dump {
1.755 albertel 4149: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4150: if (!$udomain) { $udomain=$env{'user.domain'}; }
4151: if (!$uname) { $uname=$env{'user.name'}; }
4152: my $uhome=&homeserver($uname,$udomain);
4153: if ($regexp) {
4154: $regexp=&escape($regexp);
4155: } else {
4156: $regexp='.';
4157: }
4158: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4159: my @pairs=split(/\&/,$rep);
4160: my %returnhash=();
4161: foreach my $item (@pairs) {
4162: my ($key,$value)=split(/=/,$item,2);
4163: $key = &unescape($key);
4164: next if ($key =~ /^error: 2 /);
4165: $returnhash{$key}=&thaw_unescape($value);
4166: }
4167: return %returnhash;
1.407 www 4168: }
4169:
1.717 albertel 4170: # --------------------------------------------------------- dumpstore interface
4171:
4172: sub dumpstore {
4173: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4174: if (!$udomain) { $udomain=$env{'user.domain'}; }
4175: if (!$uname) { $uname=$env{'user.name'}; }
4176: my $uhome=&homeserver($uname,$udomain);
4177: if ($regexp) {
4178: $regexp=&escape($regexp);
4179: } else {
4180: $regexp='.';
4181: }
4182: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4183: my @pairs=split(/\&/,$rep);
4184: my %returnhash=();
4185: foreach my $item (@pairs) {
4186: my ($key,$value)=split(/=/,$item,2);
4187: next if ($key =~ /^error: 2 /);
4188: $returnhash{$key}=&thaw_unescape($value);
4189: }
4190: return %returnhash;
1.717 albertel 4191: }
4192:
1.407 www 4193: # -------------------------------------------------------------- keys interface
4194:
4195: sub getkeys {
4196: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4197: if (!$udomain) { $udomain=$env{'user.domain'}; }
4198: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4199: my $uhome=&homeserver($uname,$udomain);
4200: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4201: my @keyarray=();
1.800 albertel 4202: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4203: next if ($key =~ /^error: 2 /);
1.800 albertel 4204: push(@keyarray,&unescape($key));
1.407 www 4205: }
4206: return @keyarray;
1.318 matthew 4207: }
4208:
1.319 matthew 4209: # --------------------------------------------------------------- currentdump
4210: sub currentdump {
1.328 matthew 4211: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4212: $courseid = $env{'request.course.id'} if (! defined($courseid));
4213: $sdom = $env{'user.domain'} if (! defined($sdom));
4214: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4215: my $uhome = &homeserver($sname,$sdom);
4216: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4217: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4218: #
1.318 matthew 4219: my %returnhash=();
1.319 matthew 4220: #
4221: if ($rep eq "unknown_cmd") {
4222: # an old lond will not know currentdump
4223: # Do a dump and make it look like a currentdump
1.822 albertel 4224: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4225: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4226: my %hash = @tmp;
4227: @tmp=();
1.424 matthew 4228: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4229: } else {
4230: my @pairs=split(/\&/,$rep);
1.800 albertel 4231: foreach my $pair (@pairs) {
4232: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4233: my ($symb,$param) = split(/:/,$key);
4234: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4235: &thaw_unescape($value);
1.319 matthew 4236: }
1.191 harris41 4237: }
1.12 www 4238: return %returnhash;
1.424 matthew 4239: }
4240:
4241: sub convert_dump_to_currentdump{
4242: my %hash = %{shift()};
4243: my %returnhash;
4244: # Code ripped from lond, essentially. The only difference
4245: # here is the unescaping done by lonnet::dump(). Conceivably
4246: # we might run in to problems with parameter names =~ /^v\./
4247: while (my ($key,$value) = each(%hash)) {
4248: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4249: $symb = &unescape($symb);
4250: $param = &unescape($param);
1.424 matthew 4251: next if ($v eq 'version' || $symb eq 'keys');
4252: next if (exists($returnhash{$symb}) &&
4253: exists($returnhash{$symb}->{$param}) &&
4254: $returnhash{$symb}->{'v.'.$param} > $v);
4255: $returnhash{$symb}->{$param}=$value;
4256: $returnhash{$symb}->{'v.'.$param}=$v;
4257: }
4258: #
4259: # Remove all of the keys in the hashes which keep track of
4260: # the version of the parameter.
4261: while (my ($symb,$param_hash) = each(%returnhash)) {
4262: # use a foreach because we are going to delete from the hash.
4263: foreach my $key (keys(%$param_hash)) {
4264: delete($param_hash->{$key}) if ($key =~ /^v\./);
4265: }
4266: }
4267: return \%returnhash;
1.12 www 4268: }
4269:
1.627 albertel 4270: # ------------------------------------------------------ critical inc interface
4271:
4272: sub cinc {
4273: return &inc(@_,'critical');
4274: }
4275:
1.449 matthew 4276: # --------------------------------------------------------------- inc interface
4277:
4278: sub inc {
1.627 albertel 4279: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4280: if (!$udomain) { $udomain=$env{'user.domain'}; }
4281: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4282: my $uhome=&homeserver($uname,$udomain);
4283: my $items='';
4284: if (! ref($store)) {
4285: # got a single value, so use that instead
4286: $items = &escape($store).'=&';
4287: } elsif (ref($store) eq 'SCALAR') {
4288: $items = &escape($$store).'=&';
4289: } elsif (ref($store) eq 'ARRAY') {
4290: $items = join('=&',map {&escape($_);} @{$store});
4291: } elsif (ref($store) eq 'HASH') {
4292: while (my($key,$value) = each(%{$store})) {
4293: $items.= &escape($key).'='.&escape($value).'&';
4294: }
4295: }
4296: $items=~s/\&$//;
1.627 albertel 4297: if ($critical) {
4298: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4299: } else {
4300: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4301: }
1.449 matthew 4302: }
4303:
1.12 www 4304: # --------------------------------------------------------------- put interface
4305:
4306: sub put {
1.134 albertel 4307: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4308: if (!$udomain) { $udomain=$env{'user.domain'}; }
4309: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4310: my $uhome=&homeserver($uname,$udomain);
1.12 www 4311: my $items='';
1.800 albertel 4312: foreach my $item (keys(%$storehash)) {
4313: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4314: }
1.12 www 4315: $items=~s/\&$//;
1.134 albertel 4316: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4317: }
4318:
1.631 albertel 4319: # ------------------------------------------------------------ newput interface
4320:
4321: sub newput {
4322: my ($namespace,$storehash,$udomain,$uname)=@_;
4323: if (!$udomain) { $udomain=$env{'user.domain'}; }
4324: if (!$uname) { $uname=$env{'user.name'}; }
4325: my $uhome=&homeserver($uname,$udomain);
4326: my $items='';
4327: foreach my $key (keys(%$storehash)) {
4328: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4329: }
4330: $items=~s/\&$//;
4331: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4332: }
4333:
4334: # --------------------------------------------------------- putstore interface
4335:
1.524 raeburn 4336: sub putstore {
1.715 albertel 4337: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4338: if (!$udomain) { $udomain=$env{'user.domain'}; }
4339: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4340: my $uhome=&homeserver($uname,$udomain);
4341: my $items='';
1.715 albertel 4342: foreach my $key (keys(%$storehash)) {
4343: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4344: }
1.715 albertel 4345: $items=~s/\&$//;
1.716 albertel 4346: my $esc_symb=&escape($symb);
4347: my $esc_v=&escape($version);
1.715 albertel 4348: my $reply =
1.716 albertel 4349: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4350: $uhome);
4351: if ($reply eq 'unknown_cmd') {
1.716 albertel 4352: # gfall back to way things use to be done
1.715 albertel 4353: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4354: $uname);
1.524 raeburn 4355: }
1.715 albertel 4356: return $reply;
4357: }
4358:
4359: sub old_putstore {
1.716 albertel 4360: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4361: if (!$udomain) { $udomain=$env{'user.domain'}; }
4362: if (!$uname) { $uname=$env{'user.name'}; }
4363: my $uhome=&homeserver($uname,$udomain);
4364: my %newstorehash;
1.800 albertel 4365: foreach my $item (keys(%$storehash)) {
4366: my $key = $version.':'.&escape($symb).':'.$item;
4367: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4368: }
4369: my $items='';
4370: my %allitems = ();
1.800 albertel 4371: foreach my $item (keys(%newstorehash)) {
4372: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4373: my $key = $1.':keys:'.$2;
4374: $allitems{$key} .= $3.':';
4375: }
1.800 albertel 4376: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4377: }
1.800 albertel 4378: foreach my $item (keys(%allitems)) {
4379: $allitems{$item} =~ s/\:$//;
4380: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4381: }
4382: $items=~s/\&$//;
4383: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4384: }
4385:
1.47 www 4386: # ------------------------------------------------------ critical put interface
4387:
4388: sub cput {
1.134 albertel 4389: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4390: if (!$udomain) { $udomain=$env{'user.domain'}; }
4391: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4392: my $uhome=&homeserver($uname,$udomain);
1.47 www 4393: my $items='';
1.800 albertel 4394: foreach my $item (keys(%$storehash)) {
4395: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4396: }
1.47 www 4397: $items=~s/\&$//;
1.134 albertel 4398: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4399: }
4400:
4401: # -------------------------------------------------------------- eget interface
4402:
4403: sub eget {
1.133 albertel 4404: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4405: my $items='';
1.800 albertel 4406: foreach my $item (@$storearr) {
4407: $items.=&escape($item).'&';
1.191 harris41 4408: }
1.12 www 4409: $items=~s/\&$//;
1.620 albertel 4410: if (!$udomain) { $udomain=$env{'user.domain'}; }
4411: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4412: my $uhome=&homeserver($uname,$udomain);
4413: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4414: my @pairs=split(/\&/,$rep);
4415: my %returnhash=();
1.42 www 4416: my $i=0;
1.800 albertel 4417: foreach my $item (@$storearr) {
4418: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4419: $i++;
1.191 harris41 4420: }
1.12 www 4421: return %returnhash;
4422: }
4423:
1.667 albertel 4424: # ------------------------------------------------------------ tmpput interface
4425: sub tmpput {
1.802 raeburn 4426: my ($storehash,$server,$context)=@_;
1.667 albertel 4427: my $items='';
1.800 albertel 4428: foreach my $item (keys(%$storehash)) {
4429: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4430: }
4431: $items=~s/\&$//;
1.802 raeburn 4432: if (defined($context)) {
4433: $items .= ':'.&escape($context);
4434: }
1.667 albertel 4435: return &reply("tmpput:$items",$server);
4436: }
4437:
4438: # ------------------------------------------------------------ tmpget interface
4439: sub tmpget {
1.688 albertel 4440: my ($token,$server)=@_;
4441: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4442: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4443: my %returnhash;
4444: foreach my $item (split(/\&/,$rep)) {
4445: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4446: next if ($key =~ /^error: 2 /);
1.667 albertel 4447: $returnhash{&unescape($key)}=&thaw_unescape($value);
4448: }
4449: return %returnhash;
4450: }
4451:
1.688 albertel 4452: # ------------------------------------------------------------ tmpget interface
4453: sub tmpdel {
4454: my ($token,$server)=@_;
4455: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4456: return &reply("tmpdel:$token",$server);
4457: }
4458:
1.765 albertel 4459: # -------------------------------------------------- portfolio access checking
4460:
4461: sub portfolio_access {
1.766 albertel 4462: my ($requrl) = @_;
1.765 albertel 4463: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4464: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4465: if ($result) {
4466: my %setters;
4467: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4468: my ($startblock,$endblock) =
4469: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4470: if ($startblock && $endblock) {
4471: return 'B';
4472: }
4473: } else {
4474: my ($startblock,$endblock) =
4475: &Apache::loncommon::blockcheck(\%setters,'port');
4476: if ($startblock && $endblock) {
4477: return 'B';
4478: }
4479: }
4480: }
1.765 albertel 4481: if ($result eq 'ok') {
1.766 albertel 4482: return 'F';
1.765 albertel 4483: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4484: return 'A';
1.765 albertel 4485: }
1.766 albertel 4486: return '';
1.765 albertel 4487: }
4488:
4489: sub get_portfolio_access {
1.767 albertel 4490: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4491:
4492: if (!ref($access_hash)) {
4493: my $current_perms = &get_portfile_permissions($udom,$unum);
4494: my %access_controls = &get_access_controls($current_perms,$group,
4495: $file_name);
4496: $access_hash = $access_controls{$file_name};
4497: }
4498:
1.765 albertel 4499: my ($public,$guest,@domains,@users,@courses,@groups);
4500: my $now = time;
4501: if (ref($access_hash) eq 'HASH') {
4502: foreach my $key (keys(%{$access_hash})) {
4503: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4504: if ($start > $now) {
4505: next;
4506: }
4507: if ($end && $end<$now) {
4508: next;
4509: }
4510: if ($scope eq 'public') {
4511: $public = $key;
4512: last;
4513: } elsif ($scope eq 'guest') {
4514: $guest = $key;
4515: } elsif ($scope eq 'domains') {
4516: push(@domains,$key);
4517: } elsif ($scope eq 'users') {
4518: push(@users,$key);
4519: } elsif ($scope eq 'course') {
4520: push(@courses,$key);
4521: } elsif ($scope eq 'group') {
4522: push(@groups,$key);
4523: }
4524: }
4525: if ($public) {
4526: return 'ok';
4527: }
4528: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4529: if ($guest) {
4530: return $guest;
4531: }
4532: } else {
4533: if (@domains > 0) {
4534: foreach my $domkey (@domains) {
4535: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4536: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4537: return 'ok';
4538: }
4539: }
4540: }
4541: }
4542: if (@users > 0) {
4543: foreach my $userkey (@users) {
1.865 raeburn 4544: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4545: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4546: if (ref($item) eq 'HASH') {
4547: if (($item->{'uname'} eq $env{'user.name'}) &&
4548: ($item->{'udom'} eq $env{'user.domain'})) {
4549: return 'ok';
4550: }
4551: }
4552: }
4553: }
1.765 albertel 4554: }
4555: }
4556: my %roleshash;
4557: my @courses_and_groups = @courses;
4558: push(@courses_and_groups,@groups);
4559: if (@courses_and_groups > 0) {
4560: my (%allgroups,%allroles);
4561: my ($start,$end,$role,$sec,$group);
4562: foreach my $envkey (%env) {
1.1060 raeburn 4563: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4564: my $cid = $2.'_'.$3;
4565: if ($1 eq 'gr') {
4566: $group = $4;
4567: $allgroups{$cid}{$group} = $env{$envkey};
4568: } else {
4569: if ($4 eq '') {
4570: $sec = 'none';
4571: } else {
4572: $sec = $4;
4573: }
4574: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4575: }
1.811 albertel 4576: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4577: my $cid = $2.'_'.$3;
4578: if ($4 eq '') {
4579: $sec = 'none';
4580: } else {
4581: $sec = $4;
4582: }
4583: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4584: }
4585: }
4586: if (keys(%allroles) == 0) {
4587: return;
4588: }
4589: foreach my $key (@courses_and_groups) {
4590: my %content = %{$$access_hash{$key}};
4591: my $cnum = $content{'number'};
4592: my $cdom = $content{'domain'};
4593: my $cid = $cdom.'_'.$cnum;
4594: if (!exists($allroles{$cid})) {
4595: next;
4596: }
4597: foreach my $role_id (keys(%{$content{'roles'}})) {
4598: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4599: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4600: my @status = @{$content{'roles'}{$role_id}{'access'}};
4601: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4602: foreach my $role (keys(%{$allroles{$cid}})) {
4603: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4604: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4605: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4606: if (grep/^all$/,@sections) {
4607: return 'ok';
4608: } else {
4609: if (grep/^$sec$/,@sections) {
4610: return 'ok';
4611: }
4612: }
4613: }
4614: }
4615: if (keys(%{$allgroups{$cid}}) == 0) {
4616: if (grep/^none$/,@groups) {
4617: return 'ok';
4618: }
4619: } else {
4620: if (grep/^all$/,@groups) {
4621: return 'ok';
4622: }
4623: foreach my $group (keys(%{$allgroups{$cid}})) {
4624: if (grep/^$group$/,@groups) {
4625: return 'ok';
4626: }
4627: }
4628: }
4629: }
4630: }
4631: }
4632: }
4633: }
4634: if ($guest) {
4635: return $guest;
4636: }
4637: }
4638: }
4639: return;
4640: }
4641:
4642: sub course_group_datechecker {
4643: my ($dates,$now,$status) = @_;
4644: my ($start,$end) = split(/\./,$dates);
4645: if (!$start && !$end) {
4646: return 'ok';
4647: }
4648: if (grep/^active$/,@{$status}) {
4649: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4650: return 'ok';
4651: }
4652: }
4653: if (grep/^previous$/,@{$status}) {
4654: if ($end > $now ) {
4655: return 'ok';
4656: }
4657: }
4658: if (grep/^future$/,@{$status}) {
4659: if ($start > $now) {
4660: return 'ok';
4661: }
4662: }
4663: return;
4664: }
4665:
4666: sub parse_portfolio_url {
4667: my ($url) = @_;
4668:
4669: my ($type,$udom,$unum,$group,$file_name);
4670:
1.823 albertel 4671: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4672: $type = 1;
4673: $udom = $1;
4674: $unum = $2;
4675: $file_name = $3;
1.823 albertel 4676: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4677: $type = 2;
4678: $udom = $1;
4679: $unum = $2;
4680: $group = $3;
4681: $file_name = $3.'/'.$4;
4682: }
4683: if (wantarray) {
4684: return ($type,$udom,$unum,$file_name,$group);
4685: }
4686: return $type;
4687: }
4688:
4689: sub is_portfolio_url {
4690: my ($url) = @_;
4691: return scalar(&parse_portfolio_url($url));
4692: }
4693:
1.798 raeburn 4694: sub is_portfolio_file {
4695: my ($file) = @_;
1.820 raeburn 4696: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4697: return 1;
4698: }
4699: return;
4700: }
4701:
1.976 raeburn 4702: sub usertools_access {
1.985 raeburn 4703: my ($uname,$udom,$tool,$action,$context) = @_;
4704: my ($access,%tools);
4705: if ($context eq '') {
4706: $context = 'tools';
4707: }
4708: if ($context eq 'requestcourses') {
4709: %tools = (
4710: official => 1,
4711: unofficial => 1,
1.1006 raeburn 4712: community => 1,
1.985 raeburn 4713: );
4714: } else {
4715: %tools = (
4716: aboutme => 1,
4717: blog => 1,
4718: portfolio => 1,
4719: );
4720: }
1.976 raeburn 4721: return if (!defined($tools{$tool}));
4722:
4723: if ((!defined($udom)) || (!defined($uname))) {
4724: $udom = $env{'user.domain'};
4725: $uname = $env{'user.name'};
4726: }
4727:
1.978 raeburn 4728: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4729: if ($action ne 'reload') {
1.985 raeburn 4730: if ($context eq 'requestcourses') {
4731: return $env{'environment.canrequest.'.$tool};
4732: } else {
4733: return $env{'environment.availabletools.'.$tool};
4734: }
4735: }
1.976 raeburn 4736: }
4737:
4738: my ($toolstatus,$inststatus);
4739:
1.985 raeburn 4740: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4741: ($action ne 'reload')) {
4742: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4743: $inststatus = $env{'environment.inststatus'};
4744: } else {
1.1025 raeburn 4745: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985 raeburn 4746: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4747: $inststatus = $userenv{'inststatus'};
4748: }
4749:
4750: if ($toolstatus ne '') {
4751: if ($toolstatus) {
4752: $access = 1;
4753: } else {
4754: $access = 0;
4755: }
4756: return $access;
4757: }
4758:
4759: my $is_adv = &is_advanced_user($udom,$uname);
4760: my %domdef = &get_domain_defaults($udom);
4761: if (ref($domdef{$tool}) eq 'HASH') {
4762: if ($is_adv) {
4763: if ($domdef{$tool}{'_LC_adv'} ne '') {
4764: if ($domdef{$tool}{'_LC_adv'}) {
4765: $access = 1;
4766: } else {
4767: $access = 0;
4768: }
4769: return $access;
4770: }
4771: }
4772: if ($inststatus ne '') {
4773: my ($hasaccess,$hasnoaccess);
4774: foreach my $affiliation (split(/:/,$inststatus)) {
4775: if ($domdef{$tool}{$affiliation} ne '') {
4776: if ($domdef{$tool}{$affiliation}) {
4777: $hasaccess = 1;
4778: } else {
4779: $hasnoaccess = 1;
4780: }
4781: }
4782: }
4783: if ($hasaccess || $hasnoaccess) {
4784: if ($hasaccess) {
4785: $access = 1;
4786: } elsif ($hasnoaccess) {
4787: $access = 0;
4788: }
4789: return $access;
4790: }
4791: } else {
4792: if ($domdef{$tool}{'default'} ne '') {
4793: if ($domdef{$tool}{'default'}) {
4794: $access = 1;
4795: } elsif ($domdef{$tool}{'default'} == 0) {
4796: $access = 0;
4797: }
4798: return $access;
4799: }
4800: }
4801: } else {
1.985 raeburn 4802: if ($context eq 'tools') {
4803: $access = 1;
4804: } else {
4805: $access = 0;
4806: }
1.976 raeburn 4807: return $access;
4808: }
4809: }
4810:
1.1050 raeburn 4811: sub is_course_owner {
4812: my ($cdom,$cnum,$udom,$uname) = @_;
4813: if (($udom eq '') || ($uname eq '')) {
4814: $udom = $env{'user.domain'};
4815: $uname = $env{'user.name'};
4816: }
4817: unless (($udom eq '') || ($uname eq '')) {
4818: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
4819: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
4820: return 1;
4821: } else {
4822: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
4823: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
4824: return 1;
4825: }
4826: }
4827: }
4828: }
4829: return;
4830: }
4831:
1.976 raeburn 4832: sub is_advanced_user {
4833: my ($udom,$uname) = @_;
4834: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4835: my %allroles;
4836: my $is_adv;
4837: foreach my $role (keys(%roleshash)) {
4838: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4839: my $area = '/'.$tdomain.'/'.$trest;
4840: if ($sec ne '') {
4841: $area .= '/'.$sec;
4842: }
4843: if (($area ne '') && ($trole ne '')) {
4844: my $spec=$trole.'.'.$area;
4845: if ($trole =~ /^cr\//) {
4846: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4847: } elsif ($trole ne 'gr') {
4848: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4849: }
4850: }
4851: }
4852: foreach my $role (keys(%allroles)) {
4853: last if ($is_adv);
4854: foreach my $item (split(/:/,$allroles{$role})) {
4855: if ($item ne '') {
4856: my ($privilege,$restrictions)=split(/&/,$item);
4857: if ($privilege eq 'adv') {
4858: $is_adv = 1;
4859: last;
4860: }
4861: }
4862: }
4863: }
4864: return $is_adv;
4865: }
1.798 raeburn 4866:
1.1035 raeburn 4867: sub check_can_request {
1.1036 raeburn 4868: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 4869: my $canreq = 0;
4870: my ($types,$typename) = &Apache::loncommon::course_types();
4871: my @options = ('approval','validate','autolimit');
4872: my $optregex = join('|',@options);
4873: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
4874: foreach my $type (@{$types}) {
4875: if (&usertools_access($env{'user.name'},
4876: $env{'user.domain'},
4877: $type,undef,'requestcourses')) {
4878: $canreq ++;
1.1036 raeburn 4879: if (ref($request_domains) eq 'HASH') {
4880: push(@{$request_domains->{$type}},$env{'user.domain'});
4881: }
1.1035 raeburn 4882: if ($dom eq $env{'user.domain'}) {
4883: $can_request->{$type} = 1;
4884: }
4885: }
4886: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
4887: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
4888: if (@curr > 0) {
1.1036 raeburn 4889: foreach my $item (@curr) {
4890: if (ref($request_domains) eq 'HASH') {
4891: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
4892: if ($otherdom ne '') {
4893: if (ref($request_domains->{$type}) eq 'ARRAY') {
4894: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
4895: push(@{$request_domains->{$type}},$otherdom);
4896: }
4897: } else {
4898: push(@{$request_domains->{$type}},$otherdom);
4899: }
4900: }
4901: }
4902: }
4903: unless($dom eq $env{'user.domain'}) {
4904: $canreq ++;
1.1035 raeburn 4905: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
4906: $can_request->{$type} = 1;
4907: }
4908: }
4909: }
4910: }
4911: }
4912: }
4913: return $canreq;
4914: }
4915:
1.341 www 4916: # ---------------------------------------------- Custom access rule evaluation
4917:
4918: sub customaccess {
4919: my ($priv,$uri)=@_;
1.807 albertel 4920: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4921: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4922: $udom = &LONCAPA::clean_domain($udom);
4923: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4924: my $access=0;
1.800 albertel 4925: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4926: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4927: if ($type eq 'user') {
4928: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4929: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4930: if ($tdom) {
4931: if ($tdom ne $env{'user.domain'}) { next; }
4932: }
1.896 albertel 4933: if ($tuname) {
4934: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4935: }
4936: $access=($effect eq 'allow');
4937: last;
4938: }
4939: } else {
4940: if ($role) {
4941: if ($role ne $urole) { next; }
4942: }
4943: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4944: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4945: if ($tdom) {
4946: if ($tdom ne $udom) { next; }
4947: }
4948: if ($tcrs) {
4949: if ($tcrs ne $ucrs) { next; }
4950: }
4951: if ($tsec) {
4952: if ($tsec ne $usec) { next; }
4953: }
4954: $access=($effect eq 'allow');
4955: last;
4956: }
4957: if ($realm eq '' && $role eq '') {
4958: $access=($effect eq 'allow');
4959: }
1.402 bowersj2 4960: }
1.341 www 4961: }
4962: return $access;
4963: }
4964:
1.103 harris41 4965: # ------------------------------------------------- Check for a user privilege
1.12 www 4966:
4967: sub allowed {
1.810 raeburn 4968: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4969: my $ver_orguri=$uri;
1.439 www 4970: $uri=&deversion($uri);
1.152 www 4971: my $orguri=$uri;
1.52 www 4972: $uri=&declutter($uri);
1.809 raeburn 4973:
1.810 raeburn 4974: if ($priv eq 'evb') {
4975: # Evade communication block restrictions for specified role in a course
4976: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4977: return $1;
4978: } else {
4979: return;
4980: }
4981: }
4982:
1.620 albertel 4983: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4984: # Free bre access to adm and meta resources
1.775 albertel 4985: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4986: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4987: && ($priv eq 'bre')) {
1.14 www 4988: return 'F';
1.159 www 4989: }
4990:
1.545 banghart 4991: # Free bre access to user's own portfolio contents
1.714 raeburn 4992: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4993: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4994: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4995: my %setters;
4996: my ($startblock,$endblock) =
4997: &Apache::loncommon::blockcheck(\%setters,'port');
4998: if ($startblock && $endblock) {
4999: return 'B';
5000: } else {
5001: return 'F';
5002: }
1.545 banghart 5003: }
5004:
1.762 raeburn 5005: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5006: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5007: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5008: if (exists($env{'request.course.id'})) {
5009: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5010: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5011: if (($domain eq $cdom) && ($name eq $cnum)) {
5012: my $courseprivid=$env{'request.course.id'};
5013: $courseprivid=~s/\_/\//;
5014: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5015: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5016: return $1;
1.762 raeburn 5017: } else {
5018: if ($env{'request.course.sec'}) {
5019: $courseprivid.='/'.$env{'request.course.sec'};
5020: }
5021: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5022: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5023: return $2;
5024: }
1.714 raeburn 5025: }
5026: }
5027: }
5028: }
5029:
1.159 www 5030: # Free bre to public access
5031:
5032: if ($priv eq 'bre') {
1.238 www 5033: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5034: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5035: return 'F';
5036: }
1.238 www 5037: if ($copyright eq 'priv') {
5038: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5039: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5040: return '';
5041: }
5042: }
5043: if ($copyright eq 'domain') {
5044: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5045: unless (($env{'user.domain'} eq $1) ||
5046: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5047: return '';
5048: }
1.262 matthew 5049: }
1.620 albertel 5050: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5051: # Library role, so allow browsing of resources in this domain.
5052: return 'F';
1.238 www 5053: }
1.341 www 5054: if ($copyright eq 'custom') {
5055: unless (&customaccess($priv,$uri)) { return ''; }
5056: }
1.14 www 5057: }
1.264 matthew 5058: # Domain coordinator is trying to create a course
1.620 albertel 5059: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5060: # uri is the requested domain in this case.
5061: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5062: # a role of dc for the domain in question.
1.620 albertel 5063: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5064: }
1.29 www 5065:
1.52 www 5066: my $thisallowed='';
5067: my $statecond=0;
5068: my $courseprivid='';
5069:
1.1039 raeburn 5070: my $ownaccess;
1.1043 raeburn 5071: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5072: if (($priv eq 'bro') && ($env{'user.author'})) {
5073: if ($uri eq '') {
5074: $ownaccess = 1;
5075: } else {
5076: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5077: my $udom = $env{'user.domain'};
5078: my $uname = $env{'user.name'};
5079: if ($uri =~ m{^\Q$udom\E/?$}) {
5080: $ownaccess = 1;
1.1040 raeburn 5081: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5082: unless ($uri =~ m{\.\./}) {
5083: $ownaccess = 1;
5084: }
5085: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5086: my $now = time;
5087: if ($uri =~ m{^([^/]+)/?$}) {
5088: my $adom = $1;
5089: foreach my $key (keys(%env)) {
1.1042 raeburn 5090: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5091: my ($start,$end) = split('.',$env{$key});
5092: if (($now >= $start) && (!$end || $end < $now)) {
5093: $ownaccess = 1;
5094: last;
5095: }
5096: }
5097: }
5098: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5099: my $adom = $1;
5100: my $aname = $2;
1.1042 raeburn 5101: foreach my $role ('ca','aa') {
5102: if ($env{"user.role.$role./$adom/$aname"}) {
5103: my ($start,$end) =
5104: split('.',$env{"user.role.$role./$adom/$aname"});
5105: if (($now >= $start) && (!$end || $end < $now)) {
5106: $ownaccess = 1;
5107: last;
5108: }
1.1039 raeburn 5109: }
5110: }
5111: }
5112: }
5113: }
5114: }
5115: }
5116:
1.52 www 5117: # Course
5118:
1.620 albertel 5119: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5120: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5121: $thisallowed.=$1;
5122: }
1.52 www 5123: }
1.29 www 5124:
1.52 www 5125: # Domain
5126:
1.620 albertel 5127: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5128: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5129: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5130: $thisallowed.=$1;
5131: }
1.12 www 5132: }
1.52 www 5133:
5134: # Course: uri itself is a course
1.66 www 5135: my $courseuri=$uri;
5136: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5137: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5138:
1.620 albertel 5139: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5140: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5141: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5142: $thisallowed.=$1;
5143: }
1.12 www 5144: }
1.29 www 5145:
1.665 albertel 5146: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5147: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5148: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5149: $thisallowed='';
1.671 raeburn 5150: my ($match)=&is_on_map($uri);
5151: if ($match) {
5152: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5153: =~/\Q$priv\E\&([^\:]*)/) {
5154: $thisallowed.=$1;
5155: }
5156: } else {
1.705 albertel 5157: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5158: if ($refuri) {
5159: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5160: $thisallowed='F';
1.671 raeburn 5161: } else {
5162: $refuri=&declutter($refuri);
5163: my ($match) = &is_on_map($refuri);
5164: if ($match) {
5165: $thisallowed='F';
5166: }
1.669 raeburn 5167: }
1.671 raeburn 5168: }
5169: }
1.314 www 5170: }
1.492 albertel 5171:
1.766 albertel 5172: if ($priv eq 'bre'
5173: && $thisallowed ne 'F'
5174: && $thisallowed ne '2'
5175: && &is_portfolio_url($uri)) {
5176: $thisallowed = &portfolio_access($uri);
5177: }
5178:
1.52 www 5179: # Full access at system, domain or course-wide level? Exit.
1.29 www 5180: if ($thisallowed=~/F/) {
5181: return 'F';
5182: }
5183:
1.52 www 5184: # If this is generating or modifying users, exit with special codes
1.29 www 5185:
1.643 www 5186: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5187: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5188: my ($audom,$auname)=split('/',$uri);
1.643 www 5189: # no author name given, so this just checks on the general right to make a co-author in this domain
5190: unless ($auname) { return $thisallowed; }
5191: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5192: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5193: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5194: ($audom ne $env{'request.role.domain'}))) { return ''; }
5195: }
1.52 www 5196: return $thisallowed;
5197: }
5198: #
1.103 harris41 5199: # Gathered so far: system, domain and course wide privileges
1.52 www 5200: #
5201: # Course: See if uri or referer is an individual resource that is part of
5202: # the course
5203:
1.620 albertel 5204: if ($env{'request.course.id'}) {
1.232 www 5205:
1.620 albertel 5206: $courseprivid=$env{'request.course.id'};
5207: if ($env{'request.course.sec'}) {
5208: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5209: }
5210: $courseprivid=~s/\_/\//;
5211: my $checkreferer=1;
1.232 www 5212: my ($match,$cond)=&is_on_map($uri);
5213: if ($match) {
5214: $statecond=$cond;
1.620 albertel 5215: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5216: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5217: $thisallowed.=$1;
5218: $checkreferer=0;
5219: }
1.29 www 5220: }
1.83 www 5221:
1.148 www 5222: if ($checkreferer) {
1.620 albertel 5223: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5224: unless ($refuri) {
1.800 albertel 5225: foreach my $key (keys(%env)) {
5226: if ($key=~/^httpref\..*\*/) {
5227: my $pattern=$key;
1.156 www 5228: $pattern=~s/^httpref\.\/res\///;
1.148 www 5229: $pattern=~s/\*/\[\^\/\]\+/g;
5230: $pattern=~s/\//\\\//g;
1.152 www 5231: if ($orguri=~/$pattern/) {
1.800 albertel 5232: $refuri=$env{$key};
1.148 www 5233: }
5234: }
1.191 harris41 5235: }
1.148 www 5236: }
1.232 www 5237:
1.148 www 5238: if ($refuri) {
1.152 www 5239: $refuri=&declutter($refuri);
1.232 www 5240: my ($match,$cond)=&is_on_map($refuri);
5241: if ($match) {
5242: my $refstatecond=$cond;
1.620 albertel 5243: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5244: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5245: $thisallowed.=$1;
1.53 www 5246: $uri=$refuri;
5247: $statecond=$refstatecond;
1.52 www 5248: }
5249: }
1.148 www 5250: }
1.29 www 5251: }
1.52 www 5252: }
1.29 www 5253:
1.52 www 5254: #
1.103 harris41 5255: # Gathered now: all privileges that could apply, and condition number
1.52 www 5256: #
5257: #
5258: # Full or no access?
5259: #
1.29 www 5260:
1.52 www 5261: if ($thisallowed=~/F/) {
5262: return 'F';
5263: }
1.29 www 5264:
1.52 www 5265: unless ($thisallowed) {
5266: return '';
5267: }
1.29 www 5268:
1.52 www 5269: # Restrictions exist, deal with them
5270: #
5271: # C:according to course preferences
5272: # R:according to resource settings
5273: # L:unless locked
5274: # X:according to user session state
5275: #
5276:
5277: # Possibly locked functionality, check all courses
1.54 www 5278: # Locks might take effect only after 10 minutes cache expiration for other
5279: # courses, and 2 minutes for current course
1.52 www 5280:
5281: my $envkey;
5282: if ($thisallowed=~/L/) {
1.1000 raeburn 5283: foreach $envkey (keys(%env)) {
1.54 www 5284: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5285: my $courseid=$2;
5286: my $roleid=$1.'.'.$2;
1.92 www 5287: $courseid=~s/^\///;
1.54 www 5288: my $expiretime=600;
1.620 albertel 5289: if ($env{'request.role'} eq $roleid) {
1.54 www 5290: $expiretime=120;
5291: }
5292: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5293: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5294: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5295: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5296: }
1.620 albertel 5297: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5298: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5299: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5300: &log($env{'user.domain'},$env{'user.name'},
5301: $env{'user.home'},
1.57 www 5302: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5303: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5304: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5305: return '';
5306: }
5307: }
1.620 albertel 5308: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5309: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5310: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5311: &log($env{'user.domain'},$env{'user.name'},
5312: $env{'user.home'},
1.57 www 5313: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5314: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5315: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5316: return '';
5317: }
5318: }
5319: }
1.29 www 5320: }
1.52 www 5321: }
5322:
5323: #
5324: # Rest of the restrictions depend on selected course
5325: #
5326:
1.620 albertel 5327: unless ($env{'request.course.id'}) {
1.766 albertel 5328: if ($thisallowed eq 'A') {
5329: return 'A';
1.814 raeburn 5330: } elsif ($thisallowed eq 'B') {
5331: return 'B';
1.766 albertel 5332: } else {
5333: return '1';
5334: }
1.52 www 5335: }
1.29 www 5336:
1.52 www 5337: #
5338: # Now user is definitely in a course
5339: #
1.53 www 5340:
5341:
5342: # Course preferences
5343:
5344: if ($thisallowed=~/C/) {
1.620 albertel 5345: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5346: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5347: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5348: =~/\Q$rolecode\E/) {
1.689 albertel 5349: if ($priv ne 'pch') {
5350: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5351: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5352: $env{'request.course.id'});
5353: }
1.237 www 5354: return '';
5355: }
5356:
1.620 albertel 5357: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5358: =~/\Q$unamedom\E/) {
1.689 albertel 5359: if ($priv ne 'pch') {
5360: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5361: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5362: $env{'request.course.id'});
5363: }
1.54 www 5364: return '';
5365: }
1.53 www 5366: }
5367:
5368: # Resource preferences
5369:
5370: if ($thisallowed=~/R/) {
1.620 albertel 5371: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5372: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5373: if ($priv ne 'pch') {
5374: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5375: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5376: }
5377: return '';
1.54 www 5378: }
1.53 www 5379: }
1.30 www 5380:
1.246 www 5381: # Restricted by state or randomout?
1.30 www 5382:
1.52 www 5383: if ($thisallowed=~/X/) {
1.620 albertel 5384: if ($env{'acc.randomout'}) {
1.579 albertel 5385: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5386: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5387: return '';
5388: }
1.247 www 5389: }
5390: if (&condval($statecond)) {
1.52 www 5391: return '2';
5392: } else {
5393: return '';
5394: }
5395: }
1.30 www 5396:
1.766 albertel 5397: if ($thisallowed eq 'A') {
5398: return 'A';
1.814 raeburn 5399: } elsif ($thisallowed eq 'B') {
5400: return 'B';
1.766 albertel 5401: }
1.52 www 5402: return 'F';
1.232 www 5403: }
5404:
1.710 albertel 5405: sub split_uri_for_cond {
5406: my $uri=&deversion(&declutter(shift));
5407: my @uriparts=split(/\//,$uri);
5408: my $filename=pop(@uriparts);
5409: my $pathname=join('/',@uriparts);
5410: return ($pathname,$filename);
5411: }
1.232 www 5412: # --------------------------------------------------- Is a resource on the map?
5413:
5414: sub is_on_map {
1.710 albertel 5415: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5416: #Trying to find the conditional for the file
1.620 albertel 5417: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5418: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5419: if ($match) {
1.289 bowersj2 5420: return (1,$1);
5421: } else {
1.434 www 5422: return (0,0);
1.289 bowersj2 5423: }
1.12 www 5424: }
5425:
1.427 www 5426: # --------------------------------------------------------- Get symb from alias
5427:
5428: sub get_symb_from_alias {
5429: my $symb=shift;
5430: my ($map,$resid,$url)=&decode_symb($symb);
5431: # Already is a symb
5432: if ($url) { return $symb; }
5433: # Must be an alias
5434: my $aliassymb='';
5435: my %bighash;
1.620 albertel 5436: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5437: &GDBM_READER(),0640)) {
5438: my $rid=$bighash{'mapalias_'.$symb};
5439: if ($rid) {
5440: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5441: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5442: $resid,$bighash{'src_'.$rid});
1.427 www 5443: }
5444: untie %bighash;
5445: }
5446: return $aliassymb;
5447: }
5448:
1.12 www 5449: # ----------------------------------------------------------------- Define Role
5450:
5451: sub definerole {
5452: if (allowed('mcr','/')) {
5453: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5454: foreach my $role (split(':',$sysrole)) {
5455: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5456: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5457: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5458: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5459: return "refused:s:$crole&$cqual";
5460: }
5461: }
1.191 harris41 5462: }
1.800 albertel 5463: foreach my $role (split(':',$domrole)) {
5464: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5465: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5466: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5467: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5468: return "refused:d:$crole&$cqual";
5469: }
5470: }
1.191 harris41 5471: }
1.800 albertel 5472: foreach my $role (split(':',$courole)) {
5473: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5474: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5475: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5476: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5477: return "refused:c:$crole&$cqual";
5478: }
5479: }
1.191 harris41 5480: }
1.620 albertel 5481: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5482: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5483: "rolesdef_$rolename=".
5484: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5485: return reply($command,$env{'user.home'});
1.12 www 5486: } else {
5487: return 'refused';
5488: }
1.105 harris41 5489: }
5490:
5491: # ---------------- Make a metadata query against the network of library servers
5492:
5493: sub metadata_query {
1.244 matthew 5494: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5495: my %rhash;
1.845 albertel 5496: my %libserv = &all_library();
1.244 matthew 5497: my @server_list = (defined($server_array) ? @$server_array
5498: : keys(%libserv) );
5499: for my $server (@server_list) {
1.118 harris41 5500: unless ($custom or $customshow) {
5501: my $reply=&reply("querysend:".&escape($query),$server);
5502: $rhash{$server}=$reply;
5503: }
5504: else {
5505: my $reply=&reply("querysend:".&escape($query).':'.
5506: &escape($custom).':'.&escape($customshow),
5507: $server);
5508: $rhash{$server}=$reply;
5509: }
1.112 harris41 5510: }
1.118 harris41 5511: return \%rhash;
1.240 www 5512: }
5513:
5514: # ----------------------------------------- Send log queries and wait for reply
5515:
5516: sub log_query {
5517: my ($uname,$udom,$query,%filters)=@_;
5518: my $uhome=&homeserver($uname,$udom);
5519: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5520: my $uhost=&hostname($uhome);
1.800 albertel 5521: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5522: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5523: $uhome);
1.479 albertel 5524: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5525: return get_query_reply($queryid);
5526: }
5527:
1.818 raeburn 5528: # -------------------------- Update MySQL table for portfolio file
5529:
5530: sub update_portfolio_table {
1.821 raeburn 5531: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5532: if ($group ne '') {
5533: $file_name =~s /^\Q$group\E//;
5534: }
1.818 raeburn 5535: my $homeserver = &homeserver($uname,$udom);
5536: my $queryid=
1.821 raeburn 5537: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5538: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5539: my $reply = &get_query_reply($queryid);
5540: return $reply;
5541: }
5542:
1.899 raeburn 5543: # -------------------------- Update MySQL allusers table
5544:
5545: sub update_allusers_table {
5546: my ($uname,$udom,$names) = @_;
5547: my $homeserver = &homeserver($uname,$udom);
5548: my $queryid=
5549: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5550: 'lastname='.&escape($names->{'lastname'}).'%%'.
5551: 'firstname='.&escape($names->{'firstname'}).'%%'.
5552: 'middlename='.&escape($names->{'middlename'}).'%%'.
5553: 'generation='.&escape($names->{'generation'}).'%%'.
5554: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5555: 'id='.&escape($names->{'id'}),$homeserver);
5556: my $reply = &get_query_reply($queryid);
5557: return $reply;
5558: }
5559:
1.508 raeburn 5560: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5561:
5562: sub fetch_enrollment_query {
1.511 raeburn 5563: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5564: my $homeserver;
1.547 raeburn 5565: my $maxtries = 1;
1.508 raeburn 5566: if ($context eq 'automated') {
5567: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5568: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5569: } else {
5570: $homeserver = &homeserver($cnum,$dom);
5571: }
1.838 albertel 5572: my $host=&hostname($homeserver);
1.506 raeburn 5573: my $cmd = '';
1.1000 raeburn 5574: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5575: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5576: }
5577: $cmd =~ s/%%$//;
5578: $cmd = &escape($cmd);
5579: my $query = 'fetchenrollment';
1.620 albertel 5580: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5581: unless ($queryid=~/^\Q$host\E\_/) {
5582: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5583: return 'error: '.$queryid;
5584: }
1.506 raeburn 5585: my $reply = &get_query_reply($queryid);
1.547 raeburn 5586: my $tries = 1;
5587: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5588: $reply = &get_query_reply($queryid);
5589: $tries ++;
5590: }
1.526 raeburn 5591: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5592: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5593: } else {
1.901 albertel 5594: my @responses = split(/:/,$reply);
1.515 raeburn 5595: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5596: foreach my $line (@responses) {
5597: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5598: $$replyref{$key} = $value;
5599: }
5600: } else {
1.506 raeburn 5601: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5602: foreach my $line (@responses) {
5603: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5604: $$replyref{$key} = $value;
5605: if ($value > 0) {
1.800 albertel 5606: foreach my $item (@{$$affiliatesref{$key}}) {
5607: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5608: my $destname = $pathname.'/'.$filename;
5609: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5610: if ($xml_classlist =~ /^error/) {
5611: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5612: } else {
1.506 raeburn 5613: if ( open(FILE,">$destname") ) {
5614: print FILE &unescape($xml_classlist);
5615: close(FILE);
1.526 raeburn 5616: } else {
5617: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5618: }
5619: }
5620: }
5621: }
5622: }
5623: }
5624: return 'ok';
5625: }
5626: return 'error';
5627: }
5628:
1.242 www 5629: sub get_query_reply {
5630: my $queryid=shift;
1.240 www 5631: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5632: my $reply='';
5633: for (1..100) {
5634: sleep 2;
5635: if (-e $replyfile.'.end') {
1.448 albertel 5636: if (open(my $fh,$replyfile)) {
1.904 albertel 5637: $reply = join('',<$fh>);
5638: close($fh);
1.240 www 5639: } else { return 'error: reply_file_error'; }
1.242 www 5640: return &unescape($reply);
5641: }
1.240 www 5642: }
1.242 www 5643: return 'timeout:'.$queryid;
1.240 www 5644: }
5645:
5646: sub courselog_query {
1.241 www 5647: #
5648: # possible filters:
5649: # url: url or symb
5650: # username
5651: # domain
5652: # action: view, submit, grade
5653: # start: timestamp
5654: # end: timestamp
5655: #
1.240 www 5656: my (%filters)=@_;
1.620 albertel 5657: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5658: if ($filters{'url'}) {
5659: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5660: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5661: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5662: }
1.620 albertel 5663: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5664: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5665: return &log_query($cname,$cdom,'courselog',%filters);
5666: }
5667:
5668: sub userlog_query {
1.858 raeburn 5669: #
5670: # possible filters:
5671: # action: log check role
5672: # start: timestamp
5673: # end: timestamp
5674: #
1.240 www 5675: my ($uname,$udom,%filters)=@_;
5676: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5677: }
5678:
1.506 raeburn 5679: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5680:
5681: sub auto_run {
1.508 raeburn 5682: my ($cnum,$cdom) = @_;
1.876 raeburn 5683: my $response = 0;
5684: my $settings;
5685: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5686: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5687: $settings = $domconfig{'autoenroll'};
5688: if ($settings->{'run'} eq '1') {
5689: $response = 1;
5690: }
5691: } else {
1.934 raeburn 5692: my $homeserver;
5693: if (&is_course($cdom,$cnum)) {
5694: $homeserver = &homeserver($cnum,$cdom);
5695: } else {
5696: $homeserver = &domain($cdom,'primary');
5697: }
5698: if ($homeserver ne 'no_host') {
5699: $response = &reply('autorun:'.$cdom,$homeserver);
5700: }
1.876 raeburn 5701: }
1.506 raeburn 5702: return $response;
5703: }
1.776 albertel 5704:
1.506 raeburn 5705: sub auto_get_sections {
1.508 raeburn 5706: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5707: my $homeserver;
5708: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5709: $homeserver = &homeserver($cnum,$cdom);
5710: }
5711: if (!defined($homeserver)) {
5712: if ($cdom =~ /^$match_domain$/) {
5713: $homeserver = &domain($cdom,'primary');
5714: }
5715: }
5716: my @secs;
5717: if (defined($homeserver)) {
5718: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5719: unless ($response eq 'refused') {
5720: @secs = split(/:/,$response);
5721: }
1.506 raeburn 5722: }
5723: return @secs;
5724: }
1.776 albertel 5725:
1.506 raeburn 5726: sub auto_new_course {
1.508 raeburn 5727: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5728: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5729: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5730: return $response;
5731: }
1.776 albertel 5732:
1.506 raeburn 5733: sub auto_validate_courseID {
1.508 raeburn 5734: my ($cnum,$cdom,$inst_course_id) = @_;
5735: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5736: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5737: return $response;
5738: }
1.776 albertel 5739:
1.1007 raeburn 5740: sub auto_validate_instcode {
1.1020 raeburn 5741: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5742: my ($homeserver,$response);
5743: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5744: $homeserver = &homeserver($cnum,$cdom);
5745: }
5746: if (!defined($homeserver)) {
5747: if ($cdom =~ /^$match_domain$/) {
5748: $homeserver = &domain($cdom,'primary');
5749: }
5750: }
1.1065 raeburn 5751: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5752: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5753: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5754: return ($outcome,$description);
1.1007 raeburn 5755: }
5756:
1.506 raeburn 5757: sub auto_create_password {
1.873 raeburn 5758: my ($cnum,$cdom,$authparam,$udom) = @_;
5759: my ($homeserver,$response);
1.506 raeburn 5760: my $create_passwd = 0;
5761: my $authchk = '';
1.873 raeburn 5762: if ($udom =~ /^$match_domain$/) {
5763: $homeserver = &domain($udom,'primary');
5764: }
5765: if ($homeserver eq '') {
5766: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5767: $homeserver = &homeserver($cnum,$cdom);
5768: }
5769: }
5770: if ($homeserver eq '') {
5771: $authchk = 'nodomain';
1.506 raeburn 5772: } else {
1.873 raeburn 5773: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5774: if ($response eq 'refused') {
5775: $authchk = 'refused';
5776: } else {
1.901 albertel 5777: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5778: }
1.506 raeburn 5779: }
5780: return ($authparam,$create_passwd,$authchk);
5781: }
5782:
1.706 raeburn 5783: sub auto_photo_permission {
5784: my ($cnum,$cdom,$students) = @_;
5785: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5786: my ($outcome,$perm_reqd,$conditions) =
5787: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5788: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5789: return (undef,undef);
5790: }
1.706 raeburn 5791: return ($outcome,$perm_reqd,$conditions);
5792: }
5793:
5794: sub auto_checkphotos {
5795: my ($uname,$udom,$pid) = @_;
5796: my $homeserver = &homeserver($uname,$udom);
5797: my ($result,$resulttype);
5798: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5799: &escape($uname).':'.&escape($pid),
5800: $homeserver));
1.709 albertel 5801: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5802: return (undef,undef);
5803: }
1.706 raeburn 5804: if ($outcome) {
5805: ($result,$resulttype) = split(/:/,$outcome);
5806: }
5807: return ($result,$resulttype);
5808: }
5809:
5810: sub auto_photochoice {
5811: my ($cnum,$cdom) = @_;
5812: my $homeserver = &homeserver($cnum,$cdom);
5813: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5814: &escape($cdom),
5815: $homeserver)));
1.709 albertel 5816: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5817: return (undef,undef);
5818: }
1.706 raeburn 5819: return ($update,$comment);
5820: }
5821:
5822: sub auto_photoupdate {
5823: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5824: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5825: my $host=&hostname($homeserver);
1.706 raeburn 5826: my $cmd = '';
5827: my $maxtries = 1;
1.800 albertel 5828: foreach my $affiliate (keys(%{$affiliatesref})) {
5829: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5830: }
5831: $cmd =~ s/%%$//;
5832: $cmd = &escape($cmd);
5833: my $query = 'institutionalphotos';
5834: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5835: unless ($queryid=~/^\Q$host\E\_/) {
5836: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5837: return 'error: '.$queryid;
5838: }
5839: my $reply = &get_query_reply($queryid);
5840: my $tries = 1;
5841: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5842: $reply = &get_query_reply($queryid);
5843: $tries ++;
5844: }
5845: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5846: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5847: } else {
5848: my @responses = split(/:/,$reply);
5849: my $outcome = shift(@responses);
5850: foreach my $item (@responses) {
5851: my ($key,$value) = split(/=/,$item);
5852: $$photo{$key} = $value;
5853: }
5854: return $outcome;
5855: }
5856: return 'error';
5857: }
5858:
1.521 raeburn 5859: sub auto_instcode_format {
1.793 albertel 5860: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5861: $cat_order) = @_;
1.521 raeburn 5862: my $courses = '';
1.772 raeburn 5863: my @homeservers;
1.521 raeburn 5864: if ($caller eq 'global') {
1.841 albertel 5865: my %servers = &get_servers($codedom,'library');
5866: foreach my $tryserver (keys(%servers)) {
5867: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5868: push(@homeservers,$tryserver);
5869: }
1.584 raeburn 5870: }
1.1022 raeburn 5871: } elsif ($caller eq 'requests') {
5872: if ($codedom =~ /^$match_domain$/) {
5873: my $chome = &domain($codedom,'primary');
5874: unless ($chome eq 'no_host') {
5875: push(@homeservers,$chome);
5876: }
5877: }
1.521 raeburn 5878: } else {
1.772 raeburn 5879: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5880: }
1.793 albertel 5881: foreach my $code (keys(%{$instcodes})) {
5882: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5883: }
5884: chop($courses);
1.772 raeburn 5885: my $ok_response = 0;
5886: my $response;
5887: while (@homeservers > 0 && $ok_response == 0) {
5888: my $server = shift(@homeservers);
5889: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5890: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5891: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5892: split(/:/,$response);
1.772 raeburn 5893: %{$codes} = (%{$codes},&str2hash($codes_str));
5894: push(@{$codetitles},&str2array($codetitles_str));
5895: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5896: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5897: $ok_response = 1;
5898: }
5899: }
5900: if ($ok_response) {
1.521 raeburn 5901: return 'ok';
1.772 raeburn 5902: } else {
5903: return $response;
1.521 raeburn 5904: }
5905: }
5906:
1.792 raeburn 5907: sub auto_instcode_defaults {
5908: my ($domain,$returnhash,$code_order) = @_;
5909: my @homeservers;
1.841 albertel 5910:
5911: my %servers = &get_servers($domain,'library');
5912: foreach my $tryserver (keys(%servers)) {
5913: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5914: push(@homeservers,$tryserver);
5915: }
1.792 raeburn 5916: }
1.841 albertel 5917:
1.792 raeburn 5918: my $response;
1.841 albertel 5919: foreach my $server (@homeservers) {
1.792 raeburn 5920: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5921: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5922:
5923: foreach my $pair (split(/\&/,$response)) {
5924: my ($name,$value)=split(/\=/,$pair);
5925: if ($name eq 'code_order') {
5926: @{$code_order} = split(/\&/,&unescape($value));
5927: } else {
5928: $returnhash->{&unescape($name)}=&unescape($value);
5929: }
5930: }
5931: return 'ok';
1.792 raeburn 5932: }
1.841 albertel 5933:
5934: return $response;
1.1003 raeburn 5935: }
5936:
5937: sub auto_possible_instcodes {
1.1007 raeburn 5938: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
5939: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
5940: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
5941: return;
5942: }
1.1003 raeburn 5943: my (@homeservers,$uhome);
5944: if (defined(&domain($domain,'primary'))) {
5945: $uhome=&domain($domain,'primary');
5946: push(@homeservers,&domain($domain,'primary'));
5947: } else {
5948: my %servers = &get_servers($domain,'library');
5949: foreach my $tryserver (keys(%servers)) {
5950: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5951: push(@homeservers,$tryserver);
5952: }
5953: }
5954: }
5955: my $response;
5956: foreach my $server (@homeservers) {
5957: $response=&reply('autopossibleinstcodes:'.$domain,$server);
5958: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 5959: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
5960: split(':',$response);
5961: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
5962: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 5963: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 5964: my ($name,$value)=split('=',$item);
5965: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5966: }
5967: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 5968: my ($name,$value)=split('=',$item);
5969: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 5970: }
5971: return 'ok';
5972: }
5973: return $response;
5974: }
1.792 raeburn 5975:
1.1010 raeburn 5976: sub auto_courserequest_checks {
5977: my ($dom) = @_;
1.1020 raeburn 5978: my ($homeserver,%validations);
5979: if ($dom =~ /^$match_domain$/) {
5980: $homeserver = &domain($dom,'primary');
5981: }
5982: unless ($homeserver eq 'no_host') {
5983: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
5984: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
5985: my @items = split(/&/,$response);
5986: foreach my $item (@items) {
5987: my ($key,$value) = split('=',$item);
5988: $validations{&unescape($key)} = &thaw_unescape($value);
5989: }
5990: }
5991: }
1.1010 raeburn 5992: return %validations;
5993: }
5994:
1.1020 raeburn 5995: sub auto_courserequest_validation {
5996: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
5997: my ($homeserver,$response);
5998: if ($dom =~ /^$match_domain$/) {
5999: $homeserver = &domain($dom,'primary');
6000: }
6001: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6002:
1.1020 raeburn 6003: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6004: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6005: ':'.&escape($instcode).':'.&escape($instseclist),
6006: $homeserver));
6007: }
6008: return $response;
6009: }
6010:
1.777 albertel 6011: sub auto_validate_class_sec {
1.918 raeburn 6012: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6013: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6014: my $ownerlist;
6015: if (ref($owners) eq 'ARRAY') {
6016: $ownerlist = join(',',@{$owners});
6017: } else {
6018: $ownerlist = $owners;
6019: }
1.773 raeburn 6020: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6021: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6022: return $response;
6023: }
6024:
1.679 raeburn 6025: # ------------------------------------------------------- Course Group routines
6026:
6027: sub get_coursegroups {
1.809 raeburn 6028: my ($cdom,$cnum,$group,$namespace) = @_;
6029: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6030: }
6031:
1.679 raeburn 6032: sub modify_coursegroup {
6033: my ($cdom,$cnum,$groupsettings) = @_;
6034: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6035: }
6036:
1.809 raeburn 6037: sub toggle_coursegroup_status {
6038: my ($cdom,$cnum,$group,$action) = @_;
6039: my ($from_namespace,$to_namespace);
6040: if ($action eq 'delete') {
6041: $from_namespace = 'coursegroups';
6042: $to_namespace = 'deleted_groups';
6043: } else {
6044: $from_namespace = 'deleted_groups';
6045: $to_namespace = 'coursegroups';
6046: }
6047: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6048: if (my $tmp = &error(%curr_group)) {
6049: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6050: return ('read error',$tmp);
6051: } else {
6052: my %savedsettings = %curr_group;
1.809 raeburn 6053: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6054: my $deloutcome;
6055: if ($result eq 'ok') {
1.809 raeburn 6056: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6057: } else {
6058: return ('write error',$result);
6059: }
6060: if ($deloutcome eq 'ok') {
6061: return 'ok';
6062: } else {
6063: return ('delete error',$deloutcome);
6064: }
6065: }
6066: }
6067:
1.679 raeburn 6068: sub modify_group_roles {
1.957 raeburn 6069: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6070: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6071: my $role = 'gr/'.&escape($userprivs);
6072: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6073: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6074: if ($result eq 'ok') {
6075: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6076: }
1.679 raeburn 6077: return $result;
6078: }
6079:
6080: sub modify_coursegroup_membership {
6081: my ($cdom,$cnum,$membership) = @_;
6082: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6083: return $result;
6084: }
6085:
1.682 raeburn 6086: sub get_active_groups {
6087: my ($udom,$uname,$cdom,$cnum) = @_;
6088: my $now = time;
6089: my %groups = ();
6090: foreach my $key (keys(%env)) {
1.811 albertel 6091: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6092: my ($start,$end) = split(/\./,$env{$key});
6093: if (($end!=0) && ($end<$now)) { next; }
6094: if (($start!=0) && ($start>$now)) { next; }
6095: if ($1 eq $cdom && $2 eq $cnum) {
6096: $groups{$3} = $env{$key} ;
6097: }
6098: }
6099: }
6100: return %groups;
6101: }
6102:
1.683 raeburn 6103: sub get_group_membership {
6104: my ($cdom,$cnum,$group) = @_;
6105: return(&dump('groupmembership',$cdom,$cnum,$group));
6106: }
6107:
6108: sub get_users_groups {
6109: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6110: my @usersgroups;
1.683 raeburn 6111: my $cachetime=1800;
6112:
6113: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6114: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6115: if (defined($cached)) {
1.734 albertel 6116: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6117: } else {
6118: $grouplist = '';
1.816 raeburn 6119: my $courseurl = &courseid_to_courseurl($courseid);
6120: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6121: my $access_end = $env{'course.'.$courseid.
6122: '.default_enrollment_end_date'};
6123: my $now = time;
6124: foreach my $key (keys(%roleshash)) {
6125: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6126: my $group = $1;
6127: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6128: my $start = $2;
6129: my $end = $1;
6130: if ($start == -1) { next; } # deleted from group
6131: if (($start!=0) && ($start>$now)) { next; }
6132: if (($end!=0) && ($end<$now)) {
6133: if ($access_end && $access_end < $now) {
6134: if ($access_end - $end < 86400) {
6135: push(@usersgroups,$group);
1.733 raeburn 6136: }
6137: }
1.817 raeburn 6138: next;
1.733 raeburn 6139: }
1.817 raeburn 6140: push(@usersgroups,$group);
1.683 raeburn 6141: }
6142: }
6143: }
1.817 raeburn 6144: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6145: $grouplist = join(':',@usersgroups);
6146: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6147: }
1.733 raeburn 6148: return @usersgroups;
1.683 raeburn 6149: }
6150:
6151: sub devalidate_getgroups_cache {
6152: my ($udom,$uname,$cdom,$cnum)=@_;
6153: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6154:
1.683 raeburn 6155: my $hashid="$udom:$uname:$courseid";
6156: &devalidate_cache_new('getgroups',$hashid);
6157: }
6158:
1.12 www 6159: # ------------------------------------------------------------------ Plain Text
6160:
6161: sub plaintext {
1.988 raeburn 6162: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6163: if ($short =~ m{^cr/}) {
1.758 albertel 6164: return (split('/',$short))[-1];
6165: }
1.742 raeburn 6166: if (!defined($cid)) {
6167: $cid = $env{'request.course.id'};
6168: }
6169: my %rolenames = (
1.1008 raeburn 6170: Course => 'std',
6171: Community => 'alt1',
1.742 raeburn 6172: );
1.1037 raeburn 6173: if ($cid ne '') {
6174: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6175: unless ($forcedefault) {
6176: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6177: &Apache::lonlocal::mt_escape(\$roletext);
6178: return &Apache::lonlocal::mt($roletext);
6179: }
6180: }
6181: }
6182: if ((defined($type)) && (defined($rolenames{$type})) &&
6183: (defined($rolenames{$type})) &&
6184: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6185: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6186: } elsif ($cid ne '') {
6187: my $crstype = $env{'course.'.$cid.'.type'};
6188: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6189: (defined($prp{$short}{$rolenames{$crstype}}))) {
6190: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6191: }
1.742 raeburn 6192: }
1.1037 raeburn 6193: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6194: }
6195:
6196: # ----------------------------------------------------------------- Assign Role
6197:
6198: sub assignrole {
1.957 raeburn 6199: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6200: $context)=@_;
1.21 www 6201: my $mrole;
6202: if ($role =~ /^cr\//) {
1.393 www 6203: my $cwosec=$url;
1.811 albertel 6204: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6205: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6206: my $refused = 1;
6207: if ($context eq 'requestcourses') {
6208: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6209: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6210: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6211: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6212: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6213: if ($crsenv{'internal.courseowner'} eq
6214: $env{'user.name'}.':'.$env{'user.domain'}) {
6215: $refused = '';
6216: }
6217: }
6218: }
6219: }
6220: }
6221: if ($refused) {
6222: &logthis('Refused custom assignrole: '.
6223: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6224: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6225: return 'refused';
6226: }
1.104 www 6227: }
1.21 www 6228: $mrole='cr';
1.678 raeburn 6229: } elsif ($role =~ /^gr\//) {
6230: my $cwogrp=$url;
1.811 albertel 6231: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6232: unless (&allowed('mdg',$cwogrp)) {
6233: &logthis('Refused group assignrole: '.
6234: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6235: $env{'user.name'}.' at '.$env{'user.domain'});
6236: return 'refused';
6237: }
6238: $mrole='gr';
1.21 www 6239: } else {
1.82 www 6240: my $cwosec=$url;
1.811 albertel 6241: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6242: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6243: my $refused;
6244: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6245: if (!(&allowed('c'.$role,$url))) {
6246: $refused = 1;
6247: }
6248: } else {
6249: $refused = 1;
6250: }
1.947 raeburn 6251: if ($refused) {
1.1045 raeburn 6252: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6253: if (!$selfenroll && $context eq 'course') {
6254: my %crsenv;
6255: if ($role eq 'cc' || $role eq 'co') {
6256: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6257: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6258: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6259: if ($crsenv{'internal.courseowner'} eq
6260: $env{'user.name'}.':'.$env{'user.domain'}) {
6261: $refused = '';
6262: }
6263: }
6264: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6265: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6266: if ($crsenv{'internal.courseowner'} eq
6267: $env{'user.name'}.':'.$env{'user.domain'}) {
6268: $refused = '';
6269: }
6270: }
6271: }
6272: }
6273: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6274: $refused = '';
1.1017 raeburn 6275: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6276: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6277: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6278: my $wrongcc;
6279: if ($cnum =~ /^$match_community$/) {
6280: $wrongcc = 1 if ($role eq 'cc');
6281: } else {
6282: $wrongcc = 1 if ($role eq 'co');
6283: }
6284: unless ($wrongcc) {
6285: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6286: if ($crsenv{'internal.courseowner'} eq
6287: $env{'user.name'}.':'.$env{'user.domain'}) {
6288: $refused = '';
6289: }
1.1017 raeburn 6290: }
6291: }
6292: }
6293: if ($refused) {
1.947 raeburn 6294: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6295: ' '.$role.' '.$end.' '.$start.' by '.
6296: $env{'user.name'}.' at '.$env{'user.domain'});
6297: return 'refused';
6298: }
1.932 raeburn 6299: }
1.104 www 6300: }
1.21 www 6301: $mrole=$role;
6302: }
1.620 albertel 6303: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6304: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6305: if ($end) { $command.='_'.$end; }
1.21 www 6306: if ($start) {
6307: if ($end) {
1.81 www 6308: $command.='_'.$start;
1.21 www 6309: } else {
1.81 www 6310: $command.='_0_'.$start;
1.21 www 6311: }
6312: }
1.739 raeburn 6313: my $origstart = $start;
6314: my $origend = $end;
1.957 raeburn 6315: my $delflag;
1.357 www 6316: # actually delete
6317: if ($deleteflag) {
1.373 www 6318: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6319: # modify command to delete the role
1.620 albertel 6320: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6321: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6322: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6323: # set start and finish to negative values for userrolelog
6324: $start=-1;
6325: $end=-1;
1.957 raeburn 6326: $delflag = 1;
1.357 www 6327: }
6328: }
6329: # send command
1.349 www 6330: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6331: # log new user role if status is ok
1.349 www 6332: if ($answer eq 'ok') {
1.663 raeburn 6333: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6334: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6335: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6336: unless ($role =~ /^gr/) {
6337: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6338: $origstart,$selfenroll,$context);
1.739 raeburn 6339: }
1.1053 raeburn 6340: if ($role eq 'cc') {
6341: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6342: }
1.349 www 6343: }
6344: return $answer;
1.169 harris41 6345: }
6346:
1.1053 raeburn 6347: sub autoupdate_coowners {
6348: my ($url,$end,$start,$uname,$udom) = @_;
6349: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6350: if (($cdom ne '') && ($cnum ne '')) {
6351: my $now = time;
6352: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6353: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6354: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6355: my $instcode = $coursehash{'internal.coursecode'};
6356: if ($instcode ne '') {
1.1056 raeburn 6357: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6358: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6359: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6360: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6361: if ($result eq 'valid') {
6362: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6363: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6364: push(@newcoowners,$coowner);
6365: }
6366: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6367: push(@newcoowners,$uname.':'.$udom);
6368: }
6369: @newcoowners = sort(@newcoowners);
6370: } else {
6371: push(@newcoowners,$uname.':'.$udom);
6372: }
6373: } else {
6374: if ($coursehash{'internal.co-owners'}) {
6375: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6376: unless ($coowner eq $uname.':'.$udom) {
6377: push(@newcoowners,$coowner);
6378: }
6379: }
6380: unless (@newcoowners > 0) {
6381: $delcoowners = 1;
6382: $coowners = '';
6383: }
6384: }
6385: }
6386: if (@newcoowners || $delcoowners) {
6387: &store_coowners($cdom,$cnum,$coursehash{'home'},
6388: $delcoowners,@newcoowners);
6389: }
6390: }
6391: }
6392: }
6393: }
6394: }
6395: }
6396:
6397: sub store_coowners {
6398: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6399: my $cid = $cdom.'_'.$cnum;
6400: my ($coowners,$delresult,$putresult);
6401: if (@newcoowners) {
6402: $coowners = join(',',@newcoowners);
6403: my %coownershash = (
6404: 'internal.co-owners' => $coowners,
6405: );
6406: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6407: if ($putresult eq 'ok') {
6408: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6409: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6410: }
6411: }
6412: }
6413: if ($delcoowners) {
6414: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6415: if ($delresult eq 'ok') {
6416: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6417: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6418: }
6419: }
6420: }
6421: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6422: my %crsinfo =
6423: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6424: if (ref($crsinfo{$cid}) eq 'HASH') {
6425: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6426: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6427: }
6428: }
6429: }
6430:
1.169 harris41 6431: # -------------------------------------------------- Modify user authentication
1.197 www 6432: # Overrides without validation
6433:
1.169 harris41 6434: sub modifyuserauth {
6435: my ($udom,$uname,$umode,$upass)=@_;
6436: my $uhome=&homeserver($uname,$udom);
1.197 www 6437: unless (&allowed('mau',$udom)) { return 'refused'; }
6438: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6439: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6440: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6441: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6442: &escape($upass),$uhome);
1.620 albertel 6443: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6444: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6445: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6446: &log($udom,,$uname,$uhome,
1.620 albertel 6447: 'Authentication changed by '.$env{'user.domain'}.', '.
6448: $env{'user.name'}.', '.$umode.
1.197 www 6449: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6450: unless ($reply eq 'ok') {
1.197 www 6451: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6452: return 'error: '.$reply;
6453: }
1.170 harris41 6454: return 'ok';
1.80 www 6455: }
6456:
1.81 www 6457: # --------------------------------------------------------------- Modify a user
1.80 www 6458:
1.81 www 6459: sub modifyuser {
1.206 matthew 6460: my ($udom, $uname, $uid,
6461: $umode, $upass, $first,
6462: $middle, $last, $gene,
1.1058 raeburn 6463: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6464: $udom= &LONCAPA::clean_domain($udom);
6465: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6466: my $showcandelete = 'none';
6467: if (ref($candelete) eq 'ARRAY') {
6468: if (@{$candelete} > 0) {
6469: $showcandelete = join(', ',@{$candelete});
6470: }
6471: }
1.81 www 6472: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6473: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6474: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6475: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6476: ' desiredhome not specified').
1.620 albertel 6477: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6478: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6479: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 6480: # ----------------------------------------------------------------- Create User
1.406 albertel 6481: if (($uhome eq 'no_host') &&
6482: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6483: my $unhome='';
1.844 albertel 6484: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6485: $unhome = $desiredhome;
1.620 albertel 6486: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6487: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6488: } else { # load balancing routine for determining $unhome
1.81 www 6489: my $loadm=10000000;
1.841 albertel 6490: my %servers = &get_servers($udom,'library');
6491: foreach my $tryserver (keys(%servers)) {
6492: my $answer=reply('load',$tryserver);
6493: if (($answer=~/\d+/) && ($answer<$loadm)) {
6494: $loadm=$answer;
6495: $unhome=$tryserver;
6496: }
1.80 www 6497: }
6498: }
6499: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6500: return 'error: unable to find a home server for '.$uname.
6501: ' in domain '.$udom;
1.80 www 6502: }
6503: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6504: &escape($upass),$unhome);
6505: unless ($reply eq 'ok') {
6506: return 'error: '.$reply;
6507: }
1.230 stredwic 6508: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6509: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6510: return 'error: unable verify users home machine.';
1.80 www 6511: }
1.209 matthew 6512: } # End of creation of new user
1.80 www 6513: # ---------------------------------------------------------------------- Add ID
6514: if ($uid) {
6515: $uid=~tr/A-Z/a-z/;
6516: my %uidhash=&idrget($udom,$uname);
1.196 www 6517: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6518: && (!$forceid)) {
1.80 www 6519: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6520: return 'error: user id "'.$uid.'" does not match '.
6521: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6522: }
6523: } else {
6524: &idput($udom,($uname => $uid));
6525: }
6526: }
6527: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6528: my @tmp=&get('environment',
1.899 raeburn 6529: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6530: 'permanentemail','inststatus'],
1.134 albertel 6531: $udom,$uname);
1.313 matthew 6532: my %names;
6533: if ($tmp[0] =~ m/^error:.*/) {
6534: %names=();
6535: } else {
6536: %names = @tmp;
6537: }
1.388 www 6538: #
1.1058 raeburn 6539: # If name, email and/or uid are blank (e.g., because an uploaded file
6540: # of users did not contain them), do not overwrite existing values
6541: # unless field is in $candelete array ref.
6542: #
6543:
6544: my @fields = ('firstname','middlename','lastname','generation',
6545: 'permanentemail','id');
6546: my %newvalues;
6547: if (ref($candelete) eq 'ARRAY') {
6548: foreach my $field (@fields) {
6549: if (grep(/^\Q$field\E$/,@{$candelete})) {
6550: if ($field eq 'firstname') {
6551: $names{$field} = $first;
6552: } elsif ($field eq 'middlename') {
6553: $names{$field} = $middle;
6554: } elsif ($field eq 'lastname') {
6555: $names{$field} = $last;
6556: } elsif ($field eq 'generation') {
6557: $names{$field} = $gene;
6558: } elsif ($field eq 'permanentemail') {
6559: $names{$field} = $email;
6560: } elsif ($field eq 'id') {
6561: $names{$field} = $uid;
6562: }
6563: }
6564: }
6565: }
1.388 www 6566: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6567: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6568: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6569: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6570: if ($email) {
6571: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6572: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6573: }
1.899 raeburn 6574: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6575: if (defined($inststatus)) {
6576: $names{'inststatus'} = '';
6577: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6578: if (ref($usertypes) eq 'HASH') {
6579: my @okstatuses;
6580: foreach my $item (split(/:/,$inststatus)) {
6581: if (defined($usertypes->{$item})) {
6582: push(@okstatuses,$item);
6583: }
6584: }
6585: if (@okstatuses) {
6586: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6587: }
6588: }
6589: }
1.134 albertel 6590: my $reply = &put('environment', \%names, $udom,$uname);
6591: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 6592: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 6593: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 6594: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6595: $umode.', '.$first.', '.$middle.', '.
6596: $last.', '.$gene.', '.$email.', '.$inststatus;
6597: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6598: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6599: } else {
6600: $logmsg .= ' during self creation';
6601: }
6602: &logthis($logmsg);
1.134 albertel 6603: return 'ok';
1.80 www 6604: }
6605:
1.81 www 6606: # -------------------------------------------------------------- Modify student
1.80 www 6607:
1.81 www 6608: sub modifystudent {
6609: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6610: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6611: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6612: if (!$cid) {
1.620 albertel 6613: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6614: return 'not_in_class';
6615: }
1.80 www 6616: }
6617: # --------------------------------------------------------------- Make the user
1.81 www 6618: my $reply=&modifyuser
1.209 matthew 6619: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6620: $desiredhome,$email,$inststatus);
1.80 www 6621: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6622: # This will cause &modify_student_enrollment to get the uid from the
6623: # students environment
6624: $uid = undef if (!$forceid);
1.455 albertel 6625: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6626: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6627: return $reply;
6628: }
6629:
6630: sub modify_student_enrollment {
1.957 raeburn 6631: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6632: my ($cdom,$cnum,$chome);
6633: if (!$cid) {
1.620 albertel 6634: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6635: return 'not_in_class';
6636: }
1.620 albertel 6637: $cdom=$env{'course.'.$cid.'.domain'};
6638: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6639: } else {
6640: ($cdom,$cnum)=split(/_/,$cid);
6641: }
1.620 albertel 6642: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6643: if (!$chome) {
1.457 raeburn 6644: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6645: }
1.455 albertel 6646: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6647: # Make sure the user exists
1.81 www 6648: my $uhome=&homeserver($uname,$udom);
6649: if (($uhome eq '') || ($uhome eq 'no_host')) {
6650: return 'error: no such user';
6651: }
1.297 matthew 6652: # Get student data if we were not given enough information
6653: if (!defined($first) || $first eq '' ||
6654: !defined($last) || $last eq '' ||
6655: !defined($uid) || $uid eq '' ||
6656: !defined($middle) || $middle eq '' ||
6657: !defined($gene) || $gene eq '') {
1.294 matthew 6658: # They did not supply us with enough data to enroll the student, so
6659: # we need to pick up more information.
1.297 matthew 6660: my %tmp = &get('environment',
1.294 matthew 6661: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6662: ,$udom,$uname);
6663:
1.800 albertel 6664: #foreach my $key (keys(%tmp)) {
6665: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6666: #}
1.294 matthew 6667: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6668: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6669: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6670: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6671: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6672: }
1.556 albertel 6673: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6674: my $reply=cput('classlist',
6675: {"$uname:$udom" =>
1.515 raeburn 6676: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6677: $cdom,$cnum);
1.81 www 6678: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6679: return 'error: '.$reply;
1.652 albertel 6680: } else {
6681: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6682: }
1.297 matthew 6683: # Add student role to user
1.83 www 6684: my $uurl='/'.$cid;
1.81 www 6685: $uurl=~s/\_/\//g;
6686: if ($usec) {
6687: $uurl.='/'.$usec;
6688: }
1.957 raeburn 6689: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6690: }
6691:
1.556 albertel 6692: sub format_name {
6693: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6694: my $name;
6695: if ($first ne 'lastname') {
6696: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6697: } else {
6698: if ($lastname=~/\S/) {
6699: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6700: $name=~s/\s+,/,/;
6701: } else {
6702: $name.= $firstname.' '.$middlename.' '.$generation;
6703: }
6704: }
6705: $name=~s/^\s+//;
6706: $name=~s/\s+$//;
6707: $name=~s/\s+/ /g;
6708: return $name;
6709: }
6710:
1.84 www 6711: # ------------------------------------------------- Write to course preferences
6712:
6713: sub writecoursepref {
6714: my ($courseid,%prefs)=@_;
6715: $courseid=~s/^\///;
6716: $courseid=~s/\_/\//g;
6717: my ($cdomain,$cnum)=split(/\//,$courseid);
6718: my $chome=homeserver($cnum,$cdomain);
6719: if (($chome eq '') || ($chome eq 'no_host')) {
6720: return 'error: no such course';
6721: }
6722: my $cstring='';
1.800 albertel 6723: foreach my $pref (keys(%prefs)) {
6724: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6725: }
1.84 www 6726: $cstring=~s/\&$//;
6727: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6728: }
6729:
6730: # ---------------------------------------------------------- Make/modify course
6731:
6732: sub createcourse {
1.741 raeburn 6733: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6734: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 6735: $url=&declutter($url);
6736: my $cid='';
1.1028 raeburn 6737: if ($context eq 'requestcourses') {
6738: my $can_create = 0;
6739: my ($ownername,$ownerdom) = split(':',$course_owner);
6740: if ($udom eq $ownerdom) {
6741: if (&usertools_access($ownername,$ownerdom,$category,undef,
6742: $context)) {
6743: $can_create = 1;
6744: }
6745: } else {
6746: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6747: $category);
6748: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6749: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6750: if (@curr > 0) {
6751: my @options = qw(approval validate autolimit);
6752: my $optregex = join('|',@options);
6753: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6754: $can_create = 1;
6755: }
6756: }
6757: }
6758: }
6759: if ($can_create) {
6760: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6761: unless (&allowed('ccc',$udom)) {
6762: return 'refused';
6763: }
1.1017 raeburn 6764: }
6765: } else {
6766: return 'refused';
6767: }
1.1028 raeburn 6768: } elsif (!&allowed('ccc',$udom)) {
6769: return 'refused';
1.84 www 6770: }
1.1011 raeburn 6771: # --------------------------------------------------------------- Get Unique ID
6772: my $uname;
6773: if ($cnum =~ /^$match_courseid$/) {
6774: my $chome=&homeserver($cnum,$udom,'true');
6775: if (($chome eq '') || ($chome eq 'no_host')) {
6776: $uname = $cnum;
6777: } else {
1.1038 raeburn 6778: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6779: }
6780: } else {
1.1038 raeburn 6781: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6782: }
6783: return $uname if ($uname =~ /^error/);
6784: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 6785: if (!defined($course_server)) {
6786: if (defined(&domain($udom,'primary'))) {
6787: $course_server = &domain($udom,'primary');
6788: } else {
6789: $course_server = $env{'user.home'};
6790: }
6791: }
6792: my %host_servers =
6793: &Apache::lonnet::get_servers($udom,'library');
6794: unless ($host_servers{$course_server}) {
6795: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 6796: }
1.84 www 6797: # ------------------------------------------------------------- Make the course
6798: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6799: $course_server);
1.84 www 6800: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 6801: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6802: if (($uhome eq '') || ($uhome eq 'no_host')) {
6803: return 'error: no such course';
6804: }
1.271 www 6805: # ----------------------------------------------------------------- Course made
1.516 raeburn 6806: # log existence
1.1029 raeburn 6807: my $now = time;
1.918 raeburn 6808: my $newcourse = {
6809: $udom.'_'.$uname => {
1.921 raeburn 6810: description => $description,
6811: inst_code => $inst_code,
6812: owner => $course_owner,
6813: type => $crstype,
1.1029 raeburn 6814: creator => $env{'user.name'}.':'.
6815: $env{'user.domain'},
6816: created => $now,
6817: context => $context,
1.918 raeburn 6818: },
6819: };
1.921 raeburn 6820: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6821: # set toplevel url
1.271 www 6822: my $topurl=$url;
6823: unless ($nonstandard) {
6824: # ------------------------------------------ For standard courses, make top url
6825: my $mapurl=&clutter($url);
1.278 www 6826: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6827: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6828: <map>
6829: <resource id="1" type="start"></resource>
6830: <resource id="2" src="$mapurl"></resource>
6831: <resource id="3" type="finish"></resource>
6832: <link index="1" from="1" to="2"></link>
6833: <link index="2" from="2" to="3"></link>
6834: </map>
6835: ENDINITMAP
6836: $topurl=&declutter(
1.638 albertel 6837: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6838: );
6839: }
6840: # ----------------------------------------------------------- Write preferences
1.84 www 6841: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 6842: ('description' => $description,
6843: 'url' => $topurl,
6844: 'internal.creator' => $env{'user.name'}.':'.
6845: $env{'user.domain'},
6846: 'internal.created' => $now,
6847: 'internal.creationcontext' => $context)
6848: );
1.84 www 6849: return '/'.$udom.'/'.$uname;
6850: }
6851:
1.1011 raeburn 6852: # ------------------------------------------------------------------- Create ID
6853: sub generate_coursenum {
1.1038 raeburn 6854: my ($udom,$crstype) = @_;
1.1011 raeburn 6855: my $domdesc = &domain($udom);
6856: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 6857: my $first;
6858: if ($crstype eq 'Community') {
6859: $first = '0';
6860: } else {
6861: $first = int(1+rand(9));
6862: }
6863: my $uname=$first.
1.1011 raeburn 6864: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6865: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6866: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6867: # ----------------------------------------------- Make sure that does not exist
6868: my $uhome=&homeserver($uname,$udom,'true');
6869: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 6870: if ($crstype eq 'Community') {
6871: $first = '0';
6872: } else {
6873: $first = int(1+rand(9));
6874: }
6875: $uname=$first.
1.1011 raeburn 6876: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6877: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6878: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6879: $uhome=&homeserver($uname,$udom,'true');
6880: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6881: return 'error: unable to generate unique course-ID';
6882: }
6883: }
6884: return $uname;
6885: }
6886:
1.813 albertel 6887: sub is_course {
6888: my ($cdom,$cnum) = @_;
6889: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6890: undef,'.');
1.813 albertel 6891: if (exists($courses{$cdom.'_'.$cnum})) {
6892: return 1;
6893: }
6894: return 0;
6895: }
6896:
1.1015 raeburn 6897: sub store_userdata {
6898: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 6899: my $result;
1.1016 raeburn 6900: if ($datakey ne '') {
1.1013 raeburn 6901: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 6902: if ($udom eq '' || $uname eq '') {
6903: $udom = $env{'user.domain'};
6904: $uname = $env{'user.name'};
6905: }
6906: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 6907: if (($uhome eq '') || ($uhome eq 'no_host')) {
6908: $result = 'error: no_host';
6909: } else {
6910: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
6911: $storehash->{'host'} = $perlvar{'lonHostID'};
6912:
6913: my $namevalue='';
6914: foreach my $key (keys(%{$storehash})) {
6915: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6916: }
6917: $namevalue=~s/\&$//;
6918: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 6919: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 6920: }
6921: } else {
6922: $result = 'error: data to store was not a hash reference';
6923: }
6924: } else {
6925: $result= 'error: invalid requestkey';
6926: }
6927: return $result;
6928: }
6929:
1.21 www 6930: # ---------------------------------------------------------- Assign Custom Role
6931:
6932: sub assigncustomrole {
1.957 raeburn 6933: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6934: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6935: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6936: }
6937:
6938: # ----------------------------------------------------------------- Revoke Role
6939:
6940: sub revokerole {
1.957 raeburn 6941: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6942: my $now=time;
1.965 raeburn 6943: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6944: }
6945:
6946: # ---------------------------------------------------------- Revoke Custom Role
6947:
6948: sub revokecustomrole {
1.957 raeburn 6949: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6950: my $now=time;
1.357 www 6951: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6952: $deleteflag,$selfenroll,$context);
1.17 www 6953: }
6954:
1.533 banghart 6955: # ------------------------------------------------------------ Disk usage
1.535 albertel 6956: sub diskusage {
1.955 raeburn 6957: my ($udom,$uname,$directorypath,$getpropath)=@_;
6958: $directorypath =~ s/\/$//;
6959: my $listing=&reply('du2:'.&escape($directorypath).':'
6960: .&escape($getpropath).':'.&escape($uname).':'
6961: .&escape($udom),homeserver($uname,$udom));
6962: if ($listing eq 'unknown_cmd') {
6963: if ($getpropath) {
6964: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6965: }
6966: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6967: }
1.514 albertel 6968: return $listing;
1.512 banghart 6969: }
6970:
1.566 banghart 6971: sub is_locked {
6972: my ($file_name, $domain, $user) = @_;
6973: my @check;
6974: my $is_locked;
6975: push @check, $file_name;
1.613 albertel 6976: my %locked = &get('file_permissions',\@check,
1.620 albertel 6977: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6978: my ($tmp)=keys(%locked);
6979: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6980:
1.566 banghart 6981: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6982: $is_locked = 'false';
6983: foreach my $entry (@{$locked{$file_name}}) {
6984: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6985: $is_locked = 'true';
6986: last;
1.745 raeburn 6987: }
6988: }
1.566 banghart 6989: } else {
6990: $is_locked = 'false';
6991: }
6992: }
6993:
1.759 albertel 6994: sub declutter_portfile {
6995: my ($file) = @_;
1.833 albertel 6996: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6997: return $file;
6998: }
6999:
1.559 banghart 7000: # ------------------------------------------------------------- Mark as Read Only
7001:
7002: sub mark_as_readonly {
7003: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7004: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7005: my ($tmp)=keys(%current_permissions);
7006: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7007: foreach my $file (@{$files}) {
1.759 albertel 7008: $file = &declutter_portfile($file);
1.561 banghart 7009: push(@{$current_permissions{$file}},$what);
1.559 banghart 7010: }
1.613 albertel 7011: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7012: return;
7013: }
7014:
1.572 banghart 7015: # ------------------------------------------------------------Save Selected Files
7016:
7017: sub save_selected_files {
7018: my ($user, $path, @files) = @_;
7019: my $filename = $user."savedfiles";
1.573 banghart 7020: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7021: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7022: foreach my $file (@files) {
1.620 albertel 7023: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7024: }
7025: foreach my $file (@other_files) {
1.574 banghart 7026: print (OUT $file."\n");
1.572 banghart 7027: }
1.574 banghart 7028: close (OUT);
1.572 banghart 7029: return 'ok';
7030: }
7031:
1.574 banghart 7032: sub clear_selected_files {
7033: my ($user) = @_;
7034: my $filename = $user."savedfiles";
7035: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7036: print (OUT undef);
7037: close (OUT);
7038: return ("ok");
7039: }
7040:
1.572 banghart 7041: sub files_in_path {
7042: my ($user, $path) = @_;
7043: my $filename = $user."savedfiles";
7044: my %return_files;
1.574 banghart 7045: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7046: while (my $line_in = <IN>) {
1.574 banghart 7047: chomp ($line_in);
7048: my @paths_and_file = split (m!/!, $line_in);
7049: my $file_part = pop (@paths_and_file);
7050: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7051: $path_part.='/';
7052: my $path_and_file = $path_part.$file_part;
7053: if ($path_part eq $path) {
7054: $return_files{$file_part}= 'selected';
7055: }
7056: }
1.574 banghart 7057: close (IN);
7058: return (\%return_files);
1.572 banghart 7059: }
7060:
7061: # called in portfolio select mode, to show files selected NOT in current directory
7062: sub files_not_in_path {
7063: my ($user, $path) = @_;
7064: my $filename = $user."savedfiles";
7065: my @return_files;
7066: my $path_part;
1.800 albertel 7067: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7068: while (my $line = <IN>) {
1.572 banghart 7069: #ok, I know it's clunky, but I want it to work
1.800 albertel 7070: my @paths_and_file = split(m|/|, $line);
7071: my $file_part = pop(@paths_and_file);
7072: chomp($file_part);
7073: my $path_part = join('/', @paths_and_file);
1.572 banghart 7074: $path_part .= '/';
7075: my $path_and_file = $path_part.$file_part;
7076: if ($path_part ne $path) {
1.800 albertel 7077: push(@return_files, ($path_and_file));
1.572 banghart 7078: }
7079: }
1.800 albertel 7080: close(OUT);
1.574 banghart 7081: return (@return_files);
1.572 banghart 7082: }
7083:
1.745 raeburn 7084: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7085:
1.745 raeburn 7086: sub get_portfile_permissions {
7087: my ($domain,$user) = @_;
1.613 albertel 7088: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7089: my ($tmp)=keys(%current_permissions);
7090: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7091: return \%current_permissions;
7092: }
7093:
7094: #---------------------------------------------Get portfolio file access controls
7095:
1.749 raeburn 7096: sub get_access_controls {
1.745 raeburn 7097: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7098: my %access;
7099: my $real_file = $file;
7100: $file =~ s/\.meta$//;
1.745 raeburn 7101: if (defined($file)) {
1.749 raeburn 7102: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7103: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7104: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7105: }
7106: }
1.745 raeburn 7107: } else {
1.749 raeburn 7108: foreach my $key (keys(%{$current_permissions})) {
7109: if ($key =~ /\0accesscontrol$/) {
7110: if (defined($group)) {
7111: if ($key !~ m-^\Q$group\E/-) {
7112: next;
7113: }
7114: }
7115: my ($fullpath) = split(/\0/,$key);
7116: if (ref($$current_permissions{$key}) eq 'HASH') {
7117: foreach my $control (keys(%{$$current_permissions{$key}})) {
7118: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7119: }
7120: }
7121: }
7122: }
7123: }
7124: return %access;
7125: }
7126:
7127: sub modify_access_controls {
7128: my ($file_name,$changes,$domain,$user)=@_;
7129: my ($outcome,$deloutcome);
7130: my %store_permissions;
7131: my %new_values;
7132: my %new_control;
7133: my %translation;
7134: my @deletions = ();
7135: my $now = time;
7136: if (exists($$changes{'activate'})) {
7137: if (ref($$changes{'activate'}) eq 'HASH') {
7138: my @newitems = sort(keys(%{$$changes{'activate'}}));
7139: my $numnew = scalar(@newitems);
7140: for (my $i=0; $i<$numnew; $i++) {
7141: my $newkey = $newitems[$i];
7142: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7143: if ($newkey =~ /^\d+:/) {
7144: $newkey =~ s/^(\d+)/$newid/;
7145: $translation{$1} = $newid;
7146: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7147: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7148: $translation{$1} = $newid;
7149: }
1.749 raeburn 7150: $new_values{$file_name."\0".$newkey} =
7151: $$changes{'activate'}{$newitems[$i]};
7152: $new_control{$newkey} = $now;
7153: }
7154: }
7155: }
7156: my %todelete;
7157: my %changed_items;
7158: foreach my $action ('delete','update') {
7159: if (exists($$changes{$action})) {
7160: if (ref($$changes{$action}) eq 'HASH') {
7161: foreach my $key (keys(%{$$changes{$action}})) {
7162: my ($itemnum) = ($key =~ /^([^:]+):/);
7163: if ($action eq 'delete') {
7164: $todelete{$itemnum} = 1;
7165: } else {
7166: $changed_items{$itemnum} = $key;
7167: }
7168: }
1.745 raeburn 7169: }
7170: }
1.749 raeburn 7171: }
7172: # get lock on access controls for file.
7173: my $lockhash = {
7174: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7175: ':'.$env{'user.domain'},
7176: };
7177: my $tries = 0;
7178: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7179:
7180: while (($gotlock ne 'ok') && $tries <3) {
7181: $tries ++;
7182: sleep 1;
7183: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7184: }
7185: if ($gotlock eq 'ok') {
7186: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7187: my ($tmp)=keys(%curr_permissions);
7188: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7189: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7190: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7191: if (ref($curr_controls) eq 'HASH') {
7192: foreach my $control_item (keys(%{$curr_controls})) {
7193: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7194: if (defined($todelete{$itemnum})) {
7195: push(@deletions,$file_name."\0".$control_item);
7196: } else {
7197: if (defined($changed_items{$itemnum})) {
7198: $new_control{$changed_items{$itemnum}} = $now;
7199: push(@deletions,$file_name."\0".$control_item);
7200: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7201: } else {
7202: $new_control{$control_item} = $$curr_controls{$control_item};
7203: }
7204: }
1.745 raeburn 7205: }
7206: }
7207: }
1.970 raeburn 7208: my ($group);
7209: if (&is_course($domain,$user)) {
7210: ($group,my $file) = split(/\//,$file_name,2);
7211: }
1.749 raeburn 7212: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7213: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7214: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7215: # remove lock
7216: my @del_lock = ($file_name."\0".'locked_access_records');
7217: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7218: my $sqlresult =
1.970 raeburn 7219: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7220: $group);
1.749 raeburn 7221: } else {
7222: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7223: }
1.749 raeburn 7224: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7225: }
7226:
1.827 raeburn 7227: sub make_public_indefinitely {
7228: my ($requrl) = @_;
7229: my $now = time;
7230: my $action = 'activate';
7231: my $aclnum = 0;
7232: if (&is_portfolio_url($requrl)) {
7233: my (undef,$udom,$unum,$file_name,$group) =
7234: &parse_portfolio_url($requrl);
7235: my $current_perms = &get_portfile_permissions($udom,$unum);
7236: my %access_controls = &get_access_controls($current_perms,
7237: $group,$file_name);
7238: foreach my $key (keys(%{$access_controls{$file_name}})) {
7239: my ($num,$scope,$end,$start) =
7240: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7241: if ($scope eq 'public') {
7242: if ($start <= $now && $end == 0) {
7243: $action = 'none';
7244: } else {
7245: $action = 'update';
7246: $aclnum = $num;
7247: }
7248: last;
7249: }
7250: }
7251: if ($action eq 'none') {
7252: return 'ok';
7253: } else {
7254: my %changes;
7255: my $newend = 0;
7256: my $newstart = $now;
7257: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7258: $changes{$action}{$newkey} = {
7259: type => 'public',
7260: time => {
7261: start => $newstart,
7262: end => $newend,
7263: },
7264: };
7265: my ($outcome,$deloutcome,$new_values,$translation) =
7266: &modify_access_controls($file_name,\%changes,$udom,$unum);
7267: return $outcome;
7268: }
7269: } else {
7270: return 'invalid';
7271: }
7272: }
7273:
1.745 raeburn 7274: #------------------------------------------------------Get Marked as Read Only
7275:
7276: sub get_marked_as_readonly {
7277: my ($domain,$user,$what,$group) = @_;
7278: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7279: my @readonly_files;
1.629 banghart 7280: my $cmp1=$what;
7281: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7282: while (my ($file_name,$value) = each(%{$current_permissions})) {
7283: if (defined($group)) {
7284: if ($file_name !~ m-^\Q$group\E/-) {
7285: next;
7286: }
7287: }
1.561 banghart 7288: if (ref($value) eq "ARRAY"){
7289: foreach my $stored_what (@{$value}) {
1.629 banghart 7290: my $cmp2=$stored_what;
1.759 albertel 7291: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7292: $cmp2=join('',@{$stored_what});
1.745 raeburn 7293: }
1.629 banghart 7294: if ($cmp1 eq $cmp2) {
1.561 banghart 7295: push(@readonly_files, $file_name);
1.745 raeburn 7296: last;
1.563 banghart 7297: } elsif (!defined($what)) {
7298: push(@readonly_files, $file_name);
1.745 raeburn 7299: last;
1.561 banghart 7300: }
7301: }
1.745 raeburn 7302: }
1.561 banghart 7303: }
7304: return @readonly_files;
7305: }
1.577 banghart 7306: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7307:
1.577 banghart 7308: sub get_marked_as_readonly_hash {
1.745 raeburn 7309: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7310: my %readonly_files;
1.745 raeburn 7311: while (my ($file_name,$value) = each(%{$current_permissions})) {
7312: if (defined($group)) {
7313: if ($file_name !~ m-^\Q$group\E/-) {
7314: next;
7315: }
7316: }
1.577 banghart 7317: if (ref($value) eq "ARRAY"){
7318: foreach my $stored_what (@{$value}) {
1.745 raeburn 7319: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7320: foreach my $lock_descriptor(@{$stored_what}) {
7321: if ($lock_descriptor eq 'graded') {
7322: $readonly_files{$file_name} = 'graded';
7323: } elsif ($lock_descriptor eq 'handback') {
7324: $readonly_files{$file_name} = 'handback';
7325: } else {
7326: if (!exists($readonly_files{$file_name})) {
7327: $readonly_files{$file_name} = 'locked';
7328: }
7329: }
1.745 raeburn 7330: }
1.750 banghart 7331: }
1.577 banghart 7332: }
7333: }
7334: }
7335: return %readonly_files;
7336: }
1.559 banghart 7337: # ------------------------------------------------------------ Unmark as Read Only
7338:
7339: sub unmark_as_readonly {
1.629 banghart 7340: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7341: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7342: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7343: $file_name = &declutter_portfile($file_name);
1.634 albertel 7344: my $symb_crs = $what;
7345: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7346: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7347: my ($tmp)=keys(%current_permissions);
7348: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7349: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7350: foreach my $file (@readonly_files) {
1.759 albertel 7351: my $clean_file = &declutter_portfile($file);
7352: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7353: my $current_locks = $current_permissions{$file};
1.563 banghart 7354: my @new_locks;
7355: my @del_keys;
7356: if (ref($current_locks) eq "ARRAY"){
7357: foreach my $locker (@{$current_locks}) {
1.632 albertel 7358: my $compare=$locker;
1.749 raeburn 7359: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7360: $compare=join('',@{$locker});
1.746 raeburn 7361: if ($compare ne $symb_crs) {
7362: push(@new_locks, $locker);
7363: }
1.563 banghart 7364: }
7365: }
1.650 albertel 7366: if (scalar(@new_locks) > 0) {
1.563 banghart 7367: $current_permissions{$file} = \@new_locks;
7368: } else {
7369: push(@del_keys, $file);
1.613 albertel 7370: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7371: delete($current_permissions{$file});
1.563 banghart 7372: }
7373: }
1.561 banghart 7374: }
1.613 albertel 7375: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7376: return;
7377: }
1.512 banghart 7378:
1.17 www 7379: # ------------------------------------------------------------ Directory lister
7380:
7381: sub dirlist {
1.955 raeburn 7382: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7383: $uri=~s/^\///;
7384: $uri=~s/\/$//;
1.253 stredwic 7385: my ($udom, $uname);
1.955 raeburn 7386: if ($getuserdir) {
1.253 stredwic 7387: $udom = $userdomain;
7388: $uname = $username;
1.955 raeburn 7389: } else {
7390: (undef,$udom,$uname)=split(/\//,$uri);
7391: if(defined($userdomain)) {
7392: $udom = $userdomain;
7393: }
7394: if(defined($username)) {
7395: $uname = $username;
7396: }
1.253 stredwic 7397: }
1.955 raeburn 7398: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7399:
1.955 raeburn 7400: $dirRoot = $perlvar{'lonDocRoot'};
7401: if (defined($getpropath)) {
7402: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7403: $dirRoot =~ s/\/$//;
1.955 raeburn 7404: } elsif (defined($getuserdir)) {
7405: my $subdir=$uname.'__';
7406: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7407: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7408: ."/$udom/$subdir/$uname";
7409: } elsif (defined($alternateRoot)) {
7410: $dirRoot = $alternateRoot;
1.751 banghart 7411: }
1.253 stredwic 7412:
7413: if($udom) {
7414: if($uname) {
1.955 raeburn 7415: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7416: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7417: .':'.&escape($uname).':'.&escape($udom),
7418: &homeserver($uname,$udom));
7419: if ($listing eq 'unknown_cmd') {
7420: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7421: &homeserver($uname,$udom));
7422: } else {
7423: @listing_results = map { &unescape($_); } split(/:/,$listing);
7424: }
1.605 matthew 7425: if ($listing eq 'unknown_cmd') {
1.800 albertel 7426: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7427: &homeserver($uname,$udom));
1.605 matthew 7428: @listing_results = split(/:/,$listing);
7429: } else {
7430: @listing_results = map { &unescape($_); } split(/:/,$listing);
7431: }
7432: return @listing_results;
1.955 raeburn 7433: } elsif(!$alternateRoot) {
1.800 albertel 7434: my %allusers;
1.841 albertel 7435: my %servers = &get_servers($udom,'library');
1.955 raeburn 7436: foreach my $tryserver (keys(%servers)) {
7437: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7438: &escape($udom),$tryserver);
7439: if ($listing eq 'unknown_cmd') {
7440: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7441: $udom, $tryserver);
7442: } else {
7443: @listing_results = map { &unescape($_); } split(/:/,$listing);
7444: }
1.841 albertel 7445: if ($listing eq 'unknown_cmd') {
7446: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7447: $udom, $tryserver);
7448: @listing_results = split(/:/,$listing);
7449: } else {
7450: @listing_results =
7451: map { &unescape($_); } split(/:/,$listing);
7452: }
7453: if ($listing_results[0] ne 'no_such_dir' &&
7454: $listing_results[0] ne 'empty' &&
7455: $listing_results[0] ne 'con_lost') {
7456: foreach my $line (@listing_results) {
7457: my ($entry) = split(/&/,$line,2);
7458: $allusers{$entry} = 1;
7459: }
7460: }
1.253 stredwic 7461: }
7462: my $alluserstr='';
1.800 albertel 7463: foreach my $user (sort(keys(%allusers))) {
7464: $alluserstr.=$user.'&user:';
1.253 stredwic 7465: }
7466: $alluserstr=~s/:$//;
7467: return split(/:/,$alluserstr);
7468: } else {
1.800 albertel 7469: return ('missing user name');
1.253 stredwic 7470: }
1.955 raeburn 7471: } elsif(!defined($getpropath)) {
1.841 albertel 7472: my @all_domains = sort(&all_domains());
1.955 raeburn 7473: foreach my $domain (@all_domains) {
7474: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7475: }
7476: return @all_domains;
7477: } else {
1.800 albertel 7478: return ('missing domain');
1.275 stredwic 7479: }
7480: }
7481:
7482: # --------------------------------------------- GetFileTimestamp
7483: # This function utilizes dirlist and returns the date stamp for
7484: # when it was last modified. It will also return an error of -1
7485: # if an error occurs
7486:
7487: sub GetFileTimestamp {
1.955 raeburn 7488: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7489: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7490: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7491: my ($fileStat) =
7492: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7493: undef,$getuserdir);
1.275 stredwic 7494: my @stats = split('&', $fileStat);
7495: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7496: # @stats contains first the filename, then the stat output
7497: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7498: } else {
7499: return -1;
1.253 stredwic 7500: }
1.26 www 7501: }
7502:
1.712 albertel 7503: sub stat_file {
7504: my ($uri) = @_;
1.787 albertel 7505: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7506:
1.955 raeburn 7507: my ($udom,$uname,$file);
1.712 albertel 7508: if ($uri =~ m-^/(uploaded|editupload)/-) {
7509: ($udom,$uname,$file) =
1.811 albertel 7510: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7511: $file = 'userfiles/'.$file;
7512: }
7513: if ($uri =~ m-^/res/-) {
7514: ($udom,$uname) =
1.807 albertel 7515: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7516: $file = $uri;
7517: }
7518:
7519: if (!$udom || !$uname || !$file) {
7520: # unable to handle the uri
7521: return ();
7522: }
1.956 raeburn 7523: my $getpropath;
7524: if ($file =~ /^userfiles\//) {
7525: $getpropath = 1;
7526: }
1.955 raeburn 7527: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7528: my @stats = split('&', $result);
1.721 banghart 7529:
1.712 albertel 7530: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7531: shift(@stats); #filename is first
7532: return @stats;
7533: }
7534: return ();
7535: }
7536:
1.26 www 7537: # -------------------------------------------------------- Value of a Condition
7538:
1.713 albertel 7539: # gets the value of a specific preevaluated condition
7540: # stored in the string $env{user.state.<cid>}
7541: # or looks up a condition reference in the bighash and if if hasn't
7542: # already been evaluated recurses into docondval to get the value of
7543: # the condition, then memoizing it to
7544: # $env{user.state.<cid>.<condition>}
1.40 www 7545: sub directcondval {
7546: my $number=shift;
1.620 albertel 7547: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7548: &Apache::lonuserstate::evalstate();
7549: }
1.713 albertel 7550: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7551: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7552: } elsif ($number =~ /^_/) {
7553: my $sub_condition;
7554: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7555: &GDBM_READER(),0640)) {
7556: $sub_condition=$bighash{'conditions'.$number};
7557: untie(%bighash);
7558: }
7559: my $value = &docondval($sub_condition);
1.949 raeburn 7560: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7561: return $value;
7562: }
1.620 albertel 7563: if ($env{'user.state.'.$env{'request.course.id'}}) {
7564: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7565: } else {
7566: return 2;
7567: }
7568: }
7569:
1.713 albertel 7570: # get the collection of conditions for this resource
1.26 www 7571: sub condval {
7572: my $condidx=shift;
1.54 www 7573: my $allpathcond='';
1.713 albertel 7574: foreach my $cond (split(/\|/,$condidx)) {
7575: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7576: $allpathcond.=
7577: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7578: }
1.191 harris41 7579: }
1.54 www 7580: $allpathcond=~s/\|$//;
1.713 albertel 7581: return &docondval($allpathcond);
7582: }
7583:
7584: #evaluates an expression of conditions
7585: sub docondval {
7586: my ($allpathcond) = @_;
7587: my $result=0;
7588: if ($env{'request.course.id'}
7589: && defined($allpathcond)) {
7590: my $operand='|';
7591: my @stack;
7592: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7593: if ($chunk eq '(') {
7594: push @stack,($operand,$result);
7595: } elsif ($chunk eq ')') {
7596: my $before=pop @stack;
7597: if (pop @stack eq '&') {
7598: $result=$result>$before?$before:$result;
7599: } else {
7600: $result=$result>$before?$result:$before;
7601: }
7602: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7603: $operand=$chunk;
7604: } else {
7605: my $new=directcondval($chunk);
7606: if ($operand eq '&') {
7607: $result=$result>$new?$new:$result;
7608: } else {
7609: $result=$result>$new?$result:$new;
7610: }
7611: }
7612: }
1.26 www 7613: }
7614: return $result;
1.421 albertel 7615: }
7616:
7617: # ---------------------------------------------------- Devalidate courseresdata
7618:
7619: sub devalidatecourseresdata {
7620: my ($coursenum,$coursedomain)=@_;
7621: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7622: &devalidate_cache_new('courseres',$hashid);
1.28 www 7623: }
7624:
1.763 www 7625:
1.200 www 7626: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7627: #
7628: # Parameters:
7629: # $coursenum - Number of the course.
7630: # $coursedomain - Domain at which the course was created.
7631: # Returns:
7632: # A hash of the course parameters along (I think) with timestamps
7633: # and version info.
1.877 foxr 7634:
1.624 albertel 7635: sub get_courseresdata {
7636: my ($coursenum,$coursedomain)=@_;
1.200 www 7637: my $coursehom=&homeserver($coursenum,$coursedomain);
7638: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7639: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7640: my %dumpreply;
1.417 albertel 7641: unless (defined($cached)) {
1.624 albertel 7642: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7643: $result=\%dumpreply;
1.251 albertel 7644: my ($tmp) = keys(%dumpreply);
7645: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7646: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7647: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7648: return $tmp;
1.416 albertel 7649: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7650: $result=undef;
1.599 albertel 7651: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7652: }
7653: }
1.624 albertel 7654: return $result;
7655: }
7656:
1.633 albertel 7657: sub devalidateuserresdata {
7658: my ($uname,$udom)=@_;
7659: my $hashid="$udom:$uname";
7660: &devalidate_cache_new('userres',$hashid);
7661: }
7662:
1.624 albertel 7663: sub get_userresdata {
7664: my ($uname,$udom)=@_;
7665: #most student don\'t have any data set, check if there is some data
7666: if (&EXT_cache_status($udom,$uname)) { return undef; }
7667:
7668: my $hashid="$udom:$uname";
7669: my ($result,$cached)=&is_cached_new('userres',$hashid);
7670: if (!defined($cached)) {
7671: my %resourcedata=&dump('resourcedata',$udom,$uname);
7672: $result=\%resourcedata;
7673: &do_cache_new('userres',$hashid,$result,600);
7674: }
7675: my ($tmp)=keys(%$result);
7676: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7677: return $result;
7678: }
7679: #error 2 occurs when the .db doesn't exist
7680: if ($tmp!~/error: 2 /) {
1.672 albertel 7681: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7682: " Trying to get resource data for ".
7683: $uname." at ".$udom.": ".
7684: $tmp."</font>");
7685: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7686: #&EXT_cache_set($udom,$uname);
7687: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7688: undef($tmp); # not really an error so don't send it back
1.624 albertel 7689: }
7690: return $tmp;
7691: }
1.879 foxr 7692: #----------------------------------------------- resdata - return resource data
7693: # Purpose:
7694: # Return resource data for either users or for a course.
7695: # Parameters:
7696: # $name - Course/user name.
7697: # $domain - Name of the domain the user/course is registered on.
7698: # $type - Type of thing $name is (must be 'course' or 'user'
7699: # @which - Array of names of resources desired.
7700: # Returns:
7701: # The value of the first reasource in @which that is found in the
7702: # resource hash.
7703: # Exceptional Conditions:
7704: # If the $type passed in is not valid (not the string 'course' or
7705: # 'user', an undefined reference is returned.
7706: # If none of the resources are found, an undef is returned
1.624 albertel 7707: sub resdata {
7708: my ($name,$domain,$type,@which)=@_;
7709: my $result;
7710: if ($type eq 'course') {
7711: $result=&get_courseresdata($name,$domain);
7712: } elsif ($type eq 'user') {
7713: $result=&get_userresdata($name,$domain);
7714: }
7715: if (!ref($result)) { return $result; }
1.251 albertel 7716: foreach my $item (@which) {
1.927 albertel 7717: if (defined($result->{$item->[0]})) {
7718: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7719: }
1.250 albertel 7720: }
1.291 albertel 7721: return undef;
1.200 www 7722: }
7723:
1.379 matthew 7724: #
7725: # EXT resource caching routines
7726: #
7727:
7728: sub clear_EXT_cache_status {
1.383 albertel 7729: &delenv('cache.EXT.');
1.379 matthew 7730: }
7731:
7732: sub EXT_cache_status {
7733: my ($target_domain,$target_user) = @_;
1.383 albertel 7734: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7735: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7736: # We know already the user has no data
7737: return 1;
7738: } else {
7739: return 0;
7740: }
7741: }
7742:
7743: sub EXT_cache_set {
7744: my ($target_domain,$target_user) = @_;
1.383 albertel 7745: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7746: #&appenv({$cachename => time});
1.379 matthew 7747: }
7748:
1.28 www 7749: # --------------------------------------------------------- Value of a Variable
1.58 www 7750: sub EXT {
1.715 albertel 7751:
1.395 albertel 7752: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7753: unless ($varname) { return ''; }
1.218 albertel 7754: #get real user name/domain, courseid and symb
7755: my $courseid;
1.359 albertel 7756: my $publicuser;
1.427 www 7757: if ($symbparm) {
7758: $symbparm=&get_symb_from_alias($symbparm);
7759: }
1.218 albertel 7760: if (!($uname && $udom)) {
1.790 albertel 7761: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7762: if (!$symbparm) { $symbparm=$cursymb; }
7763: } else {
1.620 albertel 7764: $courseid=$env{'request.course.id'};
1.218 albertel 7765: }
1.48 www 7766: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7767: my $rest;
1.320 albertel 7768: if (defined($therest[0])) {
1.48 www 7769: $rest=join('.',@therest);
7770: } else {
7771: $rest='';
7772: }
1.320 albertel 7773:
1.57 www 7774: my $qualifierrest=$qualifier;
7775: if ($rest) { $qualifierrest.='.'.$rest; }
7776: my $spacequalifierrest=$space;
7777: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7778: if ($realm eq 'user') {
1.48 www 7779: # --------------------------------------------------------------- user.resource
7780: if ($space eq 'resource') {
1.651 albertel 7781: if ( (defined($Apache::lonhomework::parsing_a_problem)
7782: || defined($Apache::lonhomework::parsing_a_task))
7783: &&
1.744 albertel 7784: ($symbparm eq &symbread()) ) {
7785: # if we are in the middle of processing the resource the
7786: # get the value we are planning on committing
7787: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7788: return $Apache::lonhomework::results{$qualifierrest};
7789: } else {
7790: return $Apache::lonhomework::history{$qualifierrest};
7791: }
1.335 albertel 7792: } else {
1.359 albertel 7793: my %restored;
1.620 albertel 7794: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 7795: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7796: } else {
7797: %restored=&restore($symbparm,$courseid,$udom,$uname);
7798: }
1.335 albertel 7799: return $restored{$qualifierrest};
7800: }
1.48 www 7801: # ----------------------------------------------------------------- user.access
7802: } elsif ($space eq 'access') {
1.218 albertel 7803: # FIXME - not supporting calls for a specific user
1.48 www 7804: return &allowed($qualifier,$rest);
7805: # ------------------------------------------ user.preferences, user.environment
7806: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7807: if (($uname eq $env{'user.name'}) &&
7808: ($udom eq $env{'user.domain'})) {
7809: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7810: } else {
1.359 albertel 7811: my %returnhash;
7812: if (!$publicuser) {
7813: %returnhash=&userenvironment($udom,$uname,
7814: $qualifierrest);
7815: }
1.218 albertel 7816: return $returnhash{$qualifierrest};
7817: }
1.48 www 7818: # ----------------------------------------------------------------- user.course
7819: } elsif ($space eq 'course') {
1.218 albertel 7820: # FIXME - not supporting calls for a specific user
1.620 albertel 7821: return $env{join('.',('request.course',$qualifier))};
1.48 www 7822: # ------------------------------------------------------------------- user.role
7823: } elsif ($space eq 'role') {
1.218 albertel 7824: # FIXME - not supporting calls for a specific user
1.620 albertel 7825: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7826: if ($qualifier eq 'value') {
7827: return $role;
7828: } elsif ($qualifier eq 'extent') {
7829: return $where;
7830: }
7831: # ----------------------------------------------------------------- user.domain
7832: } elsif ($space eq 'domain') {
1.218 albertel 7833: return $udom;
1.48 www 7834: # ------------------------------------------------------------------- user.name
7835: } elsif ($space eq 'name') {
1.218 albertel 7836: return $uname;
1.48 www 7837: # ---------------------------------------------------- Any other user namespace
1.29 www 7838: } else {
1.359 albertel 7839: my %reply;
7840: if (!$publicuser) {
7841: %reply=&get($space,[$qualifierrest],$udom,$uname);
7842: }
7843: return $reply{$qualifierrest};
1.48 www 7844: }
1.236 www 7845: } elsif ($realm eq 'query') {
7846: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7847: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7848: [$spacequalifierrest]);
1.620 albertel 7849: return $env{'form.'.$spacequalifierrest};
1.236 www 7850: } elsif ($realm eq 'request') {
1.48 www 7851: # ------------------------------------------------------------- request.browser
7852: if ($space eq 'browser') {
1.430 www 7853: if ($qualifier eq 'textremote') {
1.676 albertel 7854: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7855: return 1;
7856: } else {
7857: return 0;
7858: }
7859: } else {
1.620 albertel 7860: return $env{'browser.'.$qualifier};
1.430 www 7861: }
1.57 www 7862: # ------------------------------------------------------------ request.filename
7863: } else {
1.620 albertel 7864: return $env{'request.'.$spacequalifierrest};
1.29 www 7865: }
1.28 www 7866: } elsif ($realm eq 'course') {
1.48 www 7867: # ---------------------------------------------------------- course.description
1.620 albertel 7868: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7869: } elsif ($realm eq 'resource') {
1.165 www 7870:
1.620 albertel 7871: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7872: if (!$symbparm) { $symbparm=&symbread(); }
7873: }
1.693 albertel 7874:
7875: if ($space eq 'title') {
7876: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7877: return &gettitle($symbparm);
7878: }
7879:
7880: if ($space eq 'map') {
7881: my ($map) = &decode_symb($symbparm);
7882: return &symbread($map);
7883: }
1.905 albertel 7884: if ($space eq 'filename') {
7885: if ($symbparm) {
7886: return &clutter((&decode_symb($symbparm))[2]);
7887: }
7888: return &hreflocation('',$env{'request.filename'});
7889: }
1.693 albertel 7890:
7891: my ($section, $group, @groups);
1.593 albertel 7892: my ($courselevelm,$courselevel);
1.539 albertel 7893: if ($symbparm && defined($courseid) &&
1.620 albertel 7894: $courseid eq $env{'request.course.id'}) {
1.165 www 7895:
1.218 albertel 7896: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7897:
1.60 www 7898: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7899: my $symbp=$symbparm;
1.735 albertel 7900: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7901:
7902: my $symbparm=$symbp.'.'.$spacequalifierrest;
7903: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7904:
1.620 albertel 7905: if (($env{'user.name'} eq $uname) &&
7906: ($env{'user.domain'} eq $udom)) {
7907: $section=$env{'request.course.sec'};
1.733 raeburn 7908: @groups = split(/:/,$env{'request.course.groups'});
7909: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7910: } else {
1.539 albertel 7911: if (! defined($usection)) {
1.551 albertel 7912: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7913: } else {
7914: $section = $usection;
7915: }
1.733 raeburn 7916: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7917: }
7918:
7919: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7920: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7921: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7922:
1.593 albertel 7923: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7924: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7925: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7926:
1.60 www 7927: # ----------------------------------------------------------- first, check user
1.624 albertel 7928:
7929: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7930: ([$courselevelr,'resource'],
7931: [$courselevelm,'map' ],
7932: [$courselevel, 'course' ]));
1.931 albertel 7933: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7934:
1.594 albertel 7935: # ------------------------------------------------ second, check some of course
1.684 raeburn 7936: my $coursereply;
1.691 raeburn 7937: if (@groups > 0) {
7938: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7939: $mapparm,$spacequalifierrest);
1.927 albertel 7940: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7941: }
1.96 www 7942:
1.684 raeburn 7943: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7944: $env{'course.'.$courseid.'.domain'},
7945: 'course',
7946: ([$seclevelr, 'resource'],
7947: [$seclevelm, 'map' ],
7948: [$seclevel, 'course' ],
7949: [$courselevelr,'resource']));
7950: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7951:
1.60 www 7952: # ------------------------------------------------------ third, check map parms
1.218 albertel 7953: my %parmhash=();
7954: my $thisparm='';
7955: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7956: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7957: &GDBM_READER(),0640)) {
1.218 albertel 7958: $thisparm=$parmhash{$symbparm};
7959: untie(%parmhash);
7960: }
1.927 albertel 7961: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7962: }
1.594 albertel 7963: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7964:
1.218 albertel 7965: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7966: my $filename;
7967: if (!$symbparm) { $symbparm=&symbread(); }
7968: if ($symbparm) {
1.409 www 7969: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7970: } else {
1.620 albertel 7971: $filename=$env{'request.filename'};
1.282 albertel 7972: }
7973: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7974: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7975: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7976: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7977:
1.927 albertel 7978: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7979: if ($symbparm && defined($courseid) &&
1.620 albertel 7980: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7981: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7982: $env{'course.'.$courseid.'.domain'},
7983: 'course',
1.927 albertel 7984: ([$courselevelm,'map' ],
7985: [$courselevel, 'course']));
7986: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7987: }
1.145 www 7988: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7989: unless ($space eq '0') {
1.336 albertel 7990: my @parts=split(/_/,$space);
7991: my $id=pop(@parts);
7992: my $part=join('_',@parts);
7993: if ($part eq '') { $part='0'; }
1.927 albertel 7994: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7995: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7996: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7997: }
1.395 albertel 7998: if ($recurse) { return undef; }
7999: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8000: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8001: # ---------------------------------------------------- Any other user namespace
8002: } elsif ($realm eq 'environment') {
8003: # ----------------------------------------------------------------- environment
1.620 albertel 8004: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8005: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8006: } else {
1.770 albertel 8007: if ($uname eq 'anonymous' && $udom eq '') {
8008: return '';
8009: }
1.219 albertel 8010: my %returnhash=&userenvironment($udom,$uname,
8011: $spacequalifierrest);
8012: return $returnhash{$spacequalifierrest};
8013: }
1.28 www 8014: } elsif ($realm eq 'system') {
1.48 www 8015: # ----------------------------------------------------------------- system.time
8016: if ($space eq 'time') {
8017: return time;
8018: }
1.696 albertel 8019: } elsif ($realm eq 'server') {
8020: # ----------------------------------------------------------------- system.time
8021: if ($space eq 'name') {
8022: return $ENV{'SERVER_NAME'};
8023: }
1.28 www 8024: }
1.48 www 8025: return '';
1.61 www 8026: }
8027:
1.927 albertel 8028: sub get_reply {
8029: my ($reply_value) = @_;
1.940 raeburn 8030: if (ref($reply_value) eq 'ARRAY') {
8031: if (wantarray) {
8032: return @$reply_value;
8033: }
8034: return $reply_value->[0];
8035: } else {
8036: return $reply_value;
1.927 albertel 8037: }
8038: }
8039:
1.691 raeburn 8040: sub check_group_parms {
8041: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8042: my @groupitems = ();
8043: my $resultitem;
1.927 albertel 8044: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8045: foreach my $group (@{$groups}) {
8046: foreach my $level (@levels) {
1.927 albertel 8047: my $item = $courseid.'.['.$group.'].'.$level->[0];
8048: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8049: }
8050: }
8051: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8052: $env{'course.'.$courseid.'.domain'},
8053: 'course',@groupitems);
8054: return $coursereply;
8055: }
8056:
8057: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8058: my ($courseid,@groups) = @_;
8059: @groups = sort(@groups);
1.691 raeburn 8060: return @groups;
8061: }
8062:
1.395 albertel 8063: sub packages_tab_default {
8064: my ($uri,$varname)=@_;
8065: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8066:
8067: my (@extension,@specifics,$do_default);
8068: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8069: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8070: if ($pack_type eq 'default') {
8071: $do_default=1;
8072: } elsif ($pack_type eq 'extension') {
8073: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8074: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8075: # only look at packages defaults for packages that this id is
1.738 albertel 8076: push(@specifics,[$package,$pack_type,$pack_part]);
8077: }
8078: }
8079: # first look for a package that matches the requested part id
8080: foreach my $package (@specifics) {
8081: my (undef,$pack_type,$pack_part)=@{$package};
8082: next if ($pack_part ne $part);
8083: if (defined($packagetab{"$pack_type&$name&default"})) {
8084: return $packagetab{"$pack_type&$name&default"};
8085: }
8086: }
8087: # look for any possible matching non extension_ package
8088: foreach my $package (@specifics) {
8089: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8090: if (defined($packagetab{"$pack_type&$name&default"})) {
8091: return $packagetab{"$pack_type&$name&default"};
8092: }
1.585 albertel 8093: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8094: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8095: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8096: }
8097: }
1.738 albertel 8098: # look for any posible extension_ match
8099: foreach my $package (@extension) {
8100: my ($package,$pack_type)=@{$package};
8101: if (defined($packagetab{"$pack_type&$name&default"})) {
8102: return $packagetab{"$pack_type&$name&default"};
8103: }
8104: if (defined($packagetab{$package."&$name&default"})) {
8105: return $packagetab{$package."&$name&default"};
8106: }
8107: }
8108: # look for a global default setting
8109: if ($do_default && defined($packagetab{"default&$name&default"})) {
8110: return $packagetab{"default&$name&default"};
8111: }
1.395 albertel 8112: return undef;
8113: }
8114:
1.334 albertel 8115: sub add_prefix_and_part {
8116: my ($prefix,$part)=@_;
8117: my $keyroot;
8118: if (defined($prefix) && $prefix !~ /^__/) {
8119: # prefix that has a part already
8120: $keyroot=$prefix;
8121: } elsif (defined($prefix)) {
8122: # prefix that is missing a part
8123: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8124: } else {
8125: # no prefix at all
8126: if (defined($part)) { $keyroot='_'.$part; }
8127: }
8128: return $keyroot;
8129: }
8130:
1.71 www 8131: # ---------------------------------------------------------------- Get metadata
8132:
1.599 albertel 8133: my %metaentry;
1.71 www 8134: sub metadata {
1.176 www 8135: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8136: $uri=&declutter($uri);
1.288 albertel 8137: # if it is a non metadata possible uri return quickly
1.529 albertel 8138: if (($uri eq '') ||
8139: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8140: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8141: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8142: return undef;
8143: }
8144: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8145: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8146: return undef;
1.288 albertel 8147: }
1.73 www 8148: my $filename=$uri;
8149: $uri=~s/\.meta$//;
1.172 www 8150: #
8151: # Is the metadata already cached?
1.177 www 8152: # Look at timestamp of caching
1.172 www 8153: # Everything is cached by the main uri, libraries are never directly cached
8154: #
1.428 albertel 8155: if (!defined($liburi)) {
1.599 albertel 8156: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8157: if (defined($cached)) { return $result->{':'.$what}; }
8158: }
8159: {
1.172 www 8160: #
8161: # Is this a recursive call for a library?
8162: #
1.599 albertel 8163: # if (! exists($metacache{$uri})) {
8164: # $metacache{$uri}={};
8165: # }
1.924 albertel 8166: my $cachetime = 60*60;
1.171 www 8167: if ($liburi) {
8168: $liburi=&declutter($liburi);
8169: $filename=$liburi;
1.401 bowersj2 8170: } else {
1.599 albertel 8171: &devalidate_cache_new('meta',$uri);
8172: undef(%metaentry);
1.401 bowersj2 8173: }
1.140 www 8174: my %metathesekeys=();
1.73 www 8175: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8176: my $metastring;
1.924 albertel 8177: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8178: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8179: $metastring =
1.929 albertel 8180: &Apache::lonnet::ssi_body($which,
1.924 albertel 8181: ('grade_target' => 'meta'));
8182: $cachetime = 1; # only want this cached in the child not long term
8183: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8184: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8185: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8186: $metastring=&getfile($file);
1.489 albertel 8187: }
1.208 albertel 8188: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8189: my $token;
1.140 www 8190: undef %metathesekeys;
1.71 www 8191: while ($token=$parser->get_token) {
1.339 albertel 8192: if ($token->[0] eq 'S') {
8193: if (defined($token->[2]->{'package'})) {
1.172 www 8194: #
8195: # This is a package - get package info
8196: #
1.339 albertel 8197: my $package=$token->[2]->{'package'};
8198: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8199: if (defined($token->[2]->{'id'})) {
8200: $keyroot.='_'.$token->[2]->{'id'};
8201: }
1.599 albertel 8202: if ($metaentry{':packages'}) {
8203: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8204: } else {
1.599 albertel 8205: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8206: }
1.736 albertel 8207: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8208: my $part=$keyroot;
8209: $part=~s/^\_//;
1.736 albertel 8210: if ($pack_entry=~/^\Q$package\E\&/ ||
8211: $pack_entry=~/^\Q$package\E_0\&/) {
8212: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8213: # ignore package.tab specified default values
8214: # here &package_tab_default() will fetch those
8215: if ($subp eq 'default') { next; }
1.736 albertel 8216: my $value=$packagetab{$pack_entry};
1.432 albertel 8217: my $unikey;
8218: if ($pack =~ /_0$/) {
8219: $unikey='parameter_0_'.$name;
8220: $part=0;
8221: } else {
8222: $unikey='parameter'.$keyroot.'_'.$name;
8223: }
1.339 albertel 8224: if ($subp eq 'display') {
8225: $value.=' [Part: '.$part.']';
8226: }
1.599 albertel 8227: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8228: $metathesekeys{$unikey}=1;
1.599 albertel 8229: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8230: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8231: }
1.599 albertel 8232: if (defined($metaentry{':'.$unikey.'.default'})) {
8233: $metaentry{':'.$unikey}=
8234: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8235: }
1.339 albertel 8236: }
8237: }
8238: } else {
1.172 www 8239: #
8240: # This is not a package - some other kind of start tag
1.339 albertel 8241: #
8242: my $entry=$token->[1];
1.1068 ! www 8243: my $unikey='';
1.175 www 8244:
1.339 albertel 8245: if ($entry eq 'import') {
1.175 www 8246: #
8247: # Importing a library here
1.339 albertel 8248: #
1.1067 www 8249: my $location=$parser->get_text('/import');
8250: my $dir=$filename;
8251: $dir=~s|[^/]*$||;
8252: $location=&filelocation($dir,$location);
8253:
1.1068 ! www 8254: my $importmode=$token->[2]->{'importmode'};
! 8255: if ($importmode eq 'problem') {
! 8256: # Import as problem
! 8257: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
! 8258: } elsif ($importmode eq 'part') {
! 8259: # Import as part(s)
! 8260: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
! 8261: } else {
! 8262: # Normal import
! 8263: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
! 8264: if (defined($token->[2]->{'id'})) {
! 8265: $unikey.='_'.$token->[2]->{'id'};
! 8266: }
1.1067 www 8267: }
8268:
1.1068 ! www 8269: #&logthis("About to use unikey $unikey");
! 8270:
1.339 albertel 8271: if ($depthcount<20) {
1.736 albertel 8272: my $metadata =
8273: &metadata($uri,'keys', $location,$unikey,
8274: $depthcount+1);
8275: foreach my $meta (split(',',$metadata)) {
8276: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8277: $metathesekeys{$meta}=1;
1.339 albertel 8278: }
1.1068 ! www 8279:
! 8280: #&logthis("Metadata $metadata");
! 8281: }
1.1067 www 8282: } else {
8283: #
8284: # Not importing, some other kind of non-package, non-library start tag
8285: #
8286: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8287: if (defined($token->[2]->{'id'})) {
8288: $unikey.='_'.$token->[2]->{'id'};
8289: }
1.339 albertel 8290: if (defined($token->[2]->{'name'})) {
8291: $unikey.='_'.$token->[2]->{'name'};
8292: }
8293: $metathesekeys{$unikey}=1;
1.736 albertel 8294: foreach my $param (@{$token->[3]}) {
8295: $metaentry{':'.$unikey.'.'.$param} =
8296: $token->[2]->{$param};
1.339 albertel 8297: }
8298: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8299: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8300: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8301: # only ws inside the tag, and not in default, so use default
8302: # as value
1.599 albertel 8303: $metaentry{':'.$unikey}=$default;
1.908 albertel 8304: } elsif ( $internaltext =~ /\S/ ) {
8305: # something interesting inside the tag
8306: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8307: } else {
1.908 albertel 8308: # no interesting values, don't set a default
1.339 albertel 8309: }
1.172 www 8310: # end of not-a-package not-a-library import
1.339 albertel 8311: }
1.172 www 8312: # end of not-a-package start tag
1.339 albertel 8313: }
1.172 www 8314: # the next is the end of "start tag"
1.339 albertel 8315: }
8316: }
1.483 albertel 8317: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8318: $extension = lc($extension);
8319: if ($extension eq 'htm') { $extension='html'; }
8320:
1.737 albertel 8321: foreach my $key (keys(%packagetab)) {
1.483 albertel 8322: #no specific packages #how's our extension
8323: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8324: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8325: \%metathesekeys);
8326: }
1.883 albertel 8327:
8328: if (!exists($metaentry{':packages'})
8329: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8330: foreach my $key (keys(%packagetab)) {
1.483 albertel 8331: #no specific packages well let's get default then
8332: if ($key!~/^default&/) { next; }
1.488 albertel 8333: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8334: \%metathesekeys);
8335: }
8336: }
1.338 www 8337: # are there custom rights to evaluate
1.599 albertel 8338: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8339:
1.338 www 8340: #
8341: # Importing a rights file here
1.339 albertel 8342: #
8343: unless ($depthcount) {
1.599 albertel 8344: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8345: my $dir=$filename;
8346: $dir=~s|[^/]*$||;
8347: $location=&filelocation($dir,$location);
1.736 albertel 8348: my $rights_metadata =
8349: &metadata($uri,'keys',$location,'_rights',
8350: $depthcount+1);
8351: foreach my $rights (split(',',$rights_metadata)) {
8352: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8353: $metathesekeys{$rights}=1;
1.339 albertel 8354: }
8355: }
8356: }
1.737 albertel 8357: # uniqifiy package listing
8358: my %seen;
8359: my @uniq_packages =
8360: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8361: $metaentry{':packages'} = join(',',@uniq_packages);
8362:
8363: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8364: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8365: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8366: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8367: # this is the end of "was not already recently cached
1.71 www 8368: }
1.599 albertel 8369: return $metaentry{':'.$what};
1.261 albertel 8370: }
8371:
1.488 albertel 8372: sub metadata_create_package_def {
1.483 albertel 8373: my ($uri,$key,$package,$metathesekeys)=@_;
8374: my ($pack,$name,$subp)=split(/\&/,$key);
8375: if ($subp eq 'default') { next; }
8376:
1.599 albertel 8377: if (defined($metaentry{':packages'})) {
8378: $metaentry{':packages'}.=','.$package;
1.483 albertel 8379: } else {
1.599 albertel 8380: $metaentry{':packages'}=$package;
1.483 albertel 8381: }
8382: my $value=$packagetab{$key};
8383: my $unikey;
8384: $unikey='parameter_0_'.$name;
1.599 albertel 8385: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8386: $$metathesekeys{$unikey}=1;
1.599 albertel 8387: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8388: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8389: }
1.599 albertel 8390: if (defined($metaentry{':'.$unikey.'.default'})) {
8391: $metaentry{':'.$unikey}=
8392: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8393: }
8394: }
8395:
1.261 albertel 8396: sub metadata_generate_part0 {
8397: my ($metadata,$metacache,$uri) = @_;
8398: my %allnames;
1.737 albertel 8399: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8400: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8401: my $part=$$metacache{':'.$metakey.'.part'};
8402: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8403: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8404: $allnames{$name}=$part;
8405: }
8406: }
8407: }
8408: foreach my $name (keys(%allnames)) {
8409: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8410: my $key=":parameter_0_$name";
1.261 albertel 8411: $$metacache{"$key.part"}='0';
8412: $$metacache{"$key.name"}=$name;
1.428 albertel 8413: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8414: $allnames{$name}.'_'.$name.
8415: '.type'};
1.428 albertel 8416: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8417: '.display'};
1.644 www 8418: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8419: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8420: $$metacache{"$key.display"}=$olddis;
8421: }
1.71 www 8422: }
8423:
1.764 albertel 8424: # ------------------------------------------------------ Devalidate title cache
8425:
8426: sub devalidate_title_cache {
8427: my ($url)=@_;
8428: if (!$env{'request.course.id'}) { return; }
8429: my $symb=&symbread($url);
8430: if (!$symb) { return; }
8431: my $key=$env{'request.course.id'}."\0".$symb;
8432: &devalidate_cache_new('title',$key);
8433: }
8434:
1.1014 droeschl 8435: # ------------------------------------------------- Get the title of a course
8436:
8437: sub current_course_title {
8438: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8439: }
1.301 www 8440: # ------------------------------------------------- Get the title of a resource
8441:
8442: sub gettitle {
8443: my $urlsymb=shift;
8444: my $symb=&symbread($urlsymb);
1.534 albertel 8445: if ($symb) {
1.620 albertel 8446: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8447: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8448: if (defined($cached)) {
8449: return $result;
8450: }
1.534 albertel 8451: my ($map,$resid,$url)=&decode_symb($symb);
8452: my $title='';
1.907 albertel 8453: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8454: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8455: } else {
8456: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8457: &GDBM_READER(),0640)) {
8458: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8459: $title=$bighash{'title_'.$mapid.'.'.$resid};
8460: untie(%bighash);
8461: }
1.534 albertel 8462: }
8463: $title=~s/\&colon\;/\:/gs;
8464: if ($title) {
1.599 albertel 8465: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8466: }
8467: $urlsymb=$url;
8468: }
8469: my $title=&metadata($urlsymb,'title');
8470: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8471: return $title;
1.301 www 8472: }
1.613 albertel 8473:
1.614 albertel 8474: sub get_slot {
8475: my ($which,$cnum,$cdom)=@_;
8476: if (!$cnum || !$cdom) {
1.790 albertel 8477: (undef,my $courseid)=&whichuser();
1.620 albertel 8478: $cdom=$env{'course.'.$courseid.'.domain'};
8479: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8480: }
1.703 albertel 8481: my $key=join("\0",'slots',$cdom,$cnum,$which);
8482: my %slotinfo;
8483: if (exists($remembered{$key})) {
8484: $slotinfo{$which} = $remembered{$key};
8485: } else {
8486: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8487: &Apache::lonhomework::showhash(%slotinfo);
8488: my ($tmp)=keys(%slotinfo);
8489: if ($tmp=~/^error:/) { return (); }
8490: $remembered{$key} = $slotinfo{$which};
8491: }
1.616 albertel 8492: if (ref($slotinfo{$which}) eq 'HASH') {
8493: return %{$slotinfo{$which}};
8494: }
8495: return $slotinfo{$which};
1.614 albertel 8496: }
1.31 www 8497: # ------------------------------------------------- Update symbolic store links
8498:
8499: sub symblist {
8500: my ($mapname,%newhash)=@_;
1.438 www 8501: $mapname=&deversion(&declutter($mapname));
1.31 www 8502: my %hash;
1.620 albertel 8503: if (($env{'request.course.fn'}) && (%newhash)) {
8504: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8505: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8506: foreach my $url (keys(%newhash)) {
1.711 albertel 8507: next if ($url eq 'last_known'
8508: && $env{'form.no_update_last_known'});
8509: $hash{declutter($url)}=&encode_symb($mapname,
8510: $newhash{$url}->[1],
8511: $newhash{$url}->[0]);
1.191 harris41 8512: }
1.31 www 8513: if (untie(%hash)) {
8514: return 'ok';
8515: }
8516: }
8517: }
8518: return 'error';
1.212 www 8519: }
8520:
8521: # --------------------------------------------------------------- Verify a symb
8522:
8523: sub symbverify {
1.510 www 8524: my ($symb,$thisurl)=@_;
8525: my $thisfn=$thisurl;
1.439 www 8526: $thisfn=&declutter($thisfn);
1.215 www 8527: # direct jump to resource in page or to a sequence - will construct own symbs
8528: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8529: # check URL part
1.409 www 8530: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8531:
1.431 www 8532: unless ($url eq $thisfn) { return 0; }
1.213 www 8533:
1.216 www 8534: $symb=&symbclean($symb);
1.510 www 8535: $thisurl=&deversion($thisurl);
1.439 www 8536: $thisfn=&deversion($thisfn);
1.213 www 8537:
8538: my %bighash;
8539: my $okay=0;
1.431 www 8540:
1.620 albertel 8541: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8542: &GDBM_READER(),0640)) {
1.1032 raeburn 8543: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8544: $thisurl =~ s/\?.+$//;
8545: }
1.510 www 8546: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8547: unless ($ids) {
1.510 www 8548: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8549: }
8550: if ($ids) {
8551: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8552: foreach my $id (split(/\,/,$ids)) {
8553: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8554: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8555: $symb =~ s/\?.+$//;
8556: }
1.216 www 8557: if (
8558: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8559: eq $symb) {
1.620 albertel 8560: if (($env{'request.role.adv'}) ||
1.800 albertel 8561: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8562: $okay=1;
8563: }
8564: }
1.216 www 8565: }
8566: }
1.213 www 8567: untie(%bighash);
8568: }
8569: return $okay;
1.31 www 8570: }
8571:
1.210 www 8572: # --------------------------------------------------------------- Clean-up symb
8573:
8574: sub symbclean {
8575: my $symb=shift;
1.568 albertel 8576: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8577: # remove version from map
8578: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8579:
1.210 www 8580: # remove version from URL
8581: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8582:
1.507 www 8583: # remove wrapper
8584:
1.510 www 8585: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8586: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8587: return $symb;
1.409 www 8588: }
8589:
8590: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8591:
8592: sub encode_symb {
8593: my ($map,$resid,$url)=@_;
8594: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8595: }
1.409 www 8596:
8597: sub decode_symb {
1.568 albertel 8598: my $symb=shift;
8599: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8600: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8601: return (&fixversion($map),$resid,&fixversion($url));
8602: }
8603:
8604: sub fixversion {
8605: my $fn=shift;
1.609 banghart 8606: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8607: my %bighash;
8608: my $uri=&clutter($fn);
1.620 albertel 8609: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8610: # is this cached?
1.599 albertel 8611: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8612: if (defined($cached)) { return $result; }
8613: # unfortunately not cached, or expired
1.620 albertel 8614: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8615: &GDBM_READER(),0640)) {
8616: if ($bighash{'version_'.$uri}) {
8617: my $version=$bighash{'version_'.$uri};
1.444 www 8618: unless (($version eq 'mostrecent') ||
8619: ($version==&getversion($uri))) {
1.440 www 8620: $uri=~s/\.(\w+)$/\.$version\.$1/;
8621: }
8622: }
8623: untie %bighash;
1.413 www 8624: }
1.599 albertel 8625: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8626: }
8627:
8628: sub deversion {
8629: my $url=shift;
8630: $url=~s/\.\d+\.(\w+)$/\.$1/;
8631: return $url;
1.210 www 8632: }
8633:
1.31 www 8634: # ------------------------------------------------------ Return symb list entry
8635:
8636: sub symbread {
1.249 www 8637: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8638: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8639: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8640: # no filename provided? try from environment
1.44 www 8641: unless ($thisfn) {
1.620 albertel 8642: if ($env{'request.symb'}) {
8643: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8644: }
1.620 albertel 8645: $thisfn=$env{'request.filename'};
1.44 www 8646: }
1.569 albertel 8647: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8648: # is that filename actually a symb? Verify, clean, and return
8649: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8650: if (&symbverify($thisfn,$1)) {
1.620 albertel 8651: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8652: }
1.242 www 8653: }
1.44 www 8654: $thisfn=declutter($thisfn);
1.31 www 8655: my %hash;
1.37 www 8656: my %bighash;
8657: my $syval='';
1.620 albertel 8658: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8659: my $targetfn = $thisfn;
1.609 banghart 8660: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8661: $targetfn = 'adm/wrapper/'.$thisfn;
8662: }
1.687 albertel 8663: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8664: $targetfn=$1;
8665: }
1.620 albertel 8666: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8667: &GDBM_READER(),0640)) {
1.481 raeburn 8668: $syval=$hash{$targetfn};
1.37 www 8669: untie(%hash);
8670: }
8671: # ---------------------------------------------------------- There was an entry
8672: if ($syval) {
1.601 albertel 8673: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8674: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8675: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8676: #return $env{$cache_str}='';
1.601 albertel 8677: #}
8678: #$syval.=$1;
8679: #}
1.37 www 8680: } else {
8681: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8682: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8683: &GDBM_READER(),0640)) {
1.37 www 8684: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8685: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8686: unless ($ids) {
8687: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8688: }
8689: unless ($ids) {
8690: # alias?
8691: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8692: }
1.37 www 8693: if ($ids) {
8694: # ------------------------------------------------------------------- Has ID(s)
8695: my @possibilities=split(/\,/,$ids);
1.39 www 8696: if ($#possibilities==0) {
8697: # ----------------------------------------------- There is only one possibility
1.37 www 8698: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8699: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8700: $resid,$thisfn);
1.249 www 8701: } elsif (!$donotrecurse) {
1.39 www 8702: # ------------------------------------------ There is more than one possibility
8703: my $realpossible=0;
1.800 albertel 8704: foreach my $id (@possibilities) {
8705: my $file=$bighash{'src_'.$id};
1.39 www 8706: if (&allowed('bre',$file)) {
1.800 albertel 8707: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8708: if ($bighash{'map_type_'.$mapid} ne 'page') {
8709: $realpossible++;
1.626 albertel 8710: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8711: $resid,$thisfn);
1.39 www 8712: }
8713: }
1.191 harris41 8714: }
1.39 www 8715: if ($realpossible!=1) { $syval=''; }
1.249 www 8716: } else {
8717: $syval='';
1.37 www 8718: }
8719: }
8720: untie(%bighash)
1.481 raeburn 8721: }
1.31 www 8722: }
1.62 www 8723: if ($syval) {
1.620 albertel 8724: return $env{$cache_str}=$syval;
1.62 www 8725: }
1.31 www 8726: }
1.949 raeburn 8727: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8728: return $env{$cache_str}='';
1.31 www 8729: }
8730:
8731: # ---------------------------------------------------------- Return random seed
8732:
1.32 www 8733: sub numval {
8734: my $txt=shift;
8735: $txt=~tr/A-J/0-9/;
8736: $txt=~tr/a-j/0-9/;
8737: $txt=~tr/K-T/0-9/;
8738: $txt=~tr/k-t/0-9/;
8739: $txt=~tr/U-Z/0-5/;
8740: $txt=~tr/u-z/0-5/;
8741: $txt=~s/\D//g;
1.564 albertel 8742: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8743: return int($txt);
1.368 albertel 8744: }
8745:
1.484 albertel 8746: sub numval2 {
8747: my $txt=shift;
8748: $txt=~tr/A-J/0-9/;
8749: $txt=~tr/a-j/0-9/;
8750: $txt=~tr/K-T/0-9/;
8751: $txt=~tr/k-t/0-9/;
8752: $txt=~tr/U-Z/0-5/;
8753: $txt=~tr/u-z/0-5/;
8754: $txt=~s/\D//g;
8755: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8756: my $total;
8757: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8758: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 8759: return int($total);
8760: }
8761:
1.575 albertel 8762: sub numval3 {
8763: use integer;
8764: my $txt=shift;
8765: $txt=~tr/A-J/0-9/;
8766: $txt=~tr/a-j/0-9/;
8767: $txt=~tr/K-T/0-9/;
8768: $txt=~tr/k-t/0-9/;
8769: $txt=~tr/U-Z/0-5/;
8770: $txt=~tr/u-z/0-5/;
8771: $txt=~s/\D//g;
8772: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8773: my $total;
8774: foreach my $val (@txts) { $total+=$val; }
8775: if ($_64bit) { $total=(($total<<32)>>32); }
8776: return $total;
8777: }
8778:
1.675 albertel 8779: sub digest {
8780: my ($data)=@_;
8781: my $digest=&Digest::MD5::md5($data);
8782: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8783: my ($e,$f);
8784: {
8785: use integer;
8786: $e=($a+$b);
8787: $f=($c+$d);
8788: if ($_64bit) {
8789: $e=(($e<<32)>>32);
8790: $f=(($f<<32)>>32);
8791: }
8792: }
8793: if (wantarray) {
8794: return ($e,$f);
8795: } else {
8796: my $g;
8797: {
8798: use integer;
8799: $g=($e+$f);
8800: if ($_64bit) {
8801: $g=(($g<<32)>>32);
8802: }
8803: }
8804: return $g;
8805: }
8806: }
8807:
1.368 albertel 8808: sub latest_rnd_algorithm_id {
1.675 albertel 8809: return '64bit5';
1.366 albertel 8810: }
1.32 www 8811:
1.503 albertel 8812: sub get_rand_alg {
8813: my ($courseid)=@_;
1.790 albertel 8814: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 8815: if ($courseid) {
1.620 albertel 8816: return $env{"course.$courseid.rndseed"};
1.503 albertel 8817: }
8818: return &latest_rnd_algorithm_id();
8819: }
8820:
1.562 albertel 8821: sub validCODE {
8822: my ($CODE)=@_;
8823: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8824: return 0;
8825: }
8826:
1.491 albertel 8827: sub getCODE {
1.620 albertel 8828: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 8829: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8830: defined($Apache::lonhomework::parsing_a_task) ) &&
8831: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 8832: return $Apache::lonhomework::history{'resource.CODE'};
8833: }
8834: return undef;
8835: }
8836:
1.31 www 8837: sub rndseed {
1.155 albertel 8838: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8839: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8840: if (!defined($symb)) {
1.366 albertel 8841: unless ($symb=$wsymb) { return time; }
8842: }
8843: if (!$courseid) { $courseid=$wcourseid; }
8844: if (!$domain) { $domain=$wdomain; }
8845: if (!$username) { $username=$wusername }
1.503 albertel 8846: my $which=&get_rand_alg();
1.803 albertel 8847:
1.491 albertel 8848: if (defined(&getCODE())) {
1.675 albertel 8849: if ($which eq '64bit5') {
8850: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8851: } elsif ($which eq '64bit4') {
1.575 albertel 8852: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8853: } else {
8854: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8855: }
1.675 albertel 8856: } elsif ($which eq '64bit5') {
8857: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8858: } elsif ($which eq '64bit4') {
8859: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8860: } elsif ($which eq '64bit3') {
8861: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8862: } elsif ($which eq '64bit2') {
8863: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8864: } elsif ($which eq '64bit') {
8865: return &rndseed_64bit($symb,$courseid,$domain,$username);
8866: }
8867: return &rndseed_32bit($symb,$courseid,$domain,$username);
8868: }
8869:
8870: sub rndseed_32bit {
8871: my ($symb,$courseid,$domain,$username)=@_;
8872: {
8873: use integer;
8874: my $symbchck=unpack("%32C*",$symb) << 27;
8875: my $symbseed=numval($symb) << 22;
8876: my $namechck=unpack("%32C*",$username) << 17;
8877: my $nameseed=numval($username) << 12;
8878: my $domainseed=unpack("%32C*",$domain) << 7;
8879: my $courseseed=unpack("%32C*",$courseid);
8880: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8881: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8882: #&logthis("rndseed :$num:$symb");
1.564 albertel 8883: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8884: return $num;
8885: }
8886: }
8887:
8888: sub rndseed_64bit {
8889: my ($symb,$courseid,$domain,$username)=@_;
8890: {
8891: use integer;
8892: my $symbchck=unpack("%32S*",$symb) << 21;
8893: my $symbseed=numval($symb) << 10;
8894: my $namechck=unpack("%32S*",$username);
8895:
8896: my $nameseed=numval($username) << 21;
8897: my $domainseed=unpack("%32S*",$domain) << 10;
8898: my $courseseed=unpack("%32S*",$courseid);
8899:
8900: my $num1=$symbchck+$symbseed+$namechck;
8901: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8902: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8903: #&logthis("rndseed :$num:$symb");
1.564 albertel 8904: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8905: return "$num1,$num2";
1.155 albertel 8906: }
1.366 albertel 8907: }
8908:
1.443 albertel 8909: sub rndseed_64bit2 {
8910: my ($symb,$courseid,$domain,$username)=@_;
8911: {
8912: use integer;
8913: # strings need to be an even # of cahracters long, it it is odd the
8914: # last characters gets thrown away
8915: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8916: my $symbseed=numval($symb) << 10;
8917: my $namechck=unpack("%32S*",$username.' ');
8918:
8919: my $nameseed=numval($username) << 21;
1.501 albertel 8920: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8921: my $courseseed=unpack("%32S*",$courseid.' ');
8922:
8923: my $num1=$symbchck+$symbseed+$namechck;
8924: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8925: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8926: #&logthis("rndseed :$num:$symb");
1.803 albertel 8927: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8928: return "$num1,$num2";
8929: }
8930: }
8931:
8932: sub rndseed_64bit3 {
8933: my ($symb,$courseid,$domain,$username)=@_;
8934: {
8935: use integer;
8936: # strings need to be an even # of cahracters long, it it is odd the
8937: # last characters gets thrown away
8938: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8939: my $symbseed=numval2($symb) << 10;
8940: my $namechck=unpack("%32S*",$username.' ');
8941:
8942: my $nameseed=numval2($username) << 21;
1.443 albertel 8943: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8944: my $courseseed=unpack("%32S*",$courseid.' ');
8945:
8946: my $num1=$symbchck+$symbseed+$namechck;
8947: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8948: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8949: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8950: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8951:
1.503 albertel 8952: return "$num1:$num2";
1.443 albertel 8953: }
8954: }
8955:
1.575 albertel 8956: sub rndseed_64bit4 {
8957: my ($symb,$courseid,$domain,$username)=@_;
8958: {
8959: use integer;
8960: # strings need to be an even # of cahracters long, it it is odd the
8961: # last characters gets thrown away
8962: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8963: my $symbseed=numval3($symb) << 10;
8964: my $namechck=unpack("%32S*",$username.' ');
8965:
8966: my $nameseed=numval3($username) << 21;
8967: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8968: my $courseseed=unpack("%32S*",$courseid.' ');
8969:
8970: my $num1=$symbchck+$symbseed+$namechck;
8971: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8972: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8973: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 8974: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8975:
8976: return "$num1:$num2";
8977: }
8978: }
8979:
1.675 albertel 8980: sub rndseed_64bit5 {
8981: my ($symb,$courseid,$domain,$username)=@_;
8982: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8983: return "$num1:$num2";
8984: }
8985:
1.366 albertel 8986: sub rndseed_CODE_64bit {
8987: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 8988: {
1.366 albertel 8989: use integer;
1.443 albertel 8990: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 8991: my $symbseed=numval2($symb);
1.491 albertel 8992: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8993: my $CODEseed=numval(&getCODE());
1.443 albertel 8994: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 8995: my $num1=$symbseed+$CODEchck;
8996: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8997: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8998: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 8999: if ($_64bit) { $num1=(($num1<<32)>>32); }
9000: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9001: return "$num1:$num2";
1.366 albertel 9002: }
9003: }
9004:
1.575 albertel 9005: sub rndseed_CODE_64bit4 {
9006: my ($symb,$courseid,$domain,$username)=@_;
9007: {
9008: use integer;
9009: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9010: my $symbseed=numval3($symb);
9011: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9012: my $CODEseed=numval3(&getCODE());
9013: my $courseseed=unpack("%32S*",$courseid.' ');
9014: my $num1=$symbseed+$CODEchck;
9015: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9016: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9017: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9018: if ($_64bit) { $num1=(($num1<<32)>>32); }
9019: if ($_64bit) { $num2=(($num2<<32)>>32); }
9020: return "$num1:$num2";
9021: }
9022: }
9023:
1.675 albertel 9024: sub rndseed_CODE_64bit5 {
9025: my ($symb,$courseid,$domain,$username)=@_;
9026: my $code = &getCODE();
9027: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9028: return "$num1:$num2";
9029: }
9030:
1.366 albertel 9031: sub setup_random_from_rndseed {
9032: my ($rndseed)=@_;
1.503 albertel 9033: if ($rndseed =~/([,:])/) {
9034: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9035: &Math::Random::random_set_seed(abs($num1),abs($num2));
9036: } else {
9037: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9038: }
1.36 albertel 9039: }
9040:
1.474 albertel 9041: sub latest_receipt_algorithm_id {
1.835 albertel 9042: return 'receipt3';
1.474 albertel 9043: }
9044:
1.480 www 9045: sub recunique {
9046: my $fucourseid=shift;
9047: my $unique;
1.835 albertel 9048: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9049: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9050: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9051: } else {
9052: $unique=$perlvar{'lonReceipt'};
9053: }
9054: return unpack("%32C*",$unique);
9055: }
9056:
9057: sub recprefix {
9058: my $fucourseid=shift;
9059: my $prefix;
1.835 albertel 9060: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9061: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9062: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9063: } else {
9064: $prefix=$perlvar{'lonHostID'};
9065: }
9066: return unpack("%32C*",$prefix);
9067: }
9068:
1.76 www 9069: sub ireceipt {
1.474 albertel 9070: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9071:
9072: my $return =&recprefix($fucourseid).'-';
9073:
9074: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9075: $env{'request.state'} eq 'construct') {
9076: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9077: return $return;
9078: }
9079:
1.76 www 9080: my $cuname=unpack("%32C*",$funame);
9081: my $cudom=unpack("%32C*",$fudom);
9082: my $cucourseid=unpack("%32C*",$fucourseid);
9083: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9084: my $cunique=&recunique($fucourseid);
1.474 albertel 9085: my $cpart=unpack("%32S*",$part);
1.835 albertel 9086: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9087:
1.790 albertel 9088: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9089:
9090: $return.= ($cunique%$cuname+
9091: $cunique%$cudom+
9092: $cusymb%$cuname+
9093: $cusymb%$cudom+
9094: $cucourseid%$cuname+
9095: $cucourseid%$cudom+
9096: $cpart%$cuname+
9097: $cpart%$cudom);
9098: } else {
9099: $return.= ($cunique%$cuname+
9100: $cunique%$cudom+
9101: $cusymb%$cuname+
9102: $cusymb%$cudom+
9103: $cucourseid%$cuname+
9104: $cucourseid%$cudom);
9105: }
9106: return $return;
1.76 www 9107: }
9108:
9109: sub receipt {
1.474 albertel 9110: my ($part)=@_;
1.790 albertel 9111: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9112: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9113: }
1.260 ng 9114:
1.790 albertel 9115: sub whichuser {
9116: my ($passedsymb)=@_;
9117: my ($symb,$courseid,$domain,$name,$publicuser);
9118: if (defined($env{'form.grade_symb'})) {
9119: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9120: my $allowed=&allowed('vgr',$tmp_courseid);
9121: if (!$allowed &&
9122: exists($env{'request.course.sec'}) &&
9123: $env{'request.course.sec'} !~ /^\s*$/) {
9124: $allowed=&allowed('vgr',$tmp_courseid.
9125: '/'.$env{'request.course.sec'});
9126: }
9127: if ($allowed) {
9128: ($symb)=&get_env_multiple('form.grade_symb');
9129: $courseid=$tmp_courseid;
9130: ($domain)=&get_env_multiple('form.grade_domain');
9131: ($name)=&get_env_multiple('form.grade_username');
9132: return ($symb,$courseid,$domain,$name,$publicuser);
9133: }
9134: }
9135: if (!$passedsymb) {
9136: $symb=&symbread();
9137: } else {
9138: $symb=$passedsymb;
9139: }
9140: $courseid=$env{'request.course.id'};
9141: $domain=$env{'user.domain'};
9142: $name=$env{'user.name'};
9143: if ($name eq 'public' && $domain eq 'public') {
9144: if (!defined($env{'form.username'})) {
9145: $env{'form.username'}.=time.rand(10000000);
9146: }
9147: $name.=$env{'form.username'};
9148: }
9149: return ($symb,$courseid,$domain,$name,$publicuser);
9150:
9151: }
9152:
1.36 albertel 9153: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9154: # returns either the contents of the file or
9155: # -1 if the file doesn't exist
1.481 raeburn 9156: #
9157: # if the target is a file that was uploaded via DOCS,
9158: # a check will be made to see if a current copy exists on the local server,
9159: # if it does this will be served, otherwise a copy will be retrieved from
9160: # the home server for the course and stored in /home/httpd/html/userfiles on
9161: # the local server.
1.472 albertel 9162:
1.36 albertel 9163: sub getfile {
1.538 albertel 9164: my ($file) = @_;
1.609 banghart 9165: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9166: &repcopy($file);
9167: return &readfile($file);
9168: }
9169:
9170: sub repcopy_userfile {
9171: my ($file)=@_;
1.609 banghart 9172: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9173: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9174: my ($cdom,$cnum,$filename) =
1.811 albertel 9175: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9176: my $uri="/uploaded/$cdom/$cnum/$filename";
9177: if (-e "$file") {
1.828 www 9178: # we already have a local copy, check it out
1.538 albertel 9179: my @fileinfo = stat($file);
1.828 www 9180: my $rtncode;
9181: my $info;
1.538 albertel 9182: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9183: if ($lwpresp ne 'ok') {
1.828 www 9184: # there is no such file anymore, even though we had a local copy
1.482 albertel 9185: if ($rtncode eq '404') {
1.538 albertel 9186: unlink($file);
1.482 albertel 9187: }
9188: return -1;
9189: }
9190: if ($info < $fileinfo[9]) {
1.828 www 9191: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9192: return 'ok';
1.828 www 9193: } else {
9194: # the file is outdated, get rid of it
9195: unlink($file);
1.482 albertel 9196: }
1.828 www 9197: }
9198: # one way or the other, at this point, we don't have the file
9199: # construct the correct path for the file
9200: my @parts = ($cdom,$cnum);
9201: if ($filename =~ m|^(.+)/[^/]+$|) {
9202: push @parts, split(/\//,$1);
9203: }
9204: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9205: foreach my $part (@parts) {
9206: $path .= '/'.$part;
9207: if (!-e $path) {
9208: mkdir($path,0770);
1.482 albertel 9209: }
9210: }
1.828 www 9211: # now the path exists for sure
9212: # get a user agent
9213: my $ua=new LWP::UserAgent;
9214: my $transferfile=$file.'.in.transfer';
9215: # FIXME: this should flock
9216: if (-e $transferfile) { return 'ok'; }
9217: my $request;
9218: $uri=~s/^\///;
1.980 raeburn 9219: my $homeserver = &homeserver($cnum,$cdom);
9220: my $protocol = $protocol{$homeserver};
9221: $protocol = 'http' if ($protocol ne 'https');
9222: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9223: my $response=$ua->request($request,$transferfile);
9224: # did it work?
9225: if ($response->is_error()) {
9226: unlink($transferfile);
9227: &logthis("Userfile repcopy failed for $uri");
9228: return -1;
9229: }
9230: # worked, rename the transfer file
9231: rename($transferfile,$file);
1.607 raeburn 9232: return 'ok';
1.481 raeburn 9233: }
9234:
1.517 albertel 9235: sub tokenwrapper {
9236: my $uri=shift;
1.980 raeburn 9237: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9238: $uri=~s|^/||;
1.620 albertel 9239: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9240: my $token=$1;
1.552 albertel 9241: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9242: if ($udom && $uname && $file) {
9243: $file=~s|(\?\.*)*$||;
1.949 raeburn 9244: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9245: my $homeserver = &homeserver($uname,$udom);
9246: my $protocol = $protocol{$homeserver};
9247: $protocol = 'http' if ($protocol ne 'https');
9248: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9249: (($uri=~/\?/)?'&':'?').'token='.$token.
9250: '&tokenissued='.$perlvar{'lonHostID'};
9251: } else {
9252: return '/adm/notfound.html';
9253: }
9254: }
9255:
1.828 www 9256: # call with reqtype HEAD: get last modification time
9257: # call with reqtype GET: get the file contents
9258: # Do not call this with reqtype GET for large files! It loads everything into memory
9259: #
1.481 raeburn 9260: sub getuploaded {
9261: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9262: $uri=~s/^\///;
1.980 raeburn 9263: my $homeserver = &homeserver($cnum,$cdom);
9264: my $protocol = $protocol{$homeserver};
9265: $protocol = 'http' if ($protocol ne 'https');
9266: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9267: my $ua=new LWP::UserAgent;
9268: my $request=new HTTP::Request($reqtype,$uri);
9269: my $response=$ua->request($request);
9270: $$rtncode = $response->code;
1.482 albertel 9271: if (! $response->is_success()) {
9272: return 'failed';
9273: }
9274: if ($reqtype eq 'HEAD') {
1.486 www 9275: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9276: } elsif ($reqtype eq 'GET') {
9277: $$info = $response->content;
1.472 albertel 9278: }
1.482 albertel 9279: return 'ok';
1.36 albertel 9280: }
9281:
1.481 raeburn 9282: sub readfile {
9283: my $file = shift;
9284: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9285: my $fh;
9286: open($fh,"<$file");
9287: my $a='';
1.800 albertel 9288: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9289: return $a;
9290: }
9291:
1.36 albertel 9292: sub filelocation {
1.590 banghart 9293: my ($dir,$file) = @_;
9294: my $location;
9295: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9296:
9297: if ($file =~ m-^/adm/-) {
9298: $file=~s-^/adm/wrapper/-/-;
9299: $file=~s-^/adm/coursedocs/showdoc/-/-;
9300: }
1.882 albertel 9301:
1.590 banghart 9302: if ($file=~m:^/~:) { # is a contruction space reference
9303: $location = $file;
9304: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9305: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9306: # is a correct contruction space reference
9307: $location = $file;
1.956 raeburn 9308: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9309: $location = $file;
1.609 banghart 9310: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9311: my ($udom,$uname,$filename)=
1.811 albertel 9312: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9313: my $home=&homeserver($uname,$udom);
9314: my $is_me=0;
9315: my @ids=¤t_machine_ids();
9316: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9317: if ($is_me) {
1.955 raeburn 9318: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9319: } else {
9320: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9321: $udom.'/'.$uname.'/'.$filename;
9322: }
1.882 albertel 9323: } elsif ($file =~ m-^/adm/-) {
9324: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9325: } else {
9326: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9327: $file=~s:^/res/:/:;
9328: if ( !( $file =~ m:^/:) ) {
9329: $location = $dir. '/'.$file;
9330: } else {
9331: $location = '/home/httpd/html/res'.$file;
9332: }
1.59 albertel 9333: }
1.590 banghart 9334: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9335: while ($location=~m{/\.\./}) {
9336: if ($location =~ m{/[^/]+/\.\./}) {
9337: $location=~ s{/[^/]+/\.\./}{/}g;
9338: } else {
9339: $location=~ s{/\.\./}{/}g;
9340: }
9341: } #remove dir/..
1.590 banghart 9342: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9343: return $location;
1.46 www 9344: }
1.36 albertel 9345:
1.46 www 9346: sub hreflocation {
9347: my ($dir,$file)=@_;
1.980 raeburn 9348: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9349: $file=filelocation($dir,$file);
1.700 albertel 9350: } elsif ($file=~m-^/adm/-) {
9351: $file=~s-^/adm/wrapper/-/-;
9352: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9353: }
9354: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9355: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9356: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9357: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9358: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9359: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9360: -/uploaded/$1/$2/-x;
1.46 www 9361: }
1.913 albertel 9362: if ($file=~ m{^/userfiles/}) {
9363: $file =~ s{^/userfiles/}{/uploaded/};
9364: }
1.462 albertel 9365: return $file;
1.465 albertel 9366: }
9367:
9368: sub current_machine_domains {
1.853 albertel 9369: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9370: }
9371:
9372: sub machine_domains {
9373: my ($hostname) = @_;
1.465 albertel 9374: my @domains;
1.838 albertel 9375: my %hostname = &all_hostnames();
1.465 albertel 9376: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9377: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9378: if ($hostname eq $name) {
1.844 albertel 9379: push(@domains,&host_domain($id));
1.465 albertel 9380: }
9381: }
9382: return @domains;
9383: }
9384:
9385: sub current_machine_ids {
1.853 albertel 9386: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9387: }
9388:
9389: sub machine_ids {
9390: my ($hostname) = @_;
9391: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9392: my @ids;
1.888 albertel 9393: my %name_to_host = &all_names();
1.889 albertel 9394: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9395: return @{ $name_to_host{$hostname} };
9396: }
9397: return;
1.31 www 9398: }
9399:
1.824 raeburn 9400: sub additional_machine_domains {
9401: my @domains;
9402: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9403: while( my $line = <$fh>) {
9404: $line =~ s/\s//g;
9405: push(@domains,$line);
9406: }
9407: return @domains;
9408: }
9409:
9410: sub default_login_domain {
9411: my $domain = $perlvar{'lonDefDomain'};
9412: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9413: foreach my $posdom (¤t_machine_domains(),
9414: &additional_machine_domains()) {
9415: if (lc($posdom) eq lc($testdomain)) {
9416: $domain=$posdom;
9417: last;
9418: }
9419: }
9420: return $domain;
9421: }
9422:
1.31 www 9423: # ------------------------------------------------------------- Declutters URLs
9424:
9425: sub declutter {
9426: my $thisfn=shift;
1.569 albertel 9427: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9428: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9429: $thisfn=~s/^\///;
1.697 albertel 9430: $thisfn=~s|^adm/wrapper/||;
9431: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9432: $thisfn=~s/^res\///;
1.1032 raeburn 9433: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9434: $thisfn=~s/\?.+$//;
9435: }
1.268 www 9436: return $thisfn;
9437: }
9438:
9439: # ------------------------------------------------------------- Clutter up URLs
9440:
9441: sub clutter {
9442: my $thisfn='/'.&declutter(shift);
1.887 albertel 9443: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9444: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9445: $thisfn='/res'.$thisfn;
9446: }
1.1031 raeburn 9447: if ($thisfn !~m|^/adm|) {
9448: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9449: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9450: } else {
9451: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9452: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9453: if ($embstyle eq 'ssi'
9454: || ($embstyle eq 'hdn')
9455: || ($embstyle eq 'rat')
9456: || ($embstyle eq 'prv')
9457: || ($embstyle eq 'ign')) {
9458: #do nothing with these
9459: } elsif (($embstyle eq 'img')
1.695 albertel 9460: || ($embstyle eq 'emb')
9461: || ($embstyle eq 'wrp')) {
9462: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9463: } elsif ($embstyle eq 'unk'
9464: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9465: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9466: } else {
1.718 www 9467: # &logthis("Got a blank emb style");
1.695 albertel 9468: }
1.694 albertel 9469: }
9470: }
1.31 www 9471: return $thisfn;
1.12 www 9472: }
9473:
1.787 albertel 9474: sub clutter_with_no_wrapper {
9475: my $uri = &clutter(shift);
9476: if ($uri =~ m-^/adm/-) {
9477: $uri =~ s-^/adm/wrapper/-/-;
9478: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9479: }
9480: return $uri;
9481: }
9482:
1.557 albertel 9483: sub freeze_escape {
9484: my ($value)=@_;
9485: if (ref($value)) {
9486: $value=&nfreeze($value);
9487: return '__FROZEN__'.&escape($value);
9488: }
9489: return &escape($value);
9490: }
9491:
1.11 www 9492:
1.557 albertel 9493: sub thaw_unescape {
9494: my ($value)=@_;
9495: if ($value =~ /^__FROZEN__/) {
9496: substr($value,0,10,undef);
9497: $value=&unescape($value);
9498: return &thaw($value);
9499: }
9500: return &unescape($value);
9501: }
9502:
1.436 albertel 9503: sub correct_line_ends {
9504: my ($result)=@_;
9505: $$result =~s/\r\n/\n/mg;
9506: $$result =~s/\r/\n/mg;
1.415 albertel 9507: }
1.1 albertel 9508: # ================================================================ Main Program
9509:
1.184 www 9510: sub goodbye {
1.204 albertel 9511: &logthis("Starting Shut down");
1.443 albertel 9512: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9513: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9514: #converted
1.599 albertel 9515: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9516: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9517: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9518: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9519: #1.1 only
1.870 albertel 9520: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9521: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9522: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9523: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9524: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9525: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9526: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9527: &flushcourselogs();
9528: &logthis("Shutting down");
9529: }
9530:
1.852 albertel 9531: sub get_dns {
1.869 albertel 9532: my ($url,$func,$ignore_cache) = @_;
9533: if (!$ignore_cache) {
9534: my ($content,$cached)=
9535: &Apache::lonnet::is_cached_new('dns',$url);
9536: if ($cached) {
9537: &$func($content);
9538: return;
9539: }
9540: }
9541:
9542: my %alldns;
1.852 albertel 9543: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9544: foreach my $dns (<$config>) {
9545: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9546: my $line = $1;
9547: my ($host,$protocol) = split(/:/,$line);
9548: if ($protocol ne 'https') {
9549: $protocol = 'http';
9550: }
9551: $alldns{$host} = $protocol;
1.869 albertel 9552: }
9553: while (%alldns) {
9554: my ($dns) = keys(%alldns);
1.852 albertel 9555: my $ua=new LWP::UserAgent;
1.979 raeburn 9556: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9557: my $response=$ua->request($request);
1.979 raeburn 9558: delete($alldns{$dns});
1.852 albertel 9559: next if ($response->is_error());
9560: my @content = split("\n",$response->content);
1.869 albertel 9561: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9562: &$func(\@content);
1.869 albertel 9563: return;
1.852 albertel 9564: }
9565: close($config);
1.871 albertel 9566: my $which = (split('/',$url))[3];
9567: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9568: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9569: my @content = <$config>;
9570: &$func(\@content);
9571: return;
1.852 albertel 9572: }
1.327 albertel 9573: # ------------------------------------------------------------ Read domain file
9574: {
1.852 albertel 9575: my $loaded;
1.846 albertel 9576: my %domain;
9577:
1.852 albertel 9578: sub parse_domain_tab {
9579: my ($lines) = @_;
9580: foreach my $line (@$lines) {
9581: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9582:
1.846 albertel 9583: chomp($line);
1.852 albertel 9584: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9585: my %this_domain;
9586: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9587: 'lang_def', 'city', 'longi', 'lati',
9588: 'primary') {
9589: $this_domain{$field} = shift(@elements);
9590: }
9591: $domain{$name} = \%this_domain;
1.852 albertel 9592: }
9593: }
1.864 albertel 9594:
9595: sub reset_domain_info {
9596: undef($loaded);
9597: undef(%domain);
9598: }
9599:
1.852 albertel 9600: sub load_domain_tab {
1.869 albertel 9601: my ($ignore_cache) = @_;
9602: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9603: my $fh;
9604: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9605: my @lines = <$fh>;
9606: &parse_domain_tab(\@lines);
1.448 albertel 9607: }
1.852 albertel 9608: close($fh);
9609: $loaded = 1;
1.327 albertel 9610: }
1.846 albertel 9611:
9612: sub domain {
1.852 albertel 9613: &load_domain_tab() if (!$loaded);
9614:
1.846 albertel 9615: my ($name,$what) = @_;
9616: return if ( !exists($domain{$name}) );
9617:
9618: if (!$what) {
9619: return $domain{$name}{'description'};
9620: }
9621: return $domain{$name}{$what};
9622: }
1.974 raeburn 9623:
9624: sub domain_info {
9625: &load_domain_tab() if (!$loaded);
9626: return %domain;
9627: }
9628:
1.327 albertel 9629: }
9630:
9631:
1.1 albertel 9632: # ------------------------------------------------------------- Read hosts file
9633: {
1.838 albertel 9634: my %hostname;
1.844 albertel 9635: my %hostdom;
1.845 albertel 9636: my %libserv;
1.852 albertel 9637: my $loaded;
1.888 albertel 9638: my %name_to_host;
1.852 albertel 9639:
9640: sub parse_hosts_tab {
9641: my ($file) = @_;
9642: foreach my $configline (@$file) {
9643: next if ($configline =~ /^(\#|\s*$ )/x);
9644: next if ($configline =~ /^\^/);
9645: chomp($configline);
1.968 raeburn 9646: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 9647: $name=~s/\s//g;
9648: if ($id && $domain && $role && $name) {
9649: $hostname{$id}=$name;
1.888 albertel 9650: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9651: $hostdom{$id}=$domain;
9652: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9653: if (defined($protocol)) {
9654: if ($protocol eq 'https') {
9655: $protocol{$id} = $protocol;
9656: } else {
9657: $protocol{$id} = 'http';
9658: }
1.968 raeburn 9659: } else {
1.969 raeburn 9660: $protocol{$id} = 'http';
1.968 raeburn 9661: }
1.852 albertel 9662: }
9663: }
9664: }
1.864 albertel 9665:
9666: sub reset_hosts_info {
1.897 albertel 9667: &purge_remembered();
1.864 albertel 9668: &reset_domain_info();
9669: &reset_hosts_ip_info();
1.892 albertel 9670: undef(%name_to_host);
1.864 albertel 9671: undef(%hostname);
9672: undef(%hostdom);
9673: undef(%libserv);
9674: undef($loaded);
9675: }
1.1 albertel 9676:
1.852 albertel 9677: sub load_hosts_tab {
1.869 albertel 9678: my ($ignore_cache) = @_;
9679: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9680: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9681: my @config = <$config>;
9682: &parse_hosts_tab(\@config);
9683: close($config);
9684: $loaded=1;
1.1 albertel 9685: }
1.852 albertel 9686:
1.838 albertel 9687: sub hostname {
1.852 albertel 9688: &load_hosts_tab() if (!$loaded);
9689:
1.838 albertel 9690: my ($lonid) = @_;
9691: return $hostname{$lonid};
9692: }
1.845 albertel 9693:
1.838 albertel 9694: sub all_hostnames {
1.852 albertel 9695: &load_hosts_tab() if (!$loaded);
9696:
1.838 albertel 9697: return %hostname;
9698: }
1.845 albertel 9699:
1.888 albertel 9700: sub all_names {
9701: &load_hosts_tab() if (!$loaded);
9702:
9703: return %name_to_host;
9704: }
9705:
1.974 raeburn 9706: sub all_host_domain {
9707: &load_hosts_tab() if (!$loaded);
9708: return %hostdom;
9709: }
9710:
1.845 albertel 9711: sub is_library {
1.852 albertel 9712: &load_hosts_tab() if (!$loaded);
9713:
1.845 albertel 9714: return exists($libserv{$_[0]});
9715: }
9716:
9717: sub all_library {
1.852 albertel 9718: &load_hosts_tab() if (!$loaded);
9719:
1.845 albertel 9720: return %libserv;
9721: }
9722:
1.1062 droeschl 9723: sub unique_library {
9724: #2x reverse removes all hostnames that appear more than once
9725: my %unique = reverse &all_library();
9726: return reverse %unique;
9727: }
9728:
1.841 albertel 9729: sub get_servers {
1.852 albertel 9730: &load_hosts_tab() if (!$loaded);
9731:
1.841 albertel 9732: my ($domain,$type) = @_;
9733: my %possible_hosts = ($type eq 'library') ? %libserv
9734: : %hostname;
9735: my %result;
1.842 albertel 9736: if (ref($domain) eq 'ARRAY') {
9737: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9738: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9739: $result{$host} = $hostname;
9740: }
9741: }
9742: } else {
9743: while ( my ($host,$hostname) = each(%possible_hosts)) {
9744: if ($hostdom{$host} eq $domain) {
9745: $result{$host} = $hostname;
9746: }
1.841 albertel 9747: }
9748: }
9749: return %result;
9750: }
1.845 albertel 9751:
1.1062 droeschl 9752: sub get_unique_servers {
9753: my %unique = reverse &get_servers(@_);
9754: return reverse %unique;
9755: }
9756:
1.844 albertel 9757: sub host_domain {
1.852 albertel 9758: &load_hosts_tab() if (!$loaded);
9759:
1.844 albertel 9760: my ($lonid) = @_;
9761: return $hostdom{$lonid};
9762: }
9763:
1.841 albertel 9764: sub all_domains {
1.852 albertel 9765: &load_hosts_tab() if (!$loaded);
9766:
1.841 albertel 9767: my %seen;
9768: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9769: return @uniq;
9770: }
1.1 albertel 9771: }
9772:
1.847 albertel 9773: {
9774: my %iphost;
1.856 albertel 9775: my %name_to_ip;
9776: my %lonid_to_ip;
1.869 albertel 9777:
1.847 albertel 9778: sub get_hosts_from_ip {
9779: my ($ip) = @_;
9780: my %iphosts = &get_iphost();
9781: if (ref($iphosts{$ip})) {
9782: return @{$iphosts{$ip}};
9783: }
9784: return;
1.839 albertel 9785: }
1.864 albertel 9786:
9787: sub reset_hosts_ip_info {
9788: undef(%iphost);
9789: undef(%name_to_ip);
9790: undef(%lonid_to_ip);
9791: }
1.856 albertel 9792:
9793: sub get_host_ip {
9794: my ($lonid) = @_;
9795: if (exists($lonid_to_ip{$lonid})) {
9796: return $lonid_to_ip{$lonid};
9797: }
9798: my $name=&hostname($lonid);
9799: my $ip = gethostbyname($name);
9800: return if (!$ip || length($ip) ne 4);
9801: $ip=inet_ntoa($ip);
9802: $name_to_ip{$name} = $ip;
9803: $lonid_to_ip{$lonid} = $ip;
9804: return $ip;
9805: }
1.847 albertel 9806:
9807: sub get_iphost {
1.869 albertel 9808: my ($ignore_cache) = @_;
1.894 albertel 9809:
1.869 albertel 9810: if (!$ignore_cache) {
9811: if (%iphost) {
9812: return %iphost;
9813: }
9814: my ($ip_info,$cached)=
9815: &Apache::lonnet::is_cached_new('iphost','iphost');
9816: if ($cached) {
9817: %iphost = %{$ip_info->[0]};
9818: %name_to_ip = %{$ip_info->[1]};
9819: %lonid_to_ip = %{$ip_info->[2]};
9820: return %iphost;
9821: }
9822: }
1.894 albertel 9823:
9824: # get yesterday's info for fallback
9825: my %old_name_to_ip;
9826: my ($ip_info,$cached)=
9827: &Apache::lonnet::is_cached_new('iphost','iphost');
9828: if ($cached) {
9829: %old_name_to_ip = %{$ip_info->[1]};
9830: }
9831:
1.888 albertel 9832: my %name_to_host = &all_names();
9833: foreach my $name (keys(%name_to_host)) {
1.847 albertel 9834: my $ip;
9835: if (!exists($name_to_ip{$name})) {
9836: $ip = gethostbyname($name);
9837: if (!$ip || length($ip) ne 4) {
1.894 albertel 9838: if (defined($old_name_to_ip{$name})) {
9839: $ip = $old_name_to_ip{$name};
9840: &logthis("Can't find $name defaulting to old $ip");
9841: } else {
9842: &logthis("Name $name no IP found");
9843: next;
9844: }
9845: } else {
9846: $ip=inet_ntoa($ip);
1.847 albertel 9847: }
9848: $name_to_ip{$name} = $ip;
9849: } else {
9850: $ip = $name_to_ip{$name};
1.653 albertel 9851: }
1.888 albertel 9852: foreach my $id (@{ $name_to_host{$name} }) {
9853: $lonid_to_ip{$id} = $ip;
9854: }
9855: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9856: }
1.869 albertel 9857: &Apache::lonnet::do_cache_new('iphost','iphost',
9858: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9859: 48*60*60);
1.869 albertel 9860:
1.847 albertel 9861: return %iphost;
1.598 albertel 9862: }
9863:
1.992 raeburn 9864: #
9865: # Given a DNS returns the loncapa host name for that DNS
9866: #
9867: sub host_from_dns {
9868: my ($dns) = @_;
9869: my @hosts;
9870: my $ip;
9871:
1.993 raeburn 9872: if (exists($name_to_ip{$dns})) {
1.992 raeburn 9873: $ip = $name_to_ip{$dns};
9874: }
9875: if (!$ip) {
9876: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9877: if (length($ip) == 4) {
9878: $ip = &IO::Socket::inet_ntoa($ip);
9879: }
9880: }
9881: if ($ip) {
9882: @hosts = get_hosts_from_ip($ip);
9883: return $hosts[0];
9884: }
9885: return undef;
1.986 foxr 9886: }
1.992 raeburn 9887:
1.986 foxr 9888: }
9889:
1.862 albertel 9890: BEGIN {
9891:
9892: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9893: unless ($readit) {
9894: {
9895: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9896: %perlvar = (%perlvar,%{$configvars});
9897: }
9898:
9899:
1.1 albertel 9900: # ------------------------------------------------------ Read spare server file
9901: {
1.448 albertel 9902: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9903:
9904: while (my $configline=<$config>) {
9905: chomp($configline);
1.284 matthew 9906: if ($configline) {
1.784 albertel 9907: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9908: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9909: push(@{ $spareid{$type} }, $host);
1.1 albertel 9910: }
9911: }
1.448 albertel 9912: close($config);
1.1 albertel 9913: }
1.11 www 9914: # ------------------------------------------------------------ Read permissions
9915: {
1.448 albertel 9916: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9917:
9918: while (my $configline=<$config>) {
1.448 albertel 9919: chomp($configline);
9920: if ($configline) {
9921: my ($role,$perm)=split(/ /,$configline);
9922: if ($perm ne '') { $pr{$role}=$perm; }
9923: }
1.11 www 9924: }
1.448 albertel 9925: close($config);
1.11 www 9926: }
9927:
9928: # -------------------------------------------- Read plain texts for permissions
9929: {
1.448 albertel 9930: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9931:
9932: while (my $configline=<$config>) {
1.448 albertel 9933: chomp($configline);
9934: if ($configline) {
1.742 raeburn 9935: my ($short,@plain)=split(/:/,$configline);
9936: %{$prp{$short}} = ();
9937: if (@plain > 0) {
9938: $prp{$short}{'std'} = $plain[0];
9939: for (my $i=1; $i<@plain; $i++) {
9940: $prp{$short}{'alt'.$i} = $plain[$i];
9941: }
9942: }
1.448 albertel 9943: }
1.135 www 9944: }
1.448 albertel 9945: close($config);
1.135 www 9946: }
9947:
9948: # ---------------------------------------------------------- Read package table
9949: {
1.448 albertel 9950: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9951:
9952: while (my $configline=<$config>) {
1.483 albertel 9953: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9954: chomp($configline);
9955: my ($short,$plain)=split(/:/,$configline);
9956: my ($pack,$name)=split(/\&/,$short);
9957: if ($plain ne '') {
9958: $packagetab{$pack.'&'.$name.'&name'}=$name;
9959: $packagetab{$short}=$plain;
9960: }
1.11 www 9961: }
1.448 albertel 9962: close($config);
1.329 matthew 9963: }
9964:
9965: # ------------- set up temporary directory
9966: {
9967: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9968:
1.11 www 9969: }
9970:
1.794 albertel 9971: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9972: 'compress_threshold'=> 20_000,
9973: });
1.185 www 9974:
1.281 www 9975: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 9976: $dumpcount=0;
1.958 www 9977: $locknum=0;
1.22 www 9978:
1.163 harris41 9979: &logtouch();
1.672 albertel 9980: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 9981: $readit=1;
1.564 albertel 9982: {
9983: use integer;
9984: my $test=(2**32)+1;
1.568 albertel 9985: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 9986: &logthis(" Detected 64bit platform ($_64bit)");
9987: }
1.195 www 9988: }
1.1 albertel 9989: }
1.179 www 9990:
1.1 albertel 9991: 1;
1.191 harris41 9992: __END__
9993:
1.243 albertel 9994: =pod
9995:
1.191 harris41 9996: =head1 NAME
9997:
1.243 albertel 9998: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 9999:
10000: =head1 SYNOPSIS
10001:
1.243 albertel 10002: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10003:
10004: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10005:
1.243 albertel 10006: Common parameters:
10007:
10008: =over 4
10009:
10010: =item *
10011:
10012: $uname : an internal username (if $cname expecting a course Id specifically)
10013:
10014: =item *
10015:
10016: $udom : a domain (if $cdom expecting a course's domain specifically)
10017:
10018: =item *
10019:
10020: $symb : a resource instance identifier
10021:
10022: =item *
10023:
10024: $namespace : the name of a .db file that contains the data needed or
10025: being set.
10026:
10027: =back
10028:
1.394 bowersj2 10029: =head1 OVERVIEW
1.191 harris41 10030:
1.394 bowersj2 10031: lonnet provides subroutines which interact with the
10032: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10033: about classes, users, and resources.
1.243 albertel 10034:
10035: For many of these objects you can also use this to store data about
10036: them or modify them in various ways.
1.191 harris41 10037:
1.394 bowersj2 10038: =head2 Symbs
1.191 harris41 10039:
1.394 bowersj2 10040: To identify a specific instance of a resource, LON-CAPA uses symbols
10041: or "symbs"X<symb>. These identifiers are built from the URL of the
10042: map, the resource number of the resource in the map, and the URL of
10043: the resource itself. The latter is somewhat redundant, but might help
10044: if maps change.
10045:
10046: An example is
10047:
10048: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10049:
10050: The respective map entry is
10051:
10052: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10053: title="Problem 2">
10054: </resource>
10055:
10056: Symbs are used by the random number generator, as well as to store and
10057: restore data specific to a certain instance of for example a problem.
10058:
10059: =head2 Storing And Retrieving Data
10060:
10061: X<store()>X<cstore()>X<restore()>Three of the most important functions
10062: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10063: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10064: is is the non-critical message twin of cstore. These functions are for
10065: handlers to store a perl hash to a user's permanent data space in an
10066: easy manner, and to retrieve it again on another call. It is expected
10067: that a handler would use this once at the beginning to retrieve data,
10068: and then again once at the end to send only the new data back.
10069:
10070: The data is stored in the user's data directory on the user's
10071: homeserver under the ID of the course.
10072:
10073: The hash that is returned by restore will have all of the previous
10074: value for all of the elements of the hash.
10075:
10076: Example:
10077:
10078: #creating a hash
10079: my %hash;
10080: $hash{'foo'}='bar';
10081:
10082: #storing it
10083: &Apache::lonnet::cstore(\%hash);
10084:
10085: #changing a value
10086: $hash{'foo'}='notbar';
10087:
10088: #adding a new value
10089: $hash{'bar'}='foo';
10090: &Apache::lonnet::cstore(\%hash);
10091:
10092: #retrieving the hash
10093: my %history=&Apache::lonnet::restore();
10094:
10095: #print the hash
10096: foreach my $key (sort(keys(%history))) {
10097: print("\%history{$key} = $history{$key}");
10098: }
10099:
10100: Will print out:
1.191 harris41 10101:
1.394 bowersj2 10102: %history{1:foo} = bar
10103: %history{1:keys} = foo:timestamp
10104: %history{1:timestamp} = 990455579
10105: %history{2:bar} = foo
10106: %history{2:foo} = notbar
10107: %history{2:keys} = foo:bar:timestamp
10108: %history{2:timestamp} = 990455580
10109: %history{bar} = foo
10110: %history{foo} = notbar
10111: %history{timestamp} = 990455580
10112: %history{version} = 2
10113:
10114: Note that the special hash entries C<keys>, C<version> and
10115: C<timestamp> were added to the hash. C<version> will be equal to the
10116: total number of versions of the data that have been stored. The
10117: C<timestamp> attribute will be the UNIX time the hash was
10118: stored. C<keys> is available in every historical section to list which
10119: keys were added or changed at a specific historical revision of a
10120: hash.
10121:
10122: B<Warning>: do not store the hash that restore returns directly. This
10123: will cause a mess since it will restore the historical keys as if the
10124: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10125:
1.394 bowersj2 10126: Calling convention:
1.191 harris41 10127:
1.394 bowersj2 10128: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10129: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10130:
1.394 bowersj2 10131: For more detailed information, see lonnet specific documentation.
1.191 harris41 10132:
1.394 bowersj2 10133: =head1 RETURN MESSAGES
1.191 harris41 10134:
1.394 bowersj2 10135: =over 4
1.191 harris41 10136:
1.394 bowersj2 10137: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10138:
1.394 bowersj2 10139: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10140: when the connection is brought back up
1.191 harris41 10141:
1.394 bowersj2 10142: =item * B<con_failed>: unable to contact remote host and unable to save message
10143: for later delivery
1.191 harris41 10144:
1.967 bisitz 10145: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10146:
1.394 bowersj2 10147: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10148: that was requested
1.191 harris41 10149:
1.243 albertel 10150: =back
1.191 harris41 10151:
1.243 albertel 10152: =head1 PUBLIC SUBROUTINES
1.191 harris41 10153:
1.243 albertel 10154: =head2 Session Environment Functions
1.191 harris41 10155:
1.243 albertel 10156: =over 4
1.191 harris41 10157:
1.394 bowersj2 10158: =item *
10159: X<appenv()>
1.949 raeburn 10160: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10161: the user envirnoment file, and will be restored for each access this
1.620 albertel 10162: user makes during this session, also modifies the %env for the current
1.949 raeburn 10163: process. Optional rolesarrayref - if defined contains a reference to an array
10164: of roles which are exempt from the restriction on modifying user.role entries
10165: in the user's environment.db and in %env.
1.191 harris41 10166:
10167: =item *
1.394 bowersj2 10168: X<delenv()>
1.987 raeburn 10169: B<delenv($delthis,$regexp)>: removes all items from the session
10170: environment file that begin with $delthis. If the
10171: optional second arg - $regexp - is true, $delthis is treated as a
10172: regular expression, otherwise \Q$delthis\E is used.
10173: The values are also deleted from the current processes %env.
1.191 harris41 10174:
1.795 albertel 10175: =item * get_env_multiple($name)
10176:
10177: gets $name from the %env hash, it seemlessly handles the cases where multiple
10178: values may be defined and end up as an array ref.
10179:
10180: returns an array of values
10181:
1.243 albertel 10182: =back
10183:
10184: =head2 User Information
1.191 harris41 10185:
1.243 albertel 10186: =over 4
1.191 harris41 10187:
10188: =item *
1.394 bowersj2 10189: X<queryauthenticate()>
10190: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10191: authentication scheme
10192:
10193: =item *
1.394 bowersj2 10194: X<authenticate()>
10195: B<authenticate($uname,$upass,$udom)>: try to
10196: authenticate user from domain's lib servers (first use the current
10197: one). C<$upass> should be the users password.
1.191 harris41 10198:
10199: =item *
1.394 bowersj2 10200: X<homeserver()>
10201: B<homeserver($uname,$udom)>: find the server which has
10202: the user's directory and files (there must be only one), this caches
10203: the answer, and also caches if there is a borken connection.
1.191 harris41 10204:
10205: =item *
1.394 bowersj2 10206: X<idget()>
10207: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10208: (IDs are a unique resource in a domain, there must be only 1 ID per
10209: username, and only 1 username per ID in a specific domain) (returns
10210: hash: id=>name,id=>name)
1.191 harris41 10211:
10212: =item *
1.394 bowersj2 10213: X<idrget()>
10214: B<idrget($udom,@unames)>: find the IDs behind a list of
10215: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10216:
10217: =item *
1.394 bowersj2 10218: X<idput()>
10219: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10220:
10221: =item *
1.394 bowersj2 10222: X<rolesinit()>
10223: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10224:
10225: =item *
1.551 albertel 10226: X<getsection()>
10227: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10228: course $cname, return section name/number or '' for "not in course"
10229: and '-1' for "no section"
10230:
10231: =item *
1.394 bowersj2 10232: X<userenvironment()>
10233: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10234: passed in @what from the requested user's environment, returns a hash
10235:
1.858 raeburn 10236: =item *
10237: X<userlog_query()>
1.859 albertel 10238: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10239: activity.log file. %filters defines filters applied when parsing the
10240: log file. These can be start or end timestamps, or the type of action
10241: - log to look for Login or Logout events, check for Checkin or
10242: Checkout, role for role selection. The response is in the form
10243: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10244: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10245:
1.243 albertel 10246: =back
10247:
10248: =head2 User Roles
10249:
10250: =over 4
10251:
10252: =item *
10253:
1.810 raeburn 10254: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10255: F: full access
10256: U,I,K: authentication modes (cxx only)
10257: '': forbidden
10258: 1: user needs to choose course
10259: 2: browse allowed
1.766 albertel 10260: A: passphrase authentication needed
1.243 albertel 10261:
10262: =item *
10263:
10264: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10265: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10266: and course level
10267:
10268: =item *
10269:
1.988 raeburn 10270: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10271: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10272: $type is Course (default) or Community.
1.988 raeburn 10273: If $forcedefault evaluates to true, text returned will be default
10274: text for $type. Otherwise, if this is a course, the text returned
10275: will be a custom name for the role (if defined in the course's
10276: environment). If no custom name is defined the default is returned.
10277:
1.832 raeburn 10278: =item *
10279:
1.935 raeburn 10280: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10281: All arguments are optional. Returns a hash of a roles, either for
10282: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10283: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10284: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10285: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10286: For each key, value is set to colon-separated start and end times for
10287: the role. If no username and domain are specified, will default to
1.934 raeburn 10288: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10289: of role statuses (active, future or previous), roles
10290: (e.g., cc,in, st etc.) and domains of the roles which can be used
10291: to restrict the list of roles reported. If no array ref is
10292: provided for types, will default to return only active roles.
1.834 albertel 10293:
1.243 albertel 10294: =back
10295:
10296: =head2 User Modification
10297:
10298: =over 4
10299:
10300: =item *
10301:
1.957 raeburn 10302: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10303: user for the level given by URL. Optional start and end dates (leave empty
10304: string or zero for "no date")
1.191 harris41 10305:
10306: =item *
10307:
1.243 albertel 10308: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10309: change a users, password, possible return values are: ok,
10310: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10311: refused
1.191 harris41 10312:
10313: =item *
10314:
1.243 albertel 10315: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10316:
10317: =item *
10318:
1.1058 raeburn 10319: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10320: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10321:
10322: will update user information (firstname,middlename,lastname,generation,
10323: permanentemail), and if forceid is true, student/employee ID also.
10324: A user's institutional affiliation(s) can also be updated.
10325: User information fields will not be overwritten with empty entries
10326: unless the field is included in the $candelete array reference.
10327: This array is included when a single user is modified via "Manage Users",
10328: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10329:
10330: =item *
10331:
1.286 matthew 10332: modifystudent
10333:
1.957 raeburn 10334: modify a student's enrollment and identification information.
1.286 matthew 10335: The course id is resolved based on the current users environment.
10336: This means the envoking user must be a course coordinator or otherwise
10337: associated with a course.
10338:
1.297 matthew 10339: This call is essentially a wrapper for lonnet::modifyuser and
10340: lonnet::modify_student_enrollment
1.286 matthew 10341:
10342: Inputs:
10343:
10344: =over 4
10345:
1.957 raeburn 10346: =item B<$udom> Student's loncapa domain
1.286 matthew 10347:
1.957 raeburn 10348: =item B<$uname> Student's loncapa login name
1.286 matthew 10349:
1.964 bisitz 10350: =item B<$uid> Student/Employee ID
1.286 matthew 10351:
1.957 raeburn 10352: =item B<$umode> Student's authentication mode
1.286 matthew 10353:
1.957 raeburn 10354: =item B<$upass> Student's password
1.286 matthew 10355:
1.957 raeburn 10356: =item B<$first> Student's first name
1.286 matthew 10357:
1.957 raeburn 10358: =item B<$middle> Student's middle name
1.286 matthew 10359:
1.957 raeburn 10360: =item B<$last> Student's last name
1.286 matthew 10361:
1.957 raeburn 10362: =item B<$gene> Student's generation
1.286 matthew 10363:
1.957 raeburn 10364: =item B<$usec> Student's section in course
1.286 matthew 10365:
10366: =item B<$end> Unix time of the roles expiration
10367:
10368: =item B<$start> Unix time of the roles start date
10369:
10370: =item B<$forceid> If defined, allow $uid to be changed
10371:
10372: =item B<$desiredhome> server to use as home server for student
10373:
1.957 raeburn 10374: =item B<$email> Student's permanent e-mail address
10375:
10376: =item B<$type> Type of enrollment (auto or manual)
10377:
1.963 raeburn 10378: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10379:
10380: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10381:
1.963 raeburn 10382: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10383:
1.963 raeburn 10384: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10385:
1.963 raeburn 10386: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10387:
1.286 matthew 10388: =back
1.297 matthew 10389:
10390: =item *
10391:
10392: modify_student_enrollment
10393:
10394: Change a students enrollment status in a class. The environment variable
10395: 'role.request.course' must be defined for this function to proceed.
10396:
10397: Inputs:
10398:
10399: =over 4
10400:
10401: =item $udom, students domain
10402:
10403: =item $uname, students name
10404:
10405: =item $uid, students user id
10406:
10407: =item $first, students first name
10408:
10409: =item $middle
10410:
10411: =item $last
10412:
10413: =item $gene
10414:
10415: =item $usec
10416:
10417: =item $end
10418:
10419: =item $start
10420:
1.957 raeburn 10421: =item $type
10422:
10423: =item $locktype
10424:
10425: =item $cid
10426:
10427: =item $selfenroll
10428:
10429: =item $context
10430:
1.297 matthew 10431: =back
10432:
1.191 harris41 10433:
10434: =item *
10435:
1.243 albertel 10436: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10437: custom role; give a custom role to a user for the level given by URL. Specify
10438: name and domain of role author, and role name
1.191 harris41 10439:
10440: =item *
10441:
1.243 albertel 10442: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10443:
10444: =item *
10445:
1.243 albertel 10446: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10447:
10448: =back
10449:
10450: =head2 Course Infomation
10451:
10452: =over 4
1.191 harris41 10453:
10454: =item *
10455:
1.631 albertel 10456: coursedescription($courseid) : returns a hash of information about the
10457: specified course id, including all environment settings for the
10458: course, the description of the course will be in the hash under the
10459: key 'description'
1.191 harris41 10460:
10461: =item *
10462:
1.624 albertel 10463: resdata($name,$domain,$type,@which) : request for current parameter
10464: setting for a specific $type, where $type is either 'course' or 'user',
10465: @what should be a list of parameters to ask about. This routine caches
10466: answers for 5 minutes.
1.243 albertel 10467:
1.877 foxr 10468: =item *
10469:
10470: get_courseresdata($courseid, $domain) : dump the entire course resource
10471: data base, returning a hash that is keyed by the resource name and has
10472: values that are the resource value. I believe that the timestamps and
10473: versions are also returned.
10474:
10475:
1.243 albertel 10476: =back
10477:
10478: =head2 Course Modification
10479:
10480: =over 4
1.191 harris41 10481:
10482: =item *
10483:
1.243 albertel 10484: writecoursepref($courseid,%prefs) : write preferences (environment
10485: database) for a course
1.191 harris41 10486:
10487: =item *
10488:
1.1011 raeburn 10489: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10490:
10491: =item *
10492:
1.1038 raeburn 10493: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10494:
10495: =back
10496:
10497: =head2 Resource Subroutines
10498:
10499: =over 4
1.191 harris41 10500:
10501: =item *
10502:
1.243 albertel 10503: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10504:
10505: =item *
10506:
1.243 albertel 10507: repcopy($filename) : subscribes to the requested file, and attempts to
10508: replicate from the owning library server, Might return
1.607 raeburn 10509: 'unavailable', 'not_found', 'forbidden', 'ok', or
10510: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10511: resource. Expects the local filesystem pathname
10512: (/home/httpd/html/res/....)
10513:
10514: =back
10515:
10516: =head2 Resource Information
10517:
10518: =over 4
1.191 harris41 10519:
10520: =item *
10521:
1.243 albertel 10522: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10523: a vairety of different possible values, $varname should be a request
10524: string, and the other parameters can be used to specify who and what
10525: one is asking about.
10526:
10527: Possible values for $varname are environment.lastname (or other item
10528: from the envirnment hash), user.name (or someother aspect about the
10529: user), resource.0.maxtries (or some other part and parameter of a
10530: resource)
1.204 albertel 10531:
10532: =item *
10533:
1.243 albertel 10534: directcondval($number) : get current value of a condition; reads from a state
10535: string
1.204 albertel 10536:
10537: =item *
10538:
1.243 albertel 10539: condval($condidx) : value of condition index based on state
1.204 albertel 10540:
10541: =item *
10542:
1.243 albertel 10543: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10544: resource's metadata, $what should be either a specific key, or either
10545: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10546: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10547:
10548: this function automatically caches all requests
1.191 harris41 10549:
10550: =item *
10551:
1.243 albertel 10552: metadata_query($query,$custom,$customshow) : make a metadata query against the
10553: network of library servers; returns file handle of where SQL and regex results
10554: will be stored for query
1.191 harris41 10555:
10556: =item *
10557:
1.243 albertel 10558: symbread($filename) : return symbolic list entry (filename argument optional);
10559: returns the data handle
1.191 harris41 10560:
10561: =item *
10562:
1.243 albertel 10563: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10564: a possible symb for the URL in $thisfn, and if is an encryypted
10565: resource that the user accessed using /enc/ returns a 1 on success, 0
10566: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10567: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10568:
1.191 harris41 10569:
10570: =item *
10571:
1.243 albertel 10572: symbclean($symb) : removes versions numbers from a symb, returns the
10573: cleaned symb
1.191 harris41 10574:
10575: =item *
10576:
1.243 albertel 10577: is_on_map($uri) : checks if the $uri is somewhere on the current
10578: course map, user must be in a course for it to work.
1.191 harris41 10579:
10580: =item *
10581:
1.243 albertel 10582: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10583:
10584: =item *
10585:
1.243 albertel 10586: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10587: a random seed, all arguments are optional, if they aren't sent it uses the
10588: environment to derive them. Note: if symb isn't sent and it can't get one
10589: from &symbread it will use the current time as its return value
1.191 harris41 10590:
10591: =item *
10592:
1.243 albertel 10593: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10594: unfakeable, receipt
1.191 harris41 10595:
10596: =item *
10597:
1.620 albertel 10598: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10599:
10600: =item *
10601:
1.243 albertel 10602: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10603:
10604: =item *
10605:
1.243 albertel 10606: 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 10607:
10608: =item *
10609:
1.243 albertel 10610: 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 10611:
10612: =item *
10613:
1.243 albertel 10614: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10615:
10616: =item *
10617:
1.243 albertel 10618: devalidate($symb) : devalidate temporary spreadsheet calculations,
10619: forcing spreadsheet to reevaluate the resource scores next time.
10620:
10621: =back
10622:
10623: =head2 Storing/Retreiving Data
10624:
10625: =over 4
1.191 harris41 10626:
10627: =item *
10628:
1.243 albertel 10629: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10630: for this url; hashref needs to be given and should be a \%hashname; the
10631: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10632: be derived from the env
1.191 harris41 10633:
10634: =item *
10635:
1.243 albertel 10636: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10637: uses critical subroutine
1.191 harris41 10638:
10639: =item *
10640:
1.243 albertel 10641: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10642: all args are optional
1.191 harris41 10643:
10644: =item *
10645:
1.717 albertel 10646: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10647: dumps the complete (or key matching regexp) namespace into a hash
10648: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10649: normally &store()ed into
10650:
10651: $range should be either an integer '100' (give me the first 100
10652: matching records)
10653: or be two integers sperated by a - with no spaces
10654: '30-50' (give me the 30th through the 50th matching
10655: records)
10656:
10657:
10658: =item *
10659:
10660: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10661: replaces a &store() version of data with a replacement set of data
10662: for a particular resource in a namespace passed in the $storehash hash
10663: reference
10664:
10665: =item *
10666:
1.243 albertel 10667: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10668: works very similar to store/cstore, but all data is stored in a
10669: temporary location and can be reset using tmpreset, $storehash should
10670: be a hash reference, returns nothing on success
1.191 harris41 10671:
10672: =item *
10673:
1.243 albertel 10674: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10675: similar to restore, but all data is stored in a temporary location and
10676: can be reset using tmpreset. Returns a hash of values on success,
10677: error string otherwise.
1.191 harris41 10678:
10679: =item *
10680:
1.243 albertel 10681: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10682: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 10683:
10684: =item *
10685:
1.243 albertel 10686: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10687: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 10688:
10689: =item *
10690:
1.243 albertel 10691: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10692: namesp ($udom and $uname are optional)
1.191 harris41 10693:
10694: =item *
10695:
1.702 albertel 10696: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 10697: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 10698: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 10699:
1.702 albertel 10700: $range should be either an integer '100' (give me the first 100
10701: matching records)
10702: or be two integers sperated by a - with no spaces
10703: '30-50' (give me the 30th through the 50th matching
10704: records)
1.449 matthew 10705: =item *
10706:
10707: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10708: $store can be a scalar, an array reference, or if the amount to be
10709: incremented is > 1, a hash reference.
10710:
10711: ($udom and $uname are optional)
1.191 harris41 10712:
10713: =item *
10714:
1.243 albertel 10715: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10716: ($udom and $uname are optional)
1.191 harris41 10717:
10718: =item *
10719:
1.243 albertel 10720: cput($namespace,$storehash,$udom,$uname) : critical put
10721: ($udom and $uname are optional)
1.191 harris41 10722:
10723: =item *
10724:
1.748 albertel 10725: newput($namespace,$storehash,$udom,$uname) :
10726:
10727: Attempts to store the items in the $storehash, but only if they don't
10728: currently exist, if this succeeds you can be certain that you have
10729: successfully created a new key value pair in the $namespace db.
10730:
10731:
10732: Args:
10733: $namespace: name of database to store values to
10734: $storehash: hashref to store to the db
10735: $udom: (optional) domain of user containing the db
10736: $uname: (optional) name of user caontaining the db
10737:
10738: Returns:
10739: 'ok' -> succeeded in storing all keys of $storehash
10740: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10741: least <key> already existed in the db (other
10742: requested keys may also already exist)
1.967 bisitz 10743: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 10744: 'con_lost' -> unable to contact request server
10745: 'refused' -> action was not allowed by remote machine
10746:
10747:
10748: =item *
10749:
1.243 albertel 10750: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10751: reference filled in from namesp (encrypts the return communication)
10752: ($udom and $uname are optional)
1.191 harris41 10753:
10754: =item *
10755:
1.243 albertel 10756: log($udom,$name,$home,$message) : write to permanent log for user; use
10757: critical subroutine
10758:
1.806 raeburn 10759: =item *
10760:
1.860 raeburn 10761: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10762: array reference filled in from namespace found in domain level on either
10763: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 10764:
10765: =item *
10766:
1.860 raeburn 10767: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10768: domain level either on specified domain server ($uhome) or primary domain
10769: server ($udom and $uhome are optional)
1.806 raeburn 10770:
1.943 raeburn 10771: =item *
10772:
10773: get_domain_defaults($target_domain) : returns hash with defaults for
10774: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10775: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10776: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10777: Values are retrieved from cache (if current), or from domain's configuration.db
10778: (if available), or lastly from values in lonTabs/dns_domain,tab,
10779: or lonTabs/domain.tab.
10780:
10781: %domdefaults = &get_auth_defaults($target_domain);
10782:
1.243 albertel 10783: =back
10784:
10785: =head2 Network Status Functions
10786:
10787: =over 4
1.191 harris41 10788:
10789: =item *
10790:
10791: dirlist($uri) : return directory list based on URI
10792:
10793: =item *
10794:
1.243 albertel 10795: spareserver() : find server with least workload from spare.tab
10796:
1.986 foxr 10797:
10798: =item *
10799:
10800: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10801: if there is no corresponding loncapa host.
10802:
1.243 albertel 10803: =back
10804:
1.986 foxr 10805:
1.243 albertel 10806: =head2 Apache Request
10807:
10808: =over 4
1.191 harris41 10809:
10810: =item *
10811:
1.243 albertel 10812: ssi($url,%hash) : server side include, does a complete request cycle on url to
10813: localhost, posts hash
10814:
10815: =back
10816:
10817: =head2 Data to String to Data
10818:
10819: =over 4
1.191 harris41 10820:
10821: =item *
10822:
1.243 albertel 10823: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10824: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 10825:
10826: =item *
10827:
1.243 albertel 10828: hashref2str($hashref) : convert a hashref into a string complete with
10829: escaping and '=' and '&' separators, supports elements that are
10830: arrayrefs and hashrefs
1.191 harris41 10831:
10832: =item *
10833:
1.243 albertel 10834: arrayref2str($arrayref) : convert an arrayref into a string complete
10835: with escaping and '&' separators, supports elements that are arrayrefs
10836: and hashrefs
1.191 harris41 10837:
10838: =item *
10839:
1.243 albertel 10840: str2hash($string) : convert string to hash using unescaping and
10841: splitting on '=' and '&', supports elements that are arrayrefs and
10842: hashrefs
1.191 harris41 10843:
10844: =item *
10845:
1.243 albertel 10846: str2array($string) : convert string to hash using unescaping and
10847: splitting on '&', supports elements that are arrayrefs and hashrefs
10848:
10849: =back
10850:
10851: =head2 Logging Routines
10852:
10853: =over 4
10854:
10855: These routines allow one to make log messages in the lonnet.log and
10856: lonnet.perm logfiles.
1.191 harris41 10857:
10858: =item *
10859:
1.243 albertel 10860: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 10861:
10862: =item *
10863:
1.243 albertel 10864: logthis() : append message to the normal lonnet.log file, it gets
10865: preiodically rolled over and deleted.
1.191 harris41 10866:
10867: =item *
10868:
1.243 albertel 10869: logperm() : append a permanent message to lonnet.perm.log, this log
10870: file never gets deleted by any automated portion of the system, only
10871: messages of critical importance should go in here.
10872:
10873: =back
10874:
10875: =head2 General File Helper Routines
10876:
10877: =over 4
1.191 harris41 10878:
10879: =item *
10880:
1.481 raeburn 10881: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10882: (a) files in /uploaded
10883: (i) If a local copy of the file exists -
10884: compares modification date of local copy with last-modified date for
10885: definitive version stored on home server for course. If local copy is
10886: stale, requests a new version from the home server and stores it.
10887: If the original has been removed from the home server, then local copy
10888: is unlinked.
10889: (ii) If local copy does not exist -
10890: requests the file from the home server and stores it.
10891:
10892: If $caller is 'uploadrep':
10893: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10894: for request for files originally uploaded via DOCS.
10895: - returns 'ok' if fresh local copy now available, -1 otherwise.
10896:
10897: Otherwise:
10898: This indicates a call from the content generation phase of the request.
10899: - returns the entire contents of the file or -1.
10900:
10901: (b) files in /res
10902: - returns the entire contents of a file or -1;
10903: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 10904:
1.712 albertel 10905:
10906: =item *
10907:
10908: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10909: reference
10910:
10911: returns either a stat() list of data about the file or an empty list
10912: if the file doesn't exist or couldn't find out about it (connection
10913: problems or user unknown)
10914:
1.191 harris41 10915: =item *
10916:
1.243 albertel 10917: filelocation($dir,$file) : returns file system location of a file
10918: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10919: directory that relative $file lookups are to looked in ($dir of /a/dir
10920: and a file of ../bob will become /a/bob)
1.191 harris41 10921:
10922: =item *
10923:
10924: hreflocation($dir,$file) : returns file system location or a URL; same as
10925: filelocation except for hrefs
10926:
10927: =item *
10928:
10929: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10930:
1.243 albertel 10931: =back
10932:
1.608 albertel 10933: =head2 Usererfile file routines (/uploaded*)
10934:
10935: =over 4
10936:
10937: =item *
10938:
10939: userfileupload(): main rotine for putting a file in a user or course's
10940: filespace, arguments are,
10941:
1.620 albertel 10942: formname - required - this is the name of the element in $env where the
1.608 albertel 10943: filename, and the contents of the file to create/modifed exist
1.620 albertel 10944: the filename is in $env{'form.'.$formname.'.filename'} and the
10945: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10946: coursedoc - if true, store the file in the course of the active role
10947: of the current user
10948: subdir - required - subdirectory to put the file in under ../userfiles/
10949: if undefined, it will be placed in "unknown"
10950:
10951: (This routine calls clean_filename() to remove any dangerous
10952: characters from the filename, and then calls finuserfileupload() to
10953: complete the transaction)
10954:
10955: returns either the url of the uploaded file (/uploaded/....) if successful
10956: and /adm/notfound.html if unsuccessful
10957:
10958: =item *
10959:
10960: clean_filename(): routine for cleaing a filename up for storage in
10961: userfile space, argument is:
10962:
10963: filename - proposed filename
10964:
10965: returns: the new clean filename
10966:
10967: =item *
10968:
10969: finishuserfileupload(): routine that creaes and sends the file to
10970: userspace, probably shouldn't be called directly
10971:
10972: docuname: username or courseid of destination for the file
10973: docudom: domain of user/course of destination for the file
10974: formname: same as for userfileupload()
10975: fname: filename (inculding subdirectories) for the file
10976:
10977: returns either the url of the uploaded file (/uploaded/....) if successful
10978: and /adm/notfound.html if unsuccessful
10979:
10980: =item *
10981:
10982: renameuserfile(): renames an existing userfile to a new name
10983:
10984: Args:
10985: docuname: username or courseid of destination for the file
10986: docudom: domain of user/course of destination for the file
10987: old: current file name (including any subdirs under userfiles)
10988: new: desired file name (including any subdirs under userfiles)
10989:
10990: =item *
10991:
10992: mkdiruserfile(): creates a directory is a userfiles dir
10993:
10994: Args:
10995: docuname: username or courseid of destination for the file
10996: docudom: domain of user/course of destination for the file
10997: dir: dir to create (including any subdirs under userfiles)
10998:
10999: =item *
11000:
11001: removeuserfile(): removes a file that exists in userfiles
11002:
11003: Args:
11004: docuname: username or courseid of destination for the file
11005: docudom: domain of user/course of destination for the file
11006: fname: filname to delete (including any subdirs under userfiles)
11007:
11008: =item *
11009:
11010: removeuploadedurl(): convience function for removeuserfile()
11011:
11012: Args:
11013: url: a full /uploaded/... url to delete
11014:
1.747 albertel 11015: =item *
11016:
11017: get_portfile_permissions():
11018: Args:
11019: domain: domain of user or course contain the portfolio files
11020: user: name of user or num of course contain the portfolio files
11021: Returns:
11022: hashref of a dump of the proper file_permissions.db
11023:
11024:
11025: =item *
11026:
11027: get_access_controls():
11028:
11029: Args:
11030: current_permissions: the hash ref returned from get_portfile_permissions()
11031: group: (optional) the group you want the files associated with
11032: file: (optional) the file you want access info on
11033:
11034: Returns:
1.749 raeburn 11035: a hash (keys are file names) of hashes containing
11036: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11037: values are XML containing access control settings (see below)
1.747 albertel 11038:
11039: Internal notes:
11040:
1.749 raeburn 11041: access controls are stored in file_permissions.db as key=value pairs.
11042: key -> path to file/file_name\0uniqueID:scope_end_start
11043: where scope -> public,guest,course,group,domains or users.
11044: end -> UNIX time for end of access (0 -> no end date)
11045: start -> UNIX time for start of access
11046:
11047: value -> XML description of access control
11048: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11049: <start></start>
11050: <end></end>
11051:
11052: <password></password> for scope type = guest
11053:
11054: <domain></domain> for scope type = course or group
11055: <number></number>
11056: <roles id="">
11057: <role></role>
11058: <access></access>
11059: <section></section>
11060: <group></group>
11061: </roles>
11062:
11063: <dom></dom> for scope type = domains
11064:
11065: <users> for scope type = users
11066: <user>
11067: <uname></uname>
11068: <udom></udom>
11069: </user>
11070: </users>
11071: </scope>
11072:
11073: Access data is also aggregated for each file in an additional key=value pair:
11074: key -> path to file/file_name\0accesscontrol
11075: value -> reference to hash
11076: hash contains key = value pairs
11077: where key = uniqueID:scope_end_start
11078: value = UNIX time record was last updated
11079:
11080: Used to improve speed of look-ups of access controls for each file.
11081:
11082: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11083:
11084: modify_access_controls():
11085:
11086: Modifies access controls for a portfolio file
11087: Args
11088: 1. file name
11089: 2. reference to hash of required changes,
11090: 3. domain
11091: 4. username
11092: where domain,username are the domain of the portfolio owner
11093: (either a user or a course)
11094:
11095: Returns:
11096: 1. result of additions or updates ('ok' or 'error', with error message).
11097: 2. result of deletions ('ok' or 'error', with error message).
11098: 3. reference to hash of any new or updated access controls.
11099: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11100: key = integer (inbound ID)
11101: value = uniqueID
1.747 albertel 11102:
1.608 albertel 11103: =back
11104:
1.243 albertel 11105: =head2 HTTP Helper Routines
11106:
11107: =over 4
11108:
1.191 harris41 11109: =item *
11110:
11111: escape() : unpack non-word characters into CGI-compatible hex codes
11112:
11113: =item *
11114:
11115: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11116:
1.243 albertel 11117: =back
11118:
11119: =head1 PRIVATE SUBROUTINES
11120:
11121: =head2 Underlying communication routines (Shouldn't call)
11122:
11123: =over 4
11124:
11125: =item *
11126:
11127: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11128:
11129: =item *
11130:
11131: reply() : uses subreply to send a message to remote machine, logs all failures
11132:
11133: =item *
11134:
11135: critical() : passes a critical message to another server; if cannot
11136: get through then place message in connection buffer directory and
11137: returns con_delayed, if incapable of saving message, returns
11138: con_failed
11139:
11140: =item *
11141:
11142: reconlonc() : tries to reconnect lonc client processes.
11143:
11144: =back
11145:
11146: =head2 Resource Access Logging
11147:
11148: =over 4
11149:
11150: =item *
11151:
11152: flushcourselogs() : flush (save) buffer logs and access logs
11153:
11154: =item *
11155:
11156: courselog($what) : save message for course in hash
11157:
11158: =item *
11159:
11160: courseacclog($what) : save message for course using &courselog(). Perform
11161: special processing for specific resource types (problems, exams, quizzes, etc).
11162:
1.191 harris41 11163: =item *
11164:
11165: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11166: as a PerlChildExitHandler
1.243 albertel 11167:
11168: =back
11169:
11170: =head2 Other
11171:
11172: =over 4
11173:
11174: =item *
11175:
11176: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11177:
11178: =back
11179:
11180: =cut
1.877 foxr 11181:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>