Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.4.15
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.4.15! raeburn 4: # $Id: lonnet.pm,v 1.1056.4.14 2010/11/11 21:57:35 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1056.4.5 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
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.1056.4.13 raeburn 98: use File::Copy;
1.676 albertel 99:
1.195 www 100: my $readit;
1.550 foxr 101: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 102:
1.619 albertel 103: require Exporter;
104:
105: our @ISA = qw (Exporter);
106: our @EXPORT = qw(%env);
107:
1.449 matthew 108:
1.1 albertel 109: # --------------------------------------------------------------------- Logging
1.729 www 110: {
111: my $logid;
112: sub instructor_log {
1.957 raeburn 113: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
114: if (($cnum eq '') || ($cdom eq '')) {
115: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
116: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
117: }
1.729 www 118: $logid++;
1.957 raeburn 119: my $now = time();
120: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 121: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 122: { $id => {
123: 'exe_uname' => $env{'user.name'},
124: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 125: 'exe_time' => $now,
1.730 www 126: 'exe_ip' => $ENV{'REMOTE_ADDR'},
127: 'delflag' => $delflag,
128: 'logentry' => $storehash,
129: 'uname' => $uname,
130: 'udom' => $udom,
131: }
1.957 raeburn 132: },$cdom,$cnum);
1.729 www 133: }
134: }
1.1 albertel 135:
1.163 harris41 136: sub logtouch {
137: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 138: unless (-e "$execdir/logs/lonnet.log") {
139: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 140: close $fh;
141: }
142: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
143: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
144: }
145:
1.1 albertel 146: sub logthis {
147: my $message=shift;
148: my $execdir=$perlvar{'lonDaemons'};
149: my $now=time;
150: my $local=localtime($now);
1.448 albertel 151: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 152: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
153: print $fh $logstring;
1.448 albertel 154: close($fh);
155: }
1.1 albertel 156: return 1;
157: }
158:
159: sub logperm {
160: my $message=shift;
161: my $execdir=$perlvar{'lonDaemons'};
162: my $now=time;
163: my $local=localtime($now);
1.448 albertel 164: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
165: print $fh "$now:$message:$local\n";
166: close($fh);
167: }
1.1 albertel 168: return 1;
169: }
170:
1.850 albertel 171: sub create_connection {
1.853 albertel 172: my ($hostname,$lonid) = @_;
1.851 albertel 173: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 174: Type => SOCK_STREAM,
175: Timeout => 10);
176: return 0 if (!$client);
1.890 albertel 177: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 178: my $result = <$client>;
179: chomp($result);
180: return 1 if ($result eq 'done');
181: return 0;
182: }
183:
1.983 raeburn 184: sub get_server_timezone {
185: my ($cnum,$cdom) = @_;
186: my $home=&homeserver($cnum,$cdom);
187: if ($home ne 'no_host') {
188: my $cachetime = 24*3600;
189: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
190: if (defined($cached)) {
191: return $timezone;
192: } else {
193: my $timezone = &reply('servertimezone',$home);
194: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
195: }
196: }
197: }
1.850 albertel 198:
1.993 raeburn 199: sub get_server_loncaparev {
1.1056.4.3 raeburn 200: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 201: if (defined($lonhost)) {
202: if (!defined(&hostname($lonhost))) {
203: undef($lonhost);
204: }
205: }
206: if (!defined($lonhost)) {
207: if (defined(&domain($dom,'primary'))) {
208: $lonhost=&domain($dom,'primary');
209: if ($lonhost eq 'no_host') {
210: undef($lonhost);
211: }
212: }
213: }
214: if (defined($lonhost)) {
1.1056.4.3 raeburn 215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
218: if (defined($cached)) {
219: return $loncaparev;
220: }
221: }
222: my ($answer,$loncaparev);
223: my @ids=¤t_machine_ids();
224: if (grep(/^\Q$lonhost\E$/,@ids)) {
225: $answer = $perlvar{'lonVersion'};
1.1056.4.7 raeburn 226: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 raeburn 227: $loncaparev = $1;
228: }
229: } else {
230: $answer = &reply('serverloncaparev',$lonhost);
231: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
232: if ($caller eq 'loncron') {
233: my $ua=new LWP::UserAgent;
1.1056.4.8 raeburn 234: $ua->timeout(4);
1.1056.4.3 raeburn 235: my $protocol = $protocol{$lonhost};
236: $protocol = 'http' if ($protocol ne 'https');
237: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
238: my $request=new HTTP::Request('GET',$url);
239: my $response=$ua->request($request);
240: unless ($response->is_error()) {
241: my $content = $response->content;
1.1056.4.7 raeburn 242: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3 raeburn 243: $loncaparev = $1;
244: }
245: }
246: } else {
247: $loncaparev = $loncaparevs{$lonhost};
248: }
1.1056.4.7 raeburn 249: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 raeburn 250: $loncaparev = $1;
251: }
252: }
253: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
254: }
255: }
256:
257: sub get_server_homeID {
258: my ($hostname,$ignore_cache,$caller) = @_;
259: unless ($ignore_cache) {
260: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993 raeburn 261: if (defined($cached)) {
1.1056.4.3 raeburn 262: return $serverhomeID;
263: }
264: }
265: my $cachetime = 12*3600;
266: my $serverhomeID;
267: if ($caller eq 'loncron') {
268: my @machine_ids = &machine_ids($hostname);
269: foreach my $id (@machine_ids) {
270: my $response = &reply('serverhomeID',$id);
271: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
272: $serverhomeID = $response;
273: last;
274: }
1.993 raeburn 275: }
1.1056.4.3 raeburn 276: if ($serverhomeID eq '') {
277: $serverhomeID = $machine_ids[-1];
278: }
279: } else {
280: $serverhomeID = $serverhomeIDs{$hostname};
1.993 raeburn 281: }
1.1056.4.3 raeburn 282: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993 raeburn 283: }
284:
1.1 albertel 285: # -------------------------------------------------- Non-critical communication
286: sub subreply {
287: my ($cmd,$server)=@_;
1.838 albertel 288: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 289: #
290: # With loncnew process trimming, there's a timing hole between lonc server
291: # process exit and the master server picking up the listen on the AF_UNIX
292: # socket. In that time interval, a lock file will exist:
293:
294: my $lockfile=$peerfile.".lock";
295: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
296: sleep(1);
297: }
298: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 299: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 300: #
1.550 foxr 301: # We'll give the connection a few tries before abandoning it. If
302: # connection is not possible, we'll con_lost back to the client.
303: #
304: my $client;
305: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
306: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
307: Type => SOCK_STREAM,
308: Timeout => 10);
1.869 albertel 309: if ($client) {
1.550 foxr 310: last; # Connected!
1.850 albertel 311: } else {
1.853 albertel 312: &create_connection(&hostname($server),$server);
1.550 foxr 313: }
1.850 albertel 314: sleep(1); # Try again later if failed connection.
1.550 foxr 315: }
316: my $answer;
317: if ($client) {
1.704 albertel 318: print $client "sethost:$server:$cmd\n";
1.550 foxr 319: $answer=<$client>;
320: if (!$answer) { $answer="con_lost"; }
321: chomp($answer);
322: } else {
323: $answer = 'con_lost'; # Failed connection.
324: }
1.1 albertel 325: return $answer;
326: }
327:
328: sub reply {
329: my ($cmd,$server)=@_;
1.838 albertel 330: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 331: my $answer=subreply($cmd,$server);
1.65 www 332: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 333: &logthis("<font color=\"blue\">WARNING:".
1.12 www 334: " $cmd to $server returned $answer</font>");
335: }
1.1 albertel 336: return $answer;
337: }
338:
339: # ----------------------------------------------------------- Send USR1 to lonc
340:
341: sub reconlonc {
1.891 albertel 342: my ($lonid) = @_;
343: my $hostname = &hostname($lonid);
344: if ($lonid) {
345: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
346: if ($hostname && -e $peerfile) {
347: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
348: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
349: Type => SOCK_STREAM,
350: Timeout => 10);
351: if ($client) {
352: print $client ("reset_retries\n");
353: my $answer=<$client>;
354: #reset just this one.
355: }
356: }
357: return;
358: }
359:
1.836 www 360: &logthis("Trying to reconnect lonc");
1.1 albertel 361: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 362: if (open(my $fh,"<$loncfile")) {
1.1 albertel 363: my $loncpid=<$fh>;
364: chomp($loncpid);
365: if (kill 0 => $loncpid) {
366: &logthis("lonc at pid $loncpid responding, sending USR1");
367: kill USR1 => $loncpid;
368: sleep 1;
1.836 www 369: } else {
1.12 www 370: &logthis(
1.672 albertel 371: "<font color=\"blue\">WARNING:".
1.12 www 372: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 373: }
374: } else {
1.836 www 375: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 376: }
377: }
378:
379: # ------------------------------------------------------ Critical communication
1.12 www 380:
1.1 albertel 381: sub critical {
382: my ($cmd,$server)=@_;
1.838 albertel 383: unless (&hostname($server)) {
1.672 albertel 384: &logthis("<font color=\"blue\">WARNING:".
1.89 www 385: " Critical message to unknown server ($server)</font>");
386: return 'no_such_host';
387: }
1.1 albertel 388: my $answer=reply($cmd,$server);
389: if ($answer eq 'con_lost') {
390: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 391: my $answer=reply($cmd,$server);
1.1 albertel 392: if ($answer eq 'con_lost') {
393: my $now=time;
394: my $middlename=$cmd;
1.5 www 395: $middlename=substr($middlename,0,16);
1.1 albertel 396: $middlename=~s/\W//g;
397: my $dfilename=
1.305 www 398: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
399: $dumpcount++;
1.1 albertel 400: {
1.448 albertel 401: my $dfh;
402: if (open($dfh,">$dfilename")) {
403: print $dfh "$cmd\n";
404: close($dfh);
405: }
1.1 albertel 406: }
407: sleep 2;
408: my $wcmd='';
409: {
1.448 albertel 410: my $dfh;
411: if (open($dfh,"<$dfilename")) {
412: $wcmd=<$dfh>;
413: close($dfh);
414: }
1.1 albertel 415: }
416: chomp($wcmd);
1.7 www 417: if ($wcmd eq $cmd) {
1.672 albertel 418: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 419: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 420: &logperm("D:$server:$cmd");
421: return 'con_delayed';
422: } else {
1.672 albertel 423: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 424: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 425: &logperm("F:$server:$cmd");
426: return 'con_failed';
427: }
428: }
429: }
430: return $answer;
1.405 albertel 431: }
432:
1.755 albertel 433: # ------------------------------------------- check if return value is an error
434:
435: sub error {
436: my ($result) = @_;
1.756 albertel 437: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 438: if ($2 == 2) { return undef; }
439: return $1;
440: }
441: return undef;
442: }
443:
1.783 albertel 444: sub convert_and_load_session_env {
445: my ($lonidsdir,$handle)=@_;
446: my @profile;
447: {
1.917 albertel 448: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
449: if (!$opened) {
1.915 albertel 450: return 0;
451: }
1.783 albertel 452: flock($idf,LOCK_SH);
453: @profile=<$idf>;
454: close($idf);
455: }
456: my %temp_env;
457: foreach my $line (@profile) {
1.786 albertel 458: if ($line !~ m/=/) {
459: return 0;
460: }
1.783 albertel 461: chomp($line);
462: my ($envname,$envvalue)=split(/=/,$line,2);
463: $temp_env{&unescape($envname)} = &unescape($envvalue);
464: }
465: unlink("$lonidsdir/$handle.id");
466: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
467: 0640)) {
468: %disk_env = %temp_env;
469: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
470: untie(%disk_env);
471: }
1.786 albertel 472: return 1;
1.783 albertel 473: }
474:
1.374 www 475: # ------------------------------------------- Transfer profile into environment
1.780 albertel 476: my $env_loaded;
477: sub transfer_profile_to_env {
1.788 albertel 478: my ($lonidsdir,$handle,$force_transfer) = @_;
479: if (!$force_transfer && $env_loaded) { return; }
1.374 www 480:
1.720 albertel 481: if (!defined($lonidsdir)) {
482: $lonidsdir = $perlvar{'lonIDsDir'};
483: }
484: if (!defined($handle)) {
485: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
486: }
487:
1.786 albertel 488: my $convert;
489: {
1.917 albertel 490: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
491: if (!$opened) {
1.915 albertel 492: return;
493: }
1.786 albertel 494: flock($idf,LOCK_SH);
495: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
496: &GDBM_READER(),0640)) {
497: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
498: untie(%disk_env);
499: } else {
500: $convert = 1;
501: }
502: }
503: if ($convert) {
504: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
505: &logthis("Failed to load session, or convert session.");
506: }
1.374 www 507: }
1.783 albertel 508:
1.786 albertel 509: my %remove;
1.783 albertel 510: while ( my $envname = each(%env) ) {
1.433 matthew 511: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
512: if ($time < time-300) {
1.783 albertel 513: $remove{$key}++;
1.433 matthew 514: }
515: }
516: }
1.783 albertel 517:
1.619 albertel 518: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 519: $env_loaded=1;
1.783 albertel 520: foreach my $expired_key (keys(%remove)) {
1.433 matthew 521: &delenv($expired_key);
1.374 www 522: }
1.1 albertel 523: }
524:
1.916 albertel 525: # ---------------------------------------------------- Check for valid session
526: sub check_for_valid_session {
527: my ($r) = @_;
528: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
529: my $lonid=$cookies{'lonID'};
530: return undef if (!$lonid);
531:
532: my $handle=&LONCAPA::clean_handle($lonid->value);
533: my $lonidsdir=$r->dir_config('lonIDsDir');
534: return undef if (!-e "$lonidsdir/$handle.id");
535:
1.917 albertel 536: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
537: return undef if (!$opened);
1.916 albertel 538:
539: flock($idf,LOCK_SH);
540: my %disk_env;
541: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
542: &GDBM_READER(),0640)) {
543: return undef;
544: }
545:
546: if (!defined($disk_env{'user.name'})
547: || !defined($disk_env{'user.domain'})) {
548: return undef;
549: }
550: return $handle;
551: }
552:
1.830 albertel 553: sub timed_flock {
554: my ($file,$lock_type) = @_;
555: my $failed=0;
556: eval {
557: local $SIG{__DIE__}='DEFAULT';
558: local $SIG{ALRM}=sub {
559: $failed=1;
560: die("failed lock");
561: };
562: alarm(13);
563: flock($file,$lock_type);
564: alarm(0);
565: };
566: if ($failed) {
567: return undef;
568: } else {
569: return 1;
570: }
571: }
572:
1.5 www 573: # ---------------------------------------------------------- Append Environment
574:
575: sub appenv {
1.949 raeburn 576: my ($newenv,$roles) = @_;
577: if (ref($newenv) eq 'HASH') {
578: foreach my $key (keys(%{$newenv})) {
579: my $refused = 0;
580: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
581: $refused = 1;
582: if (ref($roles) eq 'ARRAY') {
583: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
584: if (grep(/^\Q$role\E$/,@{$roles})) {
585: $refused = 0;
586: }
587: }
588: }
589: if ($refused) {
590: &logthis("<font color=\"blue\">WARNING: ".
591: "Attempt to modify environment ".$key." to ".$newenv->{$key}
592: .'</font>');
593: delete($newenv->{$key});
594: } else {
595: $env{$key}=$newenv->{$key};
596: }
597: }
598: my $opened = open(my $env_file,'+<',$env{'user.environment'});
599: if ($opened
600: && &timed_flock($env_file,LOCK_EX)
601: &&
602: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
603: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
604: while (my ($key,$value) = each(%{$newenv})) {
605: $disk_env{$key} = $value;
606: }
607: untie(%disk_env);
1.35 www 608: }
1.191 harris41 609: }
1.56 www 610: return 'ok';
611: }
612: # ----------------------------------------------------- Delete from Environment
613:
614: sub delenv {
1.987 raeburn 615: my ($delthis,$regexp) = @_;
1.56 www 616: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 617: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 618: "Attempt to delete from environment ".$delthis);
619: return 'error';
620: }
1.917 albertel 621: my $opened = open(my $env_file,'+<',$env{'user.environment'});
622: if ($opened
1.915 albertel 623: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 624: &&
625: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
626: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 627: foreach my $key (keys(%disk_env)) {
1.987 raeburn 628: if ($regexp) {
629: if ($key=~/^$delthis/) {
630: delete($env{$key});
631: delete($disk_env{$key});
632: }
633: } else {
634: if ($key=~/^\Q$delthis\E/) {
635: delete($env{$key});
636: delete($disk_env{$key});
637: }
638: }
1.448 albertel 639: }
1.783 albertel 640: untie(%disk_env);
1.5 www 641: }
642: return 'ok';
1.369 albertel 643: }
644:
1.790 albertel 645: sub get_env_multiple {
646: my ($name) = @_;
647: my @values;
648: if (defined($env{$name})) {
649: # exists is it an array
650: if (ref($env{$name})) {
651: @values=@{ $env{$name} };
652: } else {
653: $values[0]=$env{$name};
654: }
655: }
656: return(@values);
657: }
658:
1.958 www 659: # ------------------------------------------------------------------- Locking
660:
661: sub set_lock {
662: my ($text)=@_;
663: $locknum++;
664: my $id=$$.'-'.$locknum;
665: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
666: 'session.lock.'.$id => $text});
667: return $id;
668: }
669:
670: sub get_locks {
671: my $num=0;
672: my %texts=();
673: foreach my $lock (split(/\,/,$env{'session.locks'})) {
674: if ($lock=~/\w/) {
675: $num++;
676: $texts{$lock}=$env{'session.lock.'.$lock};
677: }
678: }
679: return ($num,%texts);
680: }
681:
682: sub remove_lock {
683: my ($id)=@_;
684: my $newlocks='';
685: foreach my $lock (split(/\,/,$env{'session.locks'})) {
686: if (($lock=~/\w/) && ($lock ne $id)) {
687: $newlocks.=','.$lock;
688: }
689: }
690: &appenv({'session.locks' => $newlocks});
691: &delenv('session.lock.'.$id);
692: }
693:
694: sub remove_all_locks {
695: my $activelocks=$env{'session.locks'};
696: foreach my $lock (split(/\,/,$env{'session.locks'})) {
697: if ($lock=~/\w/) {
698: &remove_lock($lock);
699: }
700: }
701: }
702:
703:
1.369 albertel 704: # ------------------------------------------ Find out current server userload
705: sub userload {
706: my $numusers=0;
707: {
708: opendir(LONIDS,$perlvar{'lonIDsDir'});
709: my $filename;
710: my $curtime=time;
711: while ($filename=readdir(LONIDS)) {
1.925 albertel 712: next if ($filename eq '.' || $filename eq '..');
713: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 714: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 715: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 716: }
717: closedir(LONIDS);
718: }
719: my $userloadpercent=0;
720: my $maxuserload=$perlvar{'lonUserLoadLim'};
721: if ($maxuserload) {
1.371 albertel 722: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 723: }
1.372 albertel 724: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 725: return $userloadpercent;
1.283 www 726: }
727:
728: # ------------------------------------------ Fight off request when overloaded
729:
730: sub overloaderror {
731: my ($r,$checkserver)=@_;
732: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
733: my $loadavg;
734: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 735: open(my $loadfile,'/proc/loadavg');
1.283 www 736: $loadavg=<$loadfile>;
737: $loadavg =~ s/\s.*//g;
1.285 matthew 738: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 739: close($loadfile);
1.283 www 740: } else {
741: $loadavg=&reply('load',$checkserver);
742: }
1.285 matthew 743: my $overload=$loadavg-100;
1.283 www 744: if ($overload>0) {
1.285 matthew 745: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 746: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 747: return 413;
1.283 www 748: }
749: return '';
1.5 www 750: }
1.1 albertel 751:
752: # ------------------------------ Find server with least workload from spare.tab
1.11 www 753:
1.1 albertel 754: sub spareserver {
1.670 albertel 755: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 756: my $spare_server;
1.370 albertel 757: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 758: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
759: : $userloadpercent;
1.1056.4.8 raeburn 760: my ($uint_dom,$remotesessions);
761: if ($env{'user.domain'}) {
762: my $uprimary_id = &Apache::lonnet::domain($env{'user.domain'},'primary');
763: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
764: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
765: $remotesessions = $udomdefaults{'remotesessions'};
766: }
1.784 albertel 767: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8 raeburn 768: if ($uint_dom) {
769: next unless (&spare_can_host($env{'user.domain'},$uint_dom,
770: $remotesessions,$try_server));
771: }
1.784 albertel 772: ($spare_server, $lowest_load) =
773: &compare_server_load($try_server, $spare_server, $lowest_load);
774: }
775:
776: my $found_server = ($spare_server ne '' && $lowest_load < 100);
777:
778: if (!$found_server) {
779: foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8 raeburn 780: if ($uint_dom) {
781: next unless (&spare_can_host($env{'user.domain'},$uint_dom,
782: $remotesessions,$try_server));
783: }
1.784 albertel 784: ($spare_server, $lowest_load) =
785: &compare_server_load($try_server, $spare_server, $lowest_load);
786: }
787: }
788:
789: if (!$want_server_name) {
1.968 raeburn 790: my $protocol = 'http';
791: if ($protocol{$spare_server} eq 'https') {
792: $protocol = $protocol{$spare_server};
793: }
1.1001 raeburn 794: if (defined($spare_server)) {
795: my $hostname = &hostname($spare_server);
1.1056.4.8 raeburn 796: if (defined($hostname)) {
1.1001 raeburn 797: $spare_server = $protocol.'://'.$hostname;
798: }
799: }
1.784 albertel 800: }
801: return $spare_server;
802: }
803:
804: sub compare_server_load {
805: my ($try_server, $spare_server, $lowest_load) = @_;
806:
807: my $loadans = &reply('load', $try_server);
808: my $userloadans = &reply('userload',$try_server);
809:
810: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.3 raeburn 811: return; #didn't get a number from the server
1.784 albertel 812: }
813:
814: my $load;
815: if ($loadans =~ /\d/) {
816: if ($userloadans =~ /\d/) {
817: #both are numbers, pick the bigger one
818: $load = ($loadans > $userloadans) ? $loadans
819: : $userloadans;
1.411 albertel 820: } else {
1.784 albertel 821: $load = $loadans;
1.411 albertel 822: }
1.784 albertel 823: } else {
824: $load = $userloadans;
825: }
826:
827: if (($load =~ /\d/) && ($load < $lowest_load)) {
828: $spare_server = $try_server;
829: $lowest_load = $load;
1.370 albertel 830: }
1.784 albertel 831: return ($spare_server,$lowest_load);
1.202 matthew 832: }
1.914 albertel 833:
834: # --------------------------- ask offload servers if user already has a session
835: sub find_existing_session {
836: my ($udom,$uname) = @_;
837: foreach my $try_server (@{ $spareid{'primary'} },
838: @{ $spareid{'default'} }) {
839: return $try_server if (&has_user_session($try_server, $udom, $uname));
840: }
841: return;
842: }
843:
844: # -------------------------------- ask if server already has a session for user
845: sub has_user_session {
846: my ($lonid,$udom,$uname) = @_;
847: my $result = &reply(join(':','userhassession',
848: map {&escape($_)} ($udom,$uname)),$lonid);
849: return 1 if ($result eq 'ok');
850:
851: return 0;
852: }
853:
1.1056.4.3 raeburn 854: # --------- determine least loaded server in a user's domain which allows login
855:
856: sub choose_server {
857: my ($udom) = @_;
858: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
859: my %servers = &get_servers($udom);
860: my $lowest_load = 30000;
861: my ($login_host,$hostname);
862: foreach my $lonhost (keys(%servers)) {
863: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
864: if ($loginvia eq '') {
865: ($login_host, $lowest_load) =
866: &compare_server_load($lonhost, $login_host, $lowest_load);
867: }
868: }
869: if ($login_host ne '') {
870: $hostname = $servers{$login_host};
871: }
872: return ($login_host,$hostname);
873: }
874:
1.202 matthew 875: # --------------------------------------------- Try to change a user's password
876:
877: sub changepass {
1.799 raeburn 878: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 879: $currentpass = &escape($currentpass);
880: $newpass = &escape($newpass);
1.1030 raeburn 881: my $lonhost = $perlvar{'lonHostID'};
882: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 883: $server);
884: if (! $answer) {
885: &logthis("No reply on password change request to $server ".
886: "by $uname in domain $udom.");
887: } elsif ($answer =~ "^ok") {
888: &logthis("$uname in $udom successfully changed their password ".
889: "on $server.");
890: } elsif ($answer =~ "^pwchange_failure") {
891: &logthis("$uname in $udom was unable to change their password ".
892: "on $server. The action was blocked by either lcpasswd ".
893: "or pwchange");
894: } elsif ($answer =~ "^non_authorized") {
895: &logthis("$uname in $udom did not get their password correct when ".
896: "attempting to change it on $server.");
897: } elsif ($answer =~ "^auth_mode_error") {
898: &logthis("$uname in $udom attempted to change their password despite ".
899: "not being locally or internally authenticated on $server.");
900: } elsif ($answer =~ "^unknown_user") {
901: &logthis("$uname in $udom attempted to change their password ".
902: "on $server but were unable to because $server is not ".
903: "their home server.");
904: } elsif ($answer =~ "^refused") {
905: &logthis("$server refused to change $uname in $udom password because ".
906: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 907: } elsif ($answer =~ "invalid_client") {
908: &logthis("$server refused to change $uname in $udom password because ".
909: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 910: }
911: return $answer;
1.1 albertel 912: }
913:
1.169 harris41 914: # ----------------------- Try to determine user's current authentication scheme
915:
916: sub queryauthenticate {
917: my ($uname,$udom)=@_;
1.456 albertel 918: my $uhome=&homeserver($uname,$udom);
919: if (!$uhome) {
920: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
921: return 'no_host';
922: }
923: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
924: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
925: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 926: }
1.456 albertel 927: return $answer;
1.169 harris41 928: }
929:
1.1 albertel 930: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 931:
1.1 albertel 932: sub authenticate {
1.1056.4.3 raeburn 933: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 934: $upass=&escape($upass);
935: $uname= &LONCAPA::clean_username($uname);
1.836 www 936: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 937: my $newhome;
1.836 www 938: if ((!$uhome) || ($uhome eq 'no_host')) {
939: # Maybe the machine was offline and only re-appeared again recently?
940: &reconlonc();
941: # One more
1.952 raeburn 942: $uhome=&homeserver($uname,$udom,1);
943: if (($uhome eq 'no_host') && $checkdefauth) {
944: if (defined(&domain($udom,'primary'))) {
945: $newhome=&domain($udom,'primary');
946: }
947: if ($newhome ne '') {
948: $uhome = $newhome;
949: }
950: }
1.836 www 951: if ((!$uhome) || ($uhome eq 'no_host')) {
952: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 953: return 'no_host';
954: }
1.1 albertel 955: }
1.1056.4.3 raeburn 956: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 957: if ($answer eq 'authorized') {
1.952 raeburn 958: if ($newhome) {
959: &logthis("User $uname at $udom authorized by $uhome, but needs account");
960: return 'no_account_on_host';
961: } else {
962: &logthis("User $uname at $udom authorized by $uhome");
963: return $uhome;
964: }
1.471 albertel 965: }
966: if ($answer eq 'non_authorized') {
967: &logthis("User $uname at $udom rejected by $uhome");
968: return 'no_host';
1.9 www 969: }
1.471 albertel 970: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 971: return 'no_host';
972: }
973:
1.1056.4.3 raeburn 974: sub can_host_session {
975: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
976: my $canhost = 1;
977: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
978: if (ref($remotesessions) eq 'HASH') {
979: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
980: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
981: $canhost = 0;
982: } else {
983: $canhost = 1;
984: }
985: }
986: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
987: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
988: $canhost = 1;
989: } else {
990: $canhost = 0;
991: }
992: }
993: if ($canhost) {
994: if ($remotesessions->{'version'} ne '') {
995: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
996: if ($reqmajor ne '' && $reqminor ne '') {
997: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
998: my $major = $1;
999: my $minor = $2;
1000: if (($major < $reqmajor ) ||
1001: (($major == $reqmajor) && ($minor < $reqminor))) {
1002: $canhost = 0;
1003: }
1004: } else {
1005: $canhost = 0;
1006: }
1007: }
1008: }
1009: }
1010: }
1011: if ($canhost) {
1012: if (ref($hostedsessions) eq 'HASH') {
1013: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1014: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
1015: $canhost = 0;
1016: } else {
1017: $canhost = 1;
1018: }
1019: }
1020: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1021: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
1022: $canhost = 1;
1023: } else {
1024: $canhost = 0;
1025: }
1026: }
1027: }
1028: }
1029: return $canhost;
1030: }
1031:
1.1056.4.8 raeburn 1032: sub spare_can_host {
1033: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1034: my $canhost=1;
1035: my @intdoms;
1036: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1037: if (ref($internet_names) eq 'ARRAY') {
1038: @intdoms = @{$internet_names};
1039: }
1040: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1041: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1042: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1043: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1044: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1045: $canhost = &can_host_session($udom,$try_server,$remoterev,
1046: $remotesessions,
1047: $defdomdefaults{'hostedsessions'});
1048: }
1049: return $canhost;
1050: }
1051:
1.1 albertel 1052: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1053:
1.599 albertel 1054: my %homecache;
1.1 albertel 1055: sub homeserver {
1.230 stredwic 1056: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1057: my $index="$uname:$udom";
1.426 albertel 1058:
1.599 albertel 1059: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1060:
1061: my %servers = &get_servers($udom,'library');
1062: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1063: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1064: exists($badServerCache{$tryserver}));
1.841 albertel 1065:
1066: my $answer=reply("home:$udom:$uname",$tryserver);
1067: if ($answer eq 'found') {
1068: delete($badServerCache{$tryserver});
1069: return $homecache{$index}=$tryserver;
1070: } elsif ($answer eq 'no_host') {
1071: $badServerCache{$tryserver}=1;
1072: }
1.1 albertel 1073: }
1074: return 'no_host';
1.70 www 1075: }
1076:
1077: # ------------------------------------- Find the usernames behind a list of IDs
1078:
1079: sub idget {
1080: my ($udom,@ids)=@_;
1081: my %returnhash=();
1082:
1.841 albertel 1083: my %servers = &get_servers($udom,'library');
1084: foreach my $tryserver (keys(%servers)) {
1085: my $idlist=join('&',@ids);
1086: $idlist=~tr/A-Z/a-z/;
1087: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1088: my @answer=();
1089: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1090: @answer=split(/\&/,$reply);
1091: } ;
1092: my $i;
1093: for ($i=0;$i<=$#ids;$i++) {
1094: if ($answer[$i]) {
1095: $returnhash{$ids[$i]}=$answer[$i];
1096: }
1097: }
1098: }
1.70 www 1099: return %returnhash;
1100: }
1101:
1102: # ------------------------------------- Find the IDs behind a list of usernames
1103:
1104: sub idrget {
1105: my ($udom,@unames)=@_;
1106: my %returnhash=();
1.800 albertel 1107: foreach my $uname (@unames) {
1108: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1109: }
1.70 www 1110: return %returnhash;
1111: }
1112:
1113: # ------------------------------- Store away a list of names and associated IDs
1114:
1115: sub idput {
1116: my ($udom,%ids)=@_;
1117: my %servers=();
1.800 albertel 1118: foreach my $uname (keys(%ids)) {
1119: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1120: my $uhom=&homeserver($uname,$udom);
1.70 www 1121: if ($uhom ne 'no_host') {
1.800 albertel 1122: my $id=&escape($ids{$uname});
1.70 www 1123: $id=~tr/A-Z/a-z/;
1.800 albertel 1124: my $esc_unam=&escape($uname);
1.70 www 1125: if ($servers{$uhom}) {
1.800 albertel 1126: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1127: } else {
1.800 albertel 1128: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1129: }
1130: }
1.191 harris41 1131: }
1.800 albertel 1132: foreach my $server (keys(%servers)) {
1133: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1134: }
1.344 www 1135: }
1136:
1.1023 raeburn 1137: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1138: sub dump_dom {
1.1023 raeburn 1139: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1140: if (!$udom) {
1141: $udom=$env{'user.domain'};
1142: }
1143: my %returnhash;
1.1023 raeburn 1144: if ($udom) {
1145: my $uname = &get_domainconfiguser($udom);
1146: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1147: }
1148: return %returnhash;
1149: }
1150:
1.1023 raeburn 1151: # ------------------------------------------ get items from domain db files
1.806 raeburn 1152:
1153: sub get_dom {
1.860 raeburn 1154: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1155: my $items='';
1156: foreach my $item (@$storearr) {
1157: $items.=&escape($item).'&';
1158: }
1159: $items=~s/\&$//;
1.860 raeburn 1160: if (!$udom) {
1161: $udom=$env{'user.domain'};
1162: if (defined(&domain($udom,'primary'))) {
1163: $uhome=&domain($udom,'primary');
1164: } else {
1.874 albertel 1165: undef($uhome);
1.860 raeburn 1166: }
1167: } else {
1168: if (!$uhome) {
1169: if (defined(&domain($udom,'primary'))) {
1170: $uhome=&domain($udom,'primary');
1171: }
1172: }
1173: }
1174: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1175: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1176: my %returnhash;
1.875 albertel 1177: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1178: return %returnhash;
1179: }
1.806 raeburn 1180: my @pairs=split(/\&/,$rep);
1181: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1182: return @pairs;
1183: }
1184: my $i=0;
1185: foreach my $item (@$storearr) {
1186: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1187: $i++;
1188: }
1189: return %returnhash;
1190: } else {
1.880 banghart 1191: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1192: }
1193: }
1194:
1195: # -------------------------------------------- put items in domain db files
1196:
1197: sub put_dom {
1.860 raeburn 1198: my ($namespace,$storehash,$udom,$uhome)=@_;
1199: if (!$udom) {
1200: $udom=$env{'user.domain'};
1201: if (defined(&domain($udom,'primary'))) {
1202: $uhome=&domain($udom,'primary');
1203: } else {
1.874 albertel 1204: undef($uhome);
1.860 raeburn 1205: }
1206: } else {
1207: if (!$uhome) {
1208: if (defined(&domain($udom,'primary'))) {
1209: $uhome=&domain($udom,'primary');
1210: }
1211: }
1212: }
1213: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1214: my $items='';
1215: foreach my $item (keys(%$storehash)) {
1216: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1217: }
1218: $items=~s/\&$//;
1219: return &reply("putdom:$udom:$namespace:$items",$uhome);
1220: } else {
1.860 raeburn 1221: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1222: }
1223: }
1224:
1.1023 raeburn 1225: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1226: sub newput_dom {
1.1023 raeburn 1227: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1228: my $result;
1229: if (!$udom) {
1230: $udom=$env{'user.domain'};
1231: }
1.1023 raeburn 1232: if ($udom) {
1233: my $uname = &get_domainconfiguser($udom);
1234: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1235: }
1236: return $result;
1237: }
1238:
1.1023 raeburn 1239: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1240: sub del_dom {
1.1023 raeburn 1241: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1242: if (ref($storearr) eq 'ARRAY') {
1243: if (!$udom) {
1244: $udom=$env{'user.domain'};
1245: }
1.1023 raeburn 1246: if ($udom) {
1247: my $uname = &get_domainconfiguser($udom);
1248: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1249: }
1250: }
1251: }
1252:
1.1023 raeburn 1253: # ----------------------------------construct domainconfig user for a domain
1254: sub get_domainconfiguser {
1255: my ($udom) = @_;
1256: return $udom.'-domainconfig';
1257: }
1258:
1.837 raeburn 1259: sub retrieve_inst_usertypes {
1260: my ($udom) = @_;
1261: my (%returnhash,@order);
1.989 raeburn 1262: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1263: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1264: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1265: %returnhash = %{$domdefs{'inststatustypes'}};
1266: @order = @{$domdefs{'inststatusorder'}};
1267: } else {
1268: if (defined(&domain($udom,'primary'))) {
1269: my $uhome=&domain($udom,'primary');
1270: my $rep=&reply("inst_usertypes:$udom",$uhome);
1271: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1272: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1273: return (\%returnhash,\@order);
1274: }
1275: my ($hashitems,$orderitems) = split(/:/,$rep);
1276: my @pairs=split(/\&/,$hashitems);
1277: foreach my $item (@pairs) {
1278: my ($key,$value)=split(/=/,$item,2);
1279: $key = &unescape($key);
1280: next if ($key =~ /^error: 2 /);
1281: $returnhash{$key}=&thaw_unescape($value);
1282: }
1283: my @esc_order = split(/\&/,$orderitems);
1284: foreach my $item (@esc_order) {
1285: push(@order,&unescape($item));
1286: }
1287: } else {
1288: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1289: }
1290: }
1291: return (\%returnhash,\@order);
1292: }
1293:
1.868 raeburn 1294: sub is_domainimage {
1295: my ($url) = @_;
1296: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1297: if (&domain($1) ne '') {
1298: return '1';
1299: }
1300: }
1301: return;
1302: }
1303:
1.899 raeburn 1304: sub inst_directory_query {
1305: my ($srch) = @_;
1306: my $udom = $srch->{'srchdomain'};
1307: my %results;
1308: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1309: my $outcome;
1.899 raeburn 1310: if ($homeserver ne '') {
1.904 albertel 1311: my $queryid=&reply("querysend:instdirsearch:".
1312: &escape($srch->{'srchby'}).':'.
1313: &escape($srch->{'srchterm'}).':'.
1314: &escape($srch->{'srchtype'}),$homeserver);
1315: my $host=&hostname($homeserver);
1316: if ($queryid !~/^\Q$host\E\_/) {
1317: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1318: return;
1319: }
1320: my $response = &get_query_reply($queryid);
1321: my $maxtries = 5;
1322: my $tries = 1;
1323: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1324: $response = &get_query_reply($queryid);
1325: $tries ++;
1326: }
1327:
1328: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1329: if ($response eq 'unavailable') {
1330: $outcome = $response;
1331: } else {
1332: $outcome = 'ok';
1333: my @matches = split(/\n/,$response);
1334: foreach my $match (@matches) {
1335: my ($key,$value) = split(/=/,$match);
1336: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1337: }
1.899 raeburn 1338: }
1339: }
1340: }
1.909 raeburn 1341: return ($outcome,%results);
1.899 raeburn 1342: }
1343:
1344: sub usersearch {
1345: my ($srch) = @_;
1346: my $dom = $srch->{'srchdomain'};
1347: my %results;
1348: my %libserv = &all_library();
1349: my $query = 'usersearch';
1350: foreach my $tryserver (keys(%libserv)) {
1351: if (&host_domain($tryserver) eq $dom) {
1352: my $host=&hostname($tryserver);
1353: my $queryid=
1.911 raeburn 1354: &reply("querysend:".&escape($query).':'.
1355: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1356: &escape($srch->{'srchtype'}).':'.
1357: &escape($srch->{'srchterm'}),$tryserver);
1358: if ($queryid !~/^\Q$host\E\_/) {
1359: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1360: next;
1.899 raeburn 1361: }
1362: my $reply = &get_query_reply($queryid);
1363: my $maxtries = 1;
1364: my $tries = 1;
1365: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1366: $reply = &get_query_reply($queryid);
1367: $tries ++;
1368: }
1369: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1370: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1371: } else {
1.911 raeburn 1372: my @matches;
1373: if ($reply =~ /\n/) {
1374: @matches = split(/\n/,$reply);
1375: } else {
1376: @matches = split(/\&/,$reply);
1377: }
1.899 raeburn 1378: foreach my $match (@matches) {
1379: my ($uname,$udom,%userhash);
1.911 raeburn 1380: foreach my $entry (split(/:/,$match)) {
1381: my ($key,$value) =
1382: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1383: $userhash{$key} = $value;
1384: if ($key eq 'username') {
1385: $uname = $value;
1386: } elsif ($key eq 'domain') {
1387: $udom = $value;
1.911 raeburn 1388: }
1.899 raeburn 1389: }
1390: $results{$uname.':'.$udom} = \%userhash;
1391: }
1392: }
1393: }
1394: }
1395: return %results;
1396: }
1397:
1.912 raeburn 1398: sub get_instuser {
1399: my ($udom,$uname,$id) = @_;
1400: my $homeserver = &domain($udom,'primary');
1401: my ($outcome,%results);
1402: if ($homeserver ne '') {
1403: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1404: &escape($id).':'.&escape($udom),$homeserver);
1405: my $host=&hostname($homeserver);
1406: if ($queryid !~/^\Q$host\E\_/) {
1407: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1408: return;
1409: }
1410: my $response = &get_query_reply($queryid);
1411: my $maxtries = 5;
1412: my $tries = 1;
1413: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1414: $response = &get_query_reply($queryid);
1415: $tries ++;
1416: }
1417: if (!&error($response) && $response ne 'refused') {
1418: if ($response eq 'unavailable') {
1419: $outcome = $response;
1420: } else {
1421: $outcome = 'ok';
1422: my @matches = split(/\n/,$response);
1423: foreach my $match (@matches) {
1424: my ($key,$value) = split(/=/,$match);
1425: $results{&unescape($key)} = &thaw_unescape($value);
1426: }
1427: }
1428: }
1429: }
1430: my %userinfo;
1431: if (ref($results{$uname}) eq 'HASH') {
1432: %userinfo = %{$results{$uname}};
1433: }
1434: return ($outcome,%userinfo);
1435: }
1436:
1437: sub inst_rulecheck {
1.923 raeburn 1438: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1439: my %returnhash;
1440: if ($udom ne '') {
1441: if (ref($rules) eq 'ARRAY') {
1442: @{$rules} = map {&escape($_);} (@{$rules});
1443: my $rulestr = join(':',@{$rules});
1444: my $homeserver=&domain($udom,'primary');
1445: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1446: my $response;
1447: if ($item eq 'username') {
1448: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1449: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1450: $homeserver));
1.923 raeburn 1451: } elsif ($item eq 'id') {
1452: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1453: ':'.&escape($id).':'.$rulestr,
1454: $homeserver));
1.945 raeburn 1455: } elsif ($item eq 'selfcreate') {
1456: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1457: &escape($udom).':'.&escape($uname).
1458: ':'.$rulestr,$homeserver));
1.923 raeburn 1459: }
1.912 raeburn 1460: if ($response ne 'refused') {
1461: my @pairs=split(/\&/,$response);
1462: foreach my $item (@pairs) {
1463: my ($key,$value)=split(/=/,$item,2);
1464: $key = &unescape($key);
1465: next if ($key =~ /^error: 2 /);
1466: $returnhash{$key}=&thaw_unescape($value);
1467: }
1468: }
1469: }
1470: }
1471: }
1472: return %returnhash;
1473: }
1474:
1475: sub inst_userrules {
1.923 raeburn 1476: my ($udom,$check) = @_;
1.912 raeburn 1477: my (%ruleshash,@ruleorder);
1478: if ($udom ne '') {
1479: my $homeserver=&domain($udom,'primary');
1480: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1481: my $response;
1482: if ($check eq 'id') {
1483: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1484: $homeserver);
1.943 raeburn 1485: } elsif ($check eq 'email') {
1486: $response=&reply('instemailrules:'.&escape($udom),
1487: $homeserver);
1.923 raeburn 1488: } else {
1489: $response=&reply('instuserrules:'.&escape($udom),
1490: $homeserver);
1491: }
1.912 raeburn 1492: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1493: ($response ne 'unknown_cmd') &&
1.912 raeburn 1494: ($response ne 'no_such_host')) {
1495: my ($hashitems,$orderitems) = split(/:/,$response);
1496: my @pairs=split(/\&/,$hashitems);
1497: foreach my $item (@pairs) {
1498: my ($key,$value)=split(/=/,$item,2);
1499: $key = &unescape($key);
1500: next if ($key =~ /^error: 2 /);
1501: $ruleshash{$key}=&thaw_unescape($value);
1502: }
1503: my @esc_order = split(/\&/,$orderitems);
1504: foreach my $item (@esc_order) {
1505: push(@ruleorder,&unescape($item));
1506: }
1507: }
1508: }
1509: }
1510: return (\%ruleshash,\@ruleorder);
1511: }
1512:
1.976 raeburn 1513: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1514:
1515: sub get_domain_defaults {
1516: my ($domain) = @_;
1517: my $cachetime = 60*60*24;
1518: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1519: if (defined($cached)) {
1520: if (ref($result) eq 'HASH') {
1521: return %{$result};
1522: }
1523: }
1524: my %domdefaults;
1525: my %domconfig =
1.989 raeburn 1526: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1527: 'requestcourses','inststatus',
1.1056.4.3 raeburn 1528: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1529: if (ref($domconfig{'defaults'}) eq 'HASH') {
1530: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1531: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1532: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1533: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1534: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1535: } else {
1536: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1537: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1538: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1539: }
1.976 raeburn 1540: if (ref($domconfig{'quotas'}) eq 'HASH') {
1541: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1542: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1543: } else {
1544: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1545: }
1546: my @usertools = ('aboutme','blog','portfolio');
1547: foreach my $item (@usertools) {
1548: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1549: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1550: }
1551: }
1552: }
1.985 raeburn 1553: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1554: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1555: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1556: }
1557: }
1.989 raeburn 1558: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1559: foreach my $item ('inststatustypes','inststatusorder') {
1560: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1561: }
1562: }
1.1047 raeburn 1563: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1564: foreach my $item ('canuse_pdfforms') {
1565: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1566: }
1567: }
1.1056.4.3 raeburn 1568: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1569: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1570: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1571: }
1572: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1573: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1574: }
1575: }
1.943 raeburn 1576: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1577: $cachetime);
1578: return %domdefaults;
1579: }
1580:
1.344 www 1581: # --------------------------------------------------- Assign a key to a student
1582:
1583: sub assign_access_key {
1.364 www 1584: #
1585: # a valid key looks like uname:udom#comments
1586: # comments are being appended
1587: #
1.498 www 1588: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1589: $kdom=
1.620 albertel 1590: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1591: $knum=
1.620 albertel 1592: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1593: $cdom=
1.620 albertel 1594: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1595: $cnum=
1.620 albertel 1596: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1597: $udom=$env{'user.name'} unless (defined($udom));
1598: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1599: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1600: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1601: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1602: # assigned to this person
1603: # - this should not happen,
1.345 www 1604: # unless something went wrong
1605: # the first time around
1606: # ready to assign
1.364 www 1607: $logentry=$1.'; '.$logentry;
1.496 www 1608: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1609: $kdom,$knum) eq 'ok') {
1.345 www 1610: # key now belongs to user
1.346 www 1611: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1612: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1613: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1614: return 'ok';
1615: } else {
1616: return
1617: 'error: Count not permanently assign key, will need to be re-entered later.';
1618: }
1619: } else {
1620: return 'error: Could not assign key, try again later.';
1621: }
1.364 www 1622: } elsif (!$existing{$ckey}) {
1.345 www 1623: # the key does not exist
1624: return 'error: The key does not exist';
1625: } else {
1626: # the key is somebody else's
1627: return 'error: The key is already in use';
1628: }
1.344 www 1629: }
1630:
1.364 www 1631: # ------------------------------------------ put an additional comment on a key
1632:
1633: sub comment_access_key {
1634: #
1635: # a valid key looks like uname:udom#comments
1636: # comments are being appended
1637: #
1638: my ($ckey,$cdom,$cnum,$logentry)=@_;
1639: $cdom=
1.620 albertel 1640: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1641: $cnum=
1.620 albertel 1642: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1643: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1644: if ($existing{$ckey}) {
1645: $existing{$ckey}.='; '.$logentry;
1646: # ready to assign
1.367 www 1647: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1648: $cdom,$cnum) eq 'ok') {
1649: return 'ok';
1650: } else {
1651: return 'error: Count not store comment.';
1652: }
1653: } else {
1654: # the key does not exist
1655: return 'error: The key does not exist';
1656: }
1657: }
1658:
1.344 www 1659: # ------------------------------------------------------ Generate a set of keys
1660:
1661: sub generate_access_keys {
1.364 www 1662: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1663: $cdom=
1.620 albertel 1664: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1665: $cnum=
1.620 albertel 1666: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1667: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1668: unless (($cdom) && ($cnum)) { return 0; }
1669: if ($number>10000) { return 0; }
1670: sleep(2); # make sure don't get same seed twice
1671: srand(time()^($$+($$<<15))); # from "Programming Perl"
1672: my $total=0;
1673: for (my $i=1;$i<=$number;$i++) {
1674: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1675: sprintf("%lx",int(100000*rand)).'-'.
1676: sprintf("%lx",int(100000*rand));
1677: $newkey=~s/1/g/g; # folks mix up 1 and l
1678: $newkey=~s/0/h/g; # and also 0 and O
1679: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1680: if ($existing{$newkey}) {
1681: $i--;
1682: } else {
1.364 www 1683: if (&put('accesskeys',
1684: { $newkey => '# generated '.localtime().
1.620 albertel 1685: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1686: '; '.$logentry },
1687: $cdom,$cnum) eq 'ok') {
1.344 www 1688: $total++;
1689: }
1690: }
1691: }
1.620 albertel 1692: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1693: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1694: return $total;
1695: }
1696:
1697: # ------------------------------------------------------- Validate an accesskey
1698:
1699: sub validate_access_key {
1700: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1701: $cdom=
1.620 albertel 1702: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1703: $cnum=
1.620 albertel 1704: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1705: $udom=$env{'user.domain'} unless (defined($udom));
1706: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1707: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1708: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1709: }
1710:
1711: # ------------------------------------- Find the section of student in a course
1.652 albertel 1712: sub devalidate_getsection_cache {
1713: my ($udom,$unam,$courseid)=@_;
1714: my $hashid="$udom:$unam:$courseid";
1715: &devalidate_cache_new('getsection',$hashid);
1716: }
1.298 matthew 1717:
1.815 albertel 1718: sub courseid_to_courseurl {
1719: my ($courseid) = @_;
1720: #already url style courseid
1721: return $courseid if ($courseid =~ m{^/});
1722:
1723: if (exists($env{'course.'.$courseid.'.num'})) {
1724: my $cnum = $env{'course.'.$courseid.'.num'};
1725: my $cdom = $env{'course.'.$courseid.'.domain'};
1726: return "/$cdom/$cnum";
1727: }
1728:
1729: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1730: if (exists($courseinfo{'num'})) {
1731: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1732: }
1733:
1734: return undef;
1735: }
1736:
1.298 matthew 1737: sub getsection {
1738: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1739: my $cachetime=1800;
1.551 albertel 1740:
1741: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1742: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1743: if (defined($cached)) { return $result; }
1744:
1.298 matthew 1745: my %Pending;
1746: my %Expired;
1747: #
1748: # Each role can either have not started yet (pending), be active,
1749: # or have expired.
1750: #
1751: # If there is an active role, we are done.
1752: #
1753: # If there is more than one role which has not started yet,
1754: # choose the one which will start sooner
1755: # If there is one role which has not started yet, return it.
1756: #
1757: # If there is more than one expired role, choose the one which ended last.
1758: # If there is a role which has expired, return it.
1759: #
1.815 albertel 1760: $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 1761: my $extra = &freeze_escape({'skipcheck' => 1});
1762: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1763: foreach my $key (keys(%roleshash)) {
1.479 albertel 1764: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1765: my $section=$1;
1766: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1767: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1768: my $now=time;
1.548 albertel 1769: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1770: $Expired{$end}=$section;
1771: next;
1772: }
1.548 albertel 1773: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1774: $Pending{$start}=$section;
1775: next;
1776: }
1.599 albertel 1777: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1778: }
1779: #
1780: # Presumedly there will be few matching roles from the above
1781: # loop and the sorting time will be negligible.
1782: if (scalar(keys(%Pending))) {
1783: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1784: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1785: }
1786: if (scalar(keys(%Expired))) {
1787: my @sorted = sort {$a <=> $b} keys(%Expired);
1788: my $time = pop(@sorted);
1.599 albertel 1789: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1790: }
1.599 albertel 1791: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1792: }
1.70 www 1793:
1.599 albertel 1794: sub save_cache {
1795: &purge_remembered();
1.722 albertel 1796: #&Apache::loncommon::validate_page();
1.620 albertel 1797: undef(%env);
1.780 albertel 1798: undef($env_loaded);
1.599 albertel 1799: }
1.452 albertel 1800:
1.599 albertel 1801: my $to_remember=-1;
1802: my %remembered;
1803: my %accessed;
1804: my $kicks=0;
1805: my $hits=0;
1.849 albertel 1806: sub make_key {
1807: my ($name,$id) = @_;
1.872 albertel 1808: if (length($id) > 65
1809: && length(&escape($id)) > 200) {
1810: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1811: }
1.849 albertel 1812: return &escape($name.':'.$id);
1813: }
1814:
1.599 albertel 1815: sub devalidate_cache_new {
1816: my ($name,$id,$debug) = @_;
1817: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1818: $id=&make_key($name,$id);
1.599 albertel 1819: $memcache->delete($id);
1820: delete($remembered{$id});
1821: delete($accessed{$id});
1822: }
1823:
1824: sub is_cached_new {
1825: my ($name,$id,$debug) = @_;
1.849 albertel 1826: $id=&make_key($name,$id);
1.599 albertel 1827: if (exists($remembered{$id})) {
1828: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1829: $accessed{$id}=[&gettimeofday()];
1830: $hits++;
1831: return ($remembered{$id},1);
1832: }
1833: my $value = $memcache->get($id);
1834: if (!(defined($value))) {
1835: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1836: return (undef,undef);
1.416 albertel 1837: }
1.599 albertel 1838: if ($value eq '__undef__') {
1839: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1840: $value=undef;
1841: }
1842: &make_room($id,$value,$debug);
1843: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1844: return ($value,1);
1845: }
1846:
1847: sub do_cache_new {
1848: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1849: $id=&make_key($name,$id);
1.599 albertel 1850: my $setvalue=$value;
1851: if (!defined($setvalue)) {
1852: $setvalue='__undef__';
1853: }
1.623 albertel 1854: if (!defined($time) ) {
1855: $time=600;
1856: }
1.599 albertel 1857: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1858: my $result = $memcache->set($id,$setvalue,$time);
1859: if (! $result) {
1.872 albertel 1860: &logthis("caching of id -> $id failed");
1.910 albertel 1861: $memcache->disconnect_all();
1.872 albertel 1862: }
1.600 albertel 1863: # need to make a copy of $value
1.919 albertel 1864: &make_room($id,$value,$debug);
1.599 albertel 1865: return $value;
1866: }
1867:
1868: sub make_room {
1869: my ($id,$value,$debug)=@_;
1.919 albertel 1870:
1871: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1872: : $value;
1.599 albertel 1873: if ($to_remember<0) { return; }
1874: $accessed{$id}=[&gettimeofday()];
1875: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1876: my $to_kick;
1877: my $max_time=0;
1878: foreach my $other (keys(%accessed)) {
1879: if (&tv_interval($accessed{$other}) > $max_time) {
1880: $to_kick=$other;
1881: $max_time=&tv_interval($accessed{$other});
1882: }
1883: }
1884: delete($remembered{$to_kick});
1885: delete($accessed{$to_kick});
1886: $kicks++;
1887: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1888: return;
1889: }
1890:
1.599 albertel 1891: sub purge_remembered {
1.604 albertel 1892: #&logthis("Tossing ".scalar(keys(%remembered)));
1893: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1894: undef(%remembered);
1895: undef(%accessed);
1.428 albertel 1896: }
1.70 www 1897: # ------------------------------------- Read an entry from a user's environment
1898:
1899: sub userenvironment {
1900: my ($udom,$unam,@what)=@_;
1.976 raeburn 1901: my $items;
1902: foreach my $item (@what) {
1903: $items.=&escape($item).'&';
1904: }
1905: $items=~s/\&$//;
1.70 www 1906: my %returnhash=();
1.1009 raeburn 1907: my $uhome = &homeserver($unam,$udom);
1908: unless ($uhome eq 'no_host') {
1909: my @answer=split(/\&/,
1910: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1911: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1912: return %returnhash;
1913: }
1.1009 raeburn 1914: my $i;
1915: for ($i=0;$i<=$#what;$i++) {
1916: $returnhash{$what[$i]}=&unescape($answer[$i]);
1917: }
1.70 www 1918: }
1919: return %returnhash;
1.1 albertel 1920: }
1921:
1.617 albertel 1922: # ---------------------------------------------------------- Get a studentphoto
1923: sub studentphoto {
1924: my ($udom,$unam,$ext) = @_;
1925: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1926: if (defined($env{'request.course.id'})) {
1.708 raeburn 1927: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1928: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1929: return(&retrievestudentphoto($udom,$unam,$ext));
1930: } else {
1931: my ($result,$perm_reqd)=
1.707 albertel 1932: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1933: if ($result eq 'ok') {
1934: if (!($perm_reqd eq 'yes')) {
1935: return(&retrievestudentphoto($udom,$unam,$ext));
1936: }
1937: }
1938: }
1939: }
1940: } else {
1941: my ($result,$perm_reqd) =
1.707 albertel 1942: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1943: if ($result eq 'ok') {
1944: if (!($perm_reqd eq 'yes')) {
1945: return(&retrievestudentphoto($udom,$unam,$ext));
1946: }
1947: }
1948: }
1949: return '/adm/lonKaputt/lonlogo_broken.gif';
1950: }
1951:
1952: sub retrievestudentphoto {
1953: my ($udom,$unam,$ext,$type) = @_;
1954: my $home=&Apache::lonnet::homeserver($unam,$udom);
1955: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1956: if ($ret eq 'ok') {
1957: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1958: if ($type eq 'thumbnail') {
1959: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1960: }
1961: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1962: return $tokenurl;
1963: } else {
1964: if ($type eq 'thumbnail') {
1965: return '/adm/lonKaputt/genericstudent_tn.gif';
1966: } else {
1967: return '/adm/lonKaputt/lonlogo_broken.gif';
1968: }
1.617 albertel 1969: }
1970: }
1971:
1.263 www 1972: # -------------------------------------------------------------------- New chat
1973:
1974: sub chatsend {
1.724 raeburn 1975: my ($newentry,$anon,$group)=@_;
1.620 albertel 1976: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1977: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1978: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1979: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1980: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1981: &escape($newentry)).':'.$group,$chome);
1.292 www 1982: }
1983:
1984: # ------------------------------------------ Find current version of a resource
1985:
1986: sub getversion {
1987: my $fname=&clutter(shift);
1988: unless ($fname=~/^\/res\//) { return -1; }
1989: return ¤tversion(&filelocation('',$fname));
1990: }
1991:
1992: sub currentversion {
1993: my $fname=shift;
1.599 albertel 1994: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1995: if (defined($cached)) { return $result; }
1.292 www 1996: my $author=$fname;
1997: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1998: my ($udom,$uname)=split(/\//,$author);
1999: my $home=homeserver($uname,$udom);
2000: if ($home eq 'no_host') {
2001: return -1;
2002: }
2003: my $answer=reply("currentversion:$fname",$home);
2004: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2005: return -1;
2006: }
1.599 albertel 2007: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 2008: }
2009:
1.1 albertel 2010: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2011:
1.1 albertel 2012: sub subscribe {
2013: my $fname=shift;
1.761 raeburn 2014: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2015: $fname=~s/[\n\r]//g;
1.1 albertel 2016: my $author=$fname;
2017: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2018: my ($udom,$uname)=split(/\//,$author);
2019: my $home=homeserver($uname,$udom);
1.335 albertel 2020: if ($home eq 'no_host') {
2021: return 'not_found';
1.1 albertel 2022: }
2023: my $answer=reply("sub:$fname",$home);
1.64 www 2024: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2025: $answer.=' by '.$home;
2026: }
1.1 albertel 2027: return $answer;
2028: }
2029:
1.8 www 2030: # -------------------------------------------------------------- Replicate file
2031:
2032: sub repcopy {
2033: my $filename=shift;
1.23 www 2034: $filename=~s/\/+/\//g;
1.607 raeburn 2035: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2036: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2037: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2038: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2039: return &repcopy_userfile($filename);
2040: }
1.532 albertel 2041: $filename=~s/[\n\r]//g;
1.8 www 2042: my $transname="$filename.in.transfer";
1.828 www 2043: # FIXME: this should flock
1.607 raeburn 2044: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2045: my $remoteurl=subscribe($filename);
1.64 www 2046: if ($remoteurl =~ /^con_lost by/) {
2047: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2048: return 'unavailable';
1.8 www 2049: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2050: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2051: return 'not_found';
1.64 www 2052: } elsif ($remoteurl =~ /^rejected by/) {
2053: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2054: return 'forbidden';
1.20 www 2055: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2056: return 'ok';
1.8 www 2057: } else {
1.290 www 2058: my $author=$filename;
2059: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2060: my ($udom,$uname)=split(/\//,$author);
2061: my $home=homeserver($uname,$udom);
2062: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2063: my @parts=split(/\//,$filename);
2064: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2065: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2066: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2067: return 'bad_request';
1.8 www 2068: }
2069: my $count;
2070: for ($count=5;$count<$#parts;$count++) {
2071: $path.="/$parts[$count]";
2072: if ((-e $path)!=1) {
2073: mkdir($path,0777);
2074: }
2075: }
2076: my $ua=new LWP::UserAgent;
2077: my $request=new HTTP::Request('GET',"$remoteurl");
2078: my $response=$ua->request($request,$transname);
2079: if ($response->is_error()) {
2080: unlink($transname);
2081: my $message=$response->status_line;
1.672 albertel 2082: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2083: ." LWP get: $message: $filename</font>");
1.607 raeburn 2084: return 'unavailable';
1.8 www 2085: } else {
1.16 www 2086: if ($remoteurl!~/\.meta$/) {
2087: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2088: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2089: if ($mresponse->is_error()) {
2090: unlink($filename.'.meta');
2091: &logthis(
1.672 albertel 2092: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2093: }
2094: }
1.8 www 2095: rename($transname,$filename);
1.607 raeburn 2096: return 'ok';
1.8 www 2097: }
1.290 www 2098: }
1.8 www 2099: }
1.330 www 2100: }
2101:
2102: # ------------------------------------------------ Get server side include body
2103: sub ssi_body {
1.381 albertel 2104: my ($filelink,%form)=@_;
1.606 matthew 2105: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2106: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2107: }
1.953 www 2108: my $output='';
2109: my $response;
1.980 raeburn 2110: if ($filelink=~/^https?\:/) {
1.954 raeburn 2111: ($output,$response)=&externalssi($filelink);
1.953 www 2112: } else {
1.1004 droeschl 2113: $filelink .= $filelink=~/\?/ ? '&' : '?';
2114: $filelink .= 'inhibitmenu=yes';
1.953 www 2115: ($output,$response)=&ssi($filelink,%form);
2116: }
1.778 albertel 2117: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2118: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2119: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2120: if (wantarray) {
2121: return ($output, $response);
2122: } else {
2123: return $output;
2124: }
1.8 www 2125: }
2126:
1.15 www 2127: # --------------------------------------------------------- Server Side Include
2128:
1.782 albertel 2129: sub absolute_url {
2130: my ($host_name) = @_;
2131: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2132: if ($host_name eq '') {
2133: $host_name = $ENV{'SERVER_NAME'};
2134: }
2135: return $protocol.$host_name;
2136: }
2137:
1.942 foxr 2138: #
2139: # Server side include.
2140: # Parameters:
2141: # fn Possibly encrypted resource name/id.
2142: # form Hash that describes how the rendering should be done
2143: # and other things.
1.944 foxr 2144: # Returns:
1.950 raeburn 2145: # Scalar context: The content of the response.
2146: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2147: #
1.15 www 2148: sub ssi {
2149:
1.944 foxr 2150: my ($fn,%form)=@_;
1.15 www 2151: my $ua=new LWP::UserAgent;
1.23 www 2152: my $request;
1.711 albertel 2153:
2154: $form{'no_update_last_known'}=1;
1.895 albertel 2155: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2156: if (%form) {
1.782 albertel 2157: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2158: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2159: } else {
1.782 albertel 2160: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2161: }
2162:
1.15 www 2163: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2164: my $response=$ua->request($request);
2165:
1.944 foxr 2166: if (wantarray) {
2167: return ($response->content, $response);
2168: } else {
2169: return $response->content;
1.942 foxr 2170: }
1.324 www 2171: }
2172:
2173: sub externalssi {
2174: my ($url)=@_;
2175: my $ua=new LWP::UserAgent;
2176: my $request=new HTTP::Request('GET',$url);
2177: my $response=$ua->request($request);
1.954 raeburn 2178: if (wantarray) {
2179: return ($response->content, $response);
2180: } else {
2181: return $response->content;
2182: }
1.15 www 2183: }
1.254 www 2184:
1.492 albertel 2185: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2186:
2187: sub allowuploaded {
2188: my ($srcurl,$url)=@_;
2189: $url=&clutter(&declutter($url));
2190: my $dir=$url;
2191: $dir=~s/\/[^\/]+$//;
2192: my %httpref=();
2193: my $httpurl=&hreflocation('',$url);
2194: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2195: &Apache::lonnet::appenv(\%httpref);
1.254 www 2196: }
1.477 raeburn 2197:
1.478 albertel 2198: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2199: # input: action, courseID, current domain, intended
1.637 raeburn 2200: # path to file, source of file, instruction to parse file for objects,
2201: # ref to hash for embedded objects,
2202: # ref to hash for codebase of java objects.
2203: #
1.485 raeburn 2204: # output: url to file (if action was uploaddoc),
2205: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2206: #
1.478 albertel 2207: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2208: # course.
1.477 raeburn 2209: #
1.478 albertel 2210: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2211: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2212: # course's home server.
1.477 raeburn 2213: #
1.478 albertel 2214: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2215: # be copied from $source (current location) to
2216: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2217: # and will then be copied to
2218: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2219: # course's home server.
1.485 raeburn 2220: #
1.481 raeburn 2221: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2222: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2223: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2224: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2225: # in course's home server.
1.637 raeburn 2226: #
1.477 raeburn 2227:
2228: sub process_coursefile {
1.638 albertel 2229: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2230: my $fetchresult;
1.638 albertel 2231: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2232: if ($action eq 'propagate') {
1.638 albertel 2233: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2234: $home);
1.481 raeburn 2235: } else {
1.477 raeburn 2236: my $fpath = '';
2237: my $fname = $file;
1.478 albertel 2238: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2239: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2240: my $filepath = &build_filepath($fpath);
1.481 raeburn 2241: if ($action eq 'copy') {
2242: if ($source eq '') {
2243: $fetchresult = 'no source file';
2244: return $fetchresult;
2245: } else {
2246: my $destination = $filepath.'/'.$fname;
2247: rename($source,$destination);
2248: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2249: $home);
1.481 raeburn 2250: }
2251: } elsif ($action eq 'uploaddoc') {
2252: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2253: print $fh $env{'form.'.$source};
1.481 raeburn 2254: close($fh);
1.637 raeburn 2255: if ($parser eq 'parse') {
1.1024 raeburn 2256: my $mm = new File::MMagic;
2257: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2258: if ($mime_type eq 'text/html') {
2259: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2260: unless ($parse_result eq 'ok') {
2261: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2262: }
1.637 raeburn 2263: }
2264: }
1.477 raeburn 2265: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2266: $home);
1.481 raeburn 2267: if ($fetchresult eq 'ok') {
2268: return '/uploaded/'.$fpath.'/'.$fname;
2269: } else {
2270: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2271: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2272: return '/adm/notfound.html';
2273: }
1.477 raeburn 2274: }
2275: }
1.485 raeburn 2276: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2277: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2278: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2279: }
2280: return $fetchresult;
2281: }
2282:
1.637 raeburn 2283: sub build_filepath {
2284: my ($fpath) = @_;
2285: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2286: unless ($fpath eq '') {
2287: my @parts=split('/',$fpath);
2288: foreach my $part (@parts) {
2289: $filepath.= '/'.$part;
2290: if ((-e $filepath)!=1) {
2291: mkdir($filepath,0777);
2292: }
2293: }
2294: }
2295: return $filepath;
2296: }
2297:
2298: sub store_edited_file {
1.638 albertel 2299: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2300: my $file = $primary_url;
2301: $file =~ s#^/uploaded/$docudom/$docuname/##;
2302: my $fpath = '';
2303: my $fname = $file;
2304: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2305: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2306: my $filepath = &build_filepath($fpath);
2307: open(my $fh,'>'.$filepath.'/'.$fname);
2308: print $fh $content;
2309: close($fh);
1.638 albertel 2310: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2311: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2312: $home);
1.637 raeburn 2313: if ($$fetchresult eq 'ok') {
2314: return '/uploaded/'.$fpath.'/'.$fname;
2315: } else {
1.638 albertel 2316: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2317: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2318: return '/adm/notfound.html';
2319: }
2320: }
2321:
1.531 albertel 2322: sub clean_filename {
1.831 albertel 2323: my ($fname,$args)=@_;
1.315 www 2324: # Replace Windows backslashes by forward slashes
1.257 www 2325: $fname=~s/\\/\//g;
1.831 albertel 2326: if (!$args->{'keep_path'}) {
2327: # Get rid of everything but the actual filename
2328: $fname=~s/^.*\/([^\/]+)$/$1/;
2329: }
1.315 www 2330: # Replace spaces by underscores
2331: $fname=~s/\s+/\_/g;
2332: # Replace all other weird characters by nothing
1.831 albertel 2333: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2334: # Replace all .\d. sequences with _\d. so they no longer look like version
2335: # numbers
2336: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2337: return $fname;
2338: }
1.1051 raeburn 2339: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2340: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2341: # image with the same aspect ratio as the original, but with dimensions which do
2342: # not exceed $resizewidth and $resizeheight.
2343:
1.984 neumanie 2344: sub resizeImage {
1.1051 raeburn 2345: my ($img_path,$resizewidth,$resizeheight) = @_;
2346: my $ima = Image::Magick->new;
2347: my $resized;
2348: if (-e $img_path) {
2349: $ima->Read($img_path);
2350: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2351: my $width = $ima->Get('width');
2352: my $height = $ima->Get('height');
2353: if ($width > $resizewidth) {
2354: my $factor = $width/$resizewidth;
2355: my $newheight = $height/$factor;
2356: $ima->Scale(width=>$resizewidth,height=>$newheight);
2357: $resized = 1;
2358: }
2359: }
2360: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2361: my $width = $ima->Get('width');
2362: my $height = $ima->Get('height');
2363: if ($height > $resizeheight) {
2364: my $factor = $height/$resizeheight;
2365: my $newwidth = $width/$factor;
2366: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2367: $resized = 1;
2368: }
2369: }
2370: if ($resized) {
2371: $ima->Write($img_path);
2372: }
2373: }
2374: return;
1.977 amueller 2375: }
2376:
1.608 albertel 2377: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2378: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13 raeburn 2379: # the desired filename is in $env{"form.$formname.filename"}
2380: # $context - possible values: coursedoc, existingfile, overwrite,
2381: # canceloverwrite, or ''.
2382: # if 'coursedoc': upload to the current course
2383: # if 'existingfile': write file to tmp/overwrites directory
2384: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2385: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2386: # $subdir - directory in userfile to store the file into
1.858 raeburn 2387: # $parser - instruction to parse file for objects ($parser = parse)
2388: # $allfiles - reference to hash for embedded objects
2389: # $codebase - reference to hash for codebase of java objects
2390: # $desuname - username for permanent storage of uploaded file
2391: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2392: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2393: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2394: # $resizewidth - width (pixels) to which to resize uploaded image
2395: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2396: #
1.686 albertel 2397: # output: url of file in userspace, or error: <message>
2398: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2399:
1.531 albertel 2400: sub userfileupload {
1.1056.4.13 raeburn 2401: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2402: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2403: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2404: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2405: $fname=&clean_filename($fname);
1.1056.4.13 raeburn 2406: # See if there is anything left
1.257 www 2407: unless ($fname) { return 'error: no uploaded file'; }
1.1056.4.13 raeburn 2408: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2409: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2410: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2411: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2412: my $now = time;
1.1056.4.13 raeburn 2413: my $filepath;
2414: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2415: $filepath = 'tmp/helprequests/'.$now;
2416: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2417: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2418: '_'.$env{'user.domain'}.'/pending';
2419: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2420: my ($docuname,$docudom);
2421: if ($destudom) {
2422: $docudom = $destudom;
2423: } else {
2424: $docudom = $env{'user.domain'};
2425: }
2426: if ($destuname) {
2427: $docuname = $destuname;
2428: } else {
2429: $docuname = $env{'user.name'};
2430: }
2431: if (exists($env{'form.group'})) {
2432: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2433: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2434: }
2435: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2436: if ($context eq 'canceloverwrite') {
2437: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2438: if (-e $tempfile) {
2439: my @info = stat($tempfile);
2440: if ($info[9] eq $env{'form.timestamp'}) {
2441: unlink($tempfile);
2442: }
2443: }
2444: return;
1.523 raeburn 2445: }
2446: }
1.1056.4.13 raeburn 2447: # Create the directory if not present
1.741 raeburn 2448: my @parts=split(/\//,$filepath);
2449: my $fullpath = $perlvar{'lonDaemons'};
2450: for (my $i=0;$i<@parts;$i++) {
2451: $fullpath .= '/'.$parts[$i];
2452: if ((-e $fullpath)!=1) {
2453: mkdir($fullpath,0777);
2454: }
2455: }
2456: open(my $fh,'>'.$fullpath.'/'.$fname);
2457: print $fh $env{'form.'.$formname};
2458: close($fh);
1.1056.4.13 raeburn 2459: if ($context eq 'existingfile') {
2460: my @info = stat($fullpath.'/'.$fname);
2461: return ($fullpath.'/'.$fname,$info[9]);
2462: } else {
2463: return $fullpath.'/'.$fname;
2464: }
1.523 raeburn 2465: }
1.995 raeburn 2466: if ($subdir eq 'scantron') {
2467: $fname = 'scantron_orig_'.$fname;
1.1056.4.14 raeburn 2468: } else {
1.995 raeburn 2469: $fname="$subdir/$fname";
2470: }
1.1056.4.13 raeburn 2471: if ($context eq 'coursedoc') {
1.638 albertel 2472: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2473: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2474: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2475: return &finishuserfileupload($docuname,$docudom,
2476: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2477: $codebase,$thumbwidth,$thumbheight,
1.1056.4.13 raeburn 2478: $resizewidth,$resizeheight,$context);
1.481 raeburn 2479: } else {
1.620 albertel 2480: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2481: return &process_coursefile('uploaddoc',$docuname,$docudom,
2482: $fname,$formname,$parser,
2483: $allfiles,$codebase);
1.481 raeburn 2484: }
1.719 banghart 2485: } elsif (defined($destuname)) {
2486: my $docuname=$destuname;
2487: my $docudom=$destudom;
1.860 raeburn 2488: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2489: $parser,$allfiles,$codebase,
1.1051 raeburn 2490: $thumbwidth,$thumbheight,
1.1056.4.13 raeburn 2491: $resizewidth,$resizeheight,$context);
1.259 www 2492: } else {
1.638 albertel 2493: my $docuname=$env{'user.name'};
2494: my $docudom=$env{'user.domain'};
1.714 raeburn 2495: if (exists($env{'form.group'})) {
2496: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2497: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2498: }
1.860 raeburn 2499: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2500: $parser,$allfiles,$codebase,
1.1051 raeburn 2501: $thumbwidth,$thumbheight,
1.1056.4.13 raeburn 2502: $resizewidth,$resizeheight,$context);
1.259 www 2503: }
1.271 www 2504: }
2505:
2506: sub finishuserfileupload {
1.860 raeburn 2507: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.13 raeburn 2508: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context) = @_;
1.477 raeburn 2509: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2510: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2511:
1.860 raeburn 2512: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2513: $file=$fname;
2514: if ($fname=~m|/|) {
2515: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2516: $path.=$fnamepath.'/';
2517: }
1.259 www 2518: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2519: my $count;
2520: for ($count=4;$count<=$#parts;$count++) {
2521: $filepath.="/$parts[$count]";
2522: if ((-e $filepath)!=1) {
2523: mkdir($filepath,0777);
2524: }
2525: }
1.984 neumanie 2526:
1.258 www 2527: # Save the file
2528: {
1.701 albertel 2529: if (!open(FH,'>'.$filepath.'/'.$file)) {
2530: &logthis('Failed to create '.$filepath.'/'.$file);
2531: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2532: return '/adm/notfound.html';
2533: }
1.1056.4.13 raeburn 2534: if ($context eq 'overwrite') {
2535: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2536: my $target = $filepath.'/'.$file;
2537: if (-e $source) {
2538: my @info = stat($source);
2539: if ($info[9] eq $env{'form.timestamp'}) {
2540: unless (&File::Copy::move($source,$target)) {
2541: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2542: return "Moving from $source failed";
2543: }
2544: } else {
2545: return "Temporary file: $source had unexpected date/time for last modification";
2546: }
2547: } else {
2548: return "Temporary file: $source missing";
2549: }
2550: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2551: &logthis('Failed to write to '.$filepath.'/'.$file);
2552: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2553: return '/adm/notfound.html';
2554: }
1.570 albertel 2555: close(FH);
1.1051 raeburn 2556: if ($resizewidth && $resizeheight) {
2557: my $mm = new File::MMagic;
2558: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2559: if ($mime_type =~ m{^image/}) {
2560: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2561: }
1.977 amueller 2562: }
1.258 www 2563: }
1.637 raeburn 2564: if ($parser eq 'parse') {
1.1024 raeburn 2565: my $mm = new File::MMagic;
2566: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2567: if ($mime_type eq 'text/html') {
2568: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2569: $allfiles,$codebase);
2570: unless ($parse_result eq 'ok') {
2571: &logthis('Failed to parse '.$filepath.$file.
2572: ' for embedded media: '.$parse_result);
2573: }
1.637 raeburn 2574: }
2575: }
1.860 raeburn 2576: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2577: my $input = $filepath.'/'.$file;
2578: my $output = $filepath.'/'.'tn-'.$file;
2579: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2580: system("convert -sample $thumbsize $input $output");
2581: if (-e $filepath.'/'.'tn-'.$file) {
2582: $fetchthumb = 1;
2583: }
2584: }
1.858 raeburn 2585:
1.259 www 2586: # Notify homeserver to grep it
2587: #
1.984 neumanie 2588: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2589: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2590: if ($fetchresult eq 'ok') {
1.860 raeburn 2591: if ($fetchthumb) {
2592: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2593: if ($thumbresult ne 'ok') {
2594: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2595: $docuhome.': '.$thumbresult);
2596: }
2597: }
1.259 www 2598: #
1.258 www 2599: # Return the URL to it
1.494 albertel 2600: return '/uploaded/'.$path.$file;
1.263 www 2601: } else {
1.494 albertel 2602: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2603: ': '.$fetchresult);
1.263 www 2604: return '/adm/notfound.html';
1.858 raeburn 2605: }
1.493 albertel 2606: }
2607:
1.637 raeburn 2608: sub extract_embedded_items {
1.961 raeburn 2609: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2610: my @state = ();
2611: my %javafiles = (
2612: codebase => '',
2613: code => '',
2614: archive => ''
2615: );
2616: my %mediafiles = (
2617: src => '',
2618: movie => '',
2619: );
1.648 raeburn 2620: my $p;
2621: if ($content) {
2622: $p = HTML::LCParser->new($content);
2623: } else {
1.961 raeburn 2624: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2625: }
1.641 albertel 2626: while (my $t=$p->get_token()) {
1.640 albertel 2627: if ($t->[0] eq 'S') {
2628: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2629: push(@state, $tagname);
1.648 raeburn 2630: if (lc($tagname) eq 'allow') {
2631: &add_filetype($allfiles,$attr->{'src'},'src');
2632: }
1.640 albertel 2633: if (lc($tagname) eq 'img') {
2634: &add_filetype($allfiles,$attr->{'src'},'src');
2635: }
1.886 albertel 2636: if (lc($tagname) eq 'a') {
2637: &add_filetype($allfiles,$attr->{'href'},'href');
2638: }
1.645 raeburn 2639: if (lc($tagname) eq 'script') {
2640: if ($attr->{'archive'} =~ /\.jar$/i) {
2641: &add_filetype($allfiles,$attr->{'archive'},'archive');
2642: } else {
2643: &add_filetype($allfiles,$attr->{'src'},'src');
2644: }
2645: }
2646: if (lc($tagname) eq 'link') {
2647: if (lc($attr->{'rel'}) eq 'stylesheet') {
2648: &add_filetype($allfiles,$attr->{'href'},'href');
2649: }
2650: }
1.640 albertel 2651: if (lc($tagname) eq 'object' ||
2652: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2653: foreach my $item (keys(%javafiles)) {
2654: $javafiles{$item} = '';
2655: }
2656: }
2657: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2658: my $name = lc($attr->{'name'});
2659: foreach my $item (keys(%javafiles)) {
2660: if ($name eq $item) {
2661: $javafiles{$item} = $attr->{'value'};
2662: last;
2663: }
2664: }
2665: foreach my $item (keys(%mediafiles)) {
2666: if ($name eq $item) {
2667: &add_filetype($allfiles, $attr->{'value'}, 'value');
2668: last;
2669: }
2670: }
2671: }
2672: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2673: foreach my $item (keys(%javafiles)) {
2674: if ($attr->{$item}) {
2675: $javafiles{$item} = $attr->{$item};
2676: last;
2677: }
2678: }
2679: foreach my $item (keys(%mediafiles)) {
2680: if ($attr->{$item}) {
2681: &add_filetype($allfiles,$attr->{$item},$item);
2682: last;
2683: }
2684: }
2685: }
2686: } elsif ($t->[0] eq 'E') {
2687: my ($tagname) = ($t->[1]);
2688: if ($javafiles{'codebase'} ne '') {
2689: $javafiles{'codebase'} .= '/';
2690: }
2691: if (lc($tagname) eq 'applet' ||
2692: lc($tagname) eq 'object' ||
2693: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2694: ) {
2695: foreach my $item (keys(%javafiles)) {
2696: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2697: my $file=$javafiles{'codebase'}.$javafiles{$item};
2698: &add_filetype($allfiles,$file,$item);
2699: }
2700: }
2701: }
2702: pop @state;
2703: }
2704: }
1.637 raeburn 2705: return 'ok';
2706: }
2707:
1.639 albertel 2708: sub add_filetype {
2709: my ($allfiles,$file,$type)=@_;
2710: if (exists($allfiles->{$file})) {
2711: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2712: push(@{$allfiles->{$file}}, &escape($type));
2713: }
2714: } else {
2715: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2716: }
2717: }
2718:
1.493 albertel 2719: sub removeuploadedurl {
1.984 neumanie 2720: my ($url)=@_;
2721: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2722: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2723: }
2724:
2725: sub removeuserfile {
2726: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2727: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2728: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2729: if ($result eq 'ok') {
1.798 raeburn 2730: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2731: my $metafile = $fname.'.meta';
2732: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2733: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2734: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2735: my $sqlresult =
1.823 albertel 2736: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2737: 'portfolio_metadata',$group,
2738: 'delete');
1.798 raeburn 2739: }
2740: }
2741: return $result;
1.257 www 2742: }
1.15 www 2743:
1.530 albertel 2744: sub mkdiruserfile {
2745: my ($docuname,$docudom,$dir)=@_;
2746: my $home=&homeserver($docuname,$docudom);
2747: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2748: }
2749:
1.531 albertel 2750: sub renameuserfile {
2751: my ($docuname,$docudom,$old,$new)=@_;
2752: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2753: my $result = &reply("renameuserfile:$docudom:$docuname:".
2754: &escape("$old").':'.&escape("$new"),$home);
2755: if ($result eq 'ok') {
2756: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2757: my $oldmeta = $old.'.meta';
2758: my $newmeta = $new.'.meta';
2759: my $metaresult =
2760: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2761: my $url = "/uploaded/$docudom/$docuname/$old";
2762: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2763: my $sqlresult =
1.823 albertel 2764: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2765: 'portfolio_metadata',$group,
2766: 'delete');
1.798 raeburn 2767: }
2768: }
2769: return $result;
1.531 albertel 2770: }
2771:
1.14 www 2772: # ------------------------------------------------------------------------- Log
2773:
2774: sub log {
2775: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2776: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2777: }
2778:
2779: # ------------------------------------------------------------------ Course Log
1.352 www 2780: #
2781: # This routine flushes several buffers of non-mission-critical nature
2782: #
1.157 www 2783:
2784: sub flushcourselogs {
1.352 www 2785: &logthis('Flushing log buffers');
2786: #
2787: # course logs
2788: # This is a log of all transactions in a course, which can be used
2789: # for data mining purposes
2790: #
2791: # It also collects the courseid database, which lists last transaction
2792: # times and course titles for all courseids
2793: #
2794: my %courseidbuffer=();
1.921 raeburn 2795: foreach my $crsid (keys(%courselogs)) {
1.352 www 2796: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2797: &escape($courselogs{$crsid}),
2798: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2799: delete $courselogs{$crsid};
2800: } else {
2801: &logthis('Failed to flush log buffer for '.$crsid);
2802: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2803: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2804: " exceeded maximum size, deleting.</font>");
2805: delete $courselogs{$crsid};
2806: }
1.352 www 2807: }
1.920 raeburn 2808: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2809: 'description' => $coursedescrbuf{$crsid},
2810: 'inst_code' => $courseinstcodebuf{$crsid},
2811: 'type' => $coursetypebuf{$crsid},
2812: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2813: };
1.191 harris41 2814: }
1.352 www 2815: #
2816: # Write course id database (reverse lookup) to homeserver of courses
2817: # Is used in pickcourse
2818: #
1.840 albertel 2819: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2820: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2821: $courseidbuffer{$crs_home},
2822: $crs_home,'timeonly');
1.352 www 2823: }
2824: #
2825: # File accesses
2826: # Writes to the dynamic metadata of resources to get hit counts, etc.
2827: #
1.449 matthew 2828: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2829: if ($entry =~ /___count$/) {
2830: my ($dom,$name);
1.807 albertel 2831: ($dom,$name,undef)=
1.811 albertel 2832: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2833: if (! defined($dom) || $dom eq '' ||
2834: ! defined($name) || $name eq '') {
1.620 albertel 2835: my $cid = $env{'request.course.id'};
2836: $dom = $env{'request.'.$cid.'.domain'};
2837: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2838: }
1.450 matthew 2839: my $value = $accesshash{$entry};
2840: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2841: my %temphash=($url => $value);
1.449 matthew 2842: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2843: if ($result eq 'ok') {
2844: delete $accesshash{$entry};
2845: } elsif ($result eq 'unknown_cmd') {
2846: # Target server has old code running on it.
1.450 matthew 2847: my %temphash=($entry => $value);
1.449 matthew 2848: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2849: delete $accesshash{$entry};
2850: }
2851: }
2852: } else {
1.811 albertel 2853: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2854: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2855: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2856: delete $accesshash{$entry};
2857: }
1.185 www 2858: }
1.191 harris41 2859: }
1.352 www 2860: #
2861: # Roles
2862: # Reverse lookup of user roles for course faculty/staff and co-authorship
2863: #
1.800 albertel 2864: foreach my $entry (keys(%userrolehash)) {
1.351 www 2865: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2866: split(/\:/,$entry);
2867: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2868: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2869: $rudom,$runame) eq 'ok') {
2870: delete $userrolehash{$entry};
2871: }
2872: }
1.662 raeburn 2873: #
2874: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2875: #
2876: my %domrolebuffer = ();
1.1000 raeburn 2877: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2878: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2879: if ($domrolebuffer{$rudom}) {
2880: $domrolebuffer{$rudom}.='&'.&escape($entry).
2881: '='.&escape($domainrolehash{$entry});
2882: } else {
2883: $domrolebuffer{$rudom}.=&escape($entry).
2884: '='.&escape($domainrolehash{$entry});
2885: }
2886: delete $domainrolehash{$entry};
2887: }
2888: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2889: my %servers = &get_servers($dom,'library');
2890: foreach my $tryserver (keys(%servers)) {
2891: unless (&reply('domroleput:'.$dom.':'.
2892: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2893: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2894: }
1.662 raeburn 2895: }
2896: }
1.186 www 2897: $dumpcount++;
1.157 www 2898: }
2899:
2900: sub courselog {
2901: my $what=shift;
1.158 www 2902: $what=time.':'.$what;
1.620 albertel 2903: unless ($env{'request.course.id'}) { return ''; }
2904: $coursedombuf{$env{'request.course.id'}}=
2905: $env{'course.'.$env{'request.course.id'}.'.domain'};
2906: $coursenumbuf{$env{'request.course.id'}}=
2907: $env{'course.'.$env{'request.course.id'}.'.num'};
2908: $coursehombuf{$env{'request.course.id'}}=
2909: $env{'course.'.$env{'request.course.id'}.'.home'};
2910: $coursedescrbuf{$env{'request.course.id'}}=
2911: $env{'course.'.$env{'request.course.id'}.'.description'};
2912: $courseinstcodebuf{$env{'request.course.id'}}=
2913: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2914: $courseownerbuf{$env{'request.course.id'}}=
2915: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2916: $coursetypebuf{$env{'request.course.id'}}=
2917: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2918: if (defined $courselogs{$env{'request.course.id'}}) {
2919: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2920: } else {
1.620 albertel 2921: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2922: }
1.620 albertel 2923: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2924: &flushcourselogs();
2925: }
1.158 www 2926: }
2927:
2928: sub courseacclog {
2929: my $fnsymb=shift;
1.620 albertel 2930: unless ($env{'request.course.id'}) { return ''; }
2931: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2932: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2933: $what.=':POST';
1.583 matthew 2934: # FIXME: Probably ought to escape things....
1.800 albertel 2935: foreach my $key (keys(%env)) {
2936: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2937: my $formitem = $1;
2938: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2939: $what.=':'.$formitem.'='.$env{$key};
2940: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2941: $what.=':'.$formitem.'='.$env{$key};
2942: }
1.158 www 2943: }
1.191 harris41 2944: }
1.583 matthew 2945: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2946: # FIXME: We should not be depending on a form parameter that someone
2947: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2948: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2949: $what.= ':POST';
2950: # FIXME: Probably ought to escape things....
2951: foreach my $element ('courseexp','crsfulltext','crsrelated',
2952: 'crsdiscuss') {
1.620 albertel 2953: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2954: }
2955: }
1.158 www 2956: }
2957: &courselog($what);
1.149 www 2958: }
2959:
1.185 www 2960: sub countacc {
2961: my $url=&declutter(shift);
1.458 matthew 2962: return if (! defined($url) || $url eq '');
1.620 albertel 2963: unless ($env{'request.course.id'}) { return ''; }
2964: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2965: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2966: $accesshash{$key}++;
1.185 www 2967: }
1.349 www 2968:
1.361 www 2969: sub linklog {
2970: my ($from,$to)=@_;
2971: $from=&declutter($from);
2972: $to=&declutter($to);
2973: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2974: $accesshash{$to.'___'.$from.'___goto'}=1;
2975: }
2976:
1.349 www 2977: sub userrolelog {
2978: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2979: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2980: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2981: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2982: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2983: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2984: $userrolehash
2985: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2986: =$tend.':'.$tstart;
1.662 raeburn 2987: }
1.898 albertel 2988: if (($env{'request.role'} =~ /dc\./) &&
2989: (($trole=~/^au/) || ($trole=~/^in/) ||
2990: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2991: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2992: ($trole=~/^co/))) {
1.898 albertel 2993: $userrolehash
2994: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2995: =$tend.':'.$tstart;
2996: }
1.662 raeburn 2997: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2998: ($trole=~/^li/) || ($trole=~/^li/) ||
2999: ($trole=~/^au/) || ($trole=~/^dg/) ||
3000: ($trole=~/^sc/)) {
3001: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3002: $domainrolehash
3003: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3004: = $tend.':'.$tstart;
3005: }
1.351 www 3006: }
3007:
1.957 raeburn 3008: sub courserolelog {
3009: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3010: if (($trole eq 'cc') || ($trole eq 'in') ||
3011: ($trole eq 'ep') || ($trole eq 'ad') ||
3012: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3013: ($trole=~/^cr/) || ($trole eq 'gr') ||
3014: ($trole eq 'co')) {
1.957 raeburn 3015: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3016: my $cdom = $1;
3017: my $cnum = $2;
3018: my $sec = $3;
3019: my $namespace = 'rolelog';
3020: my %storehash = (
3021: role => $trole,
3022: start => $tstart,
3023: end => $tend,
3024: selfenroll => $selfenroll,
3025: context => $context,
3026: );
3027: if ($trole eq 'gr') {
3028: $namespace = 'groupslog';
3029: $storehash{'group'} = $sec;
3030: } else {
3031: $storehash{'section'} = $sec;
3032: }
3033: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3034: if (($trole ne 'st') || ($sec ne '')) {
3035: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3036: }
1.957 raeburn 3037: }
3038: }
3039: return;
3040: }
3041:
1.351 www 3042: sub get_course_adv_roles {
1.948 raeburn 3043: my ($cid,$codes) = @_;
1.620 albertel 3044: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3045: my %coursehash=&coursedescription($cid);
1.988 raeburn 3046: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3047: my %nothide=();
1.800 albertel 3048: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3049: if ($user !~ /:/) {
3050: $nothide{join(':',split(/[\@]/,$user))}=1;
3051: } else {
3052: $nothide{$user}=1;
3053: }
1.470 www 3054: }
1.351 www 3055: my %returnhash=();
3056: my %dumphash=
3057: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3058: my $now=time;
1.997 raeburn 3059: my %privileged;
1.1000 raeburn 3060: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3061: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3062: if (($tstart) && ($tstart<0)) { next; }
3063: if (($tend) && ($tend<$now)) { next; }
3064: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3065: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3066: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3067: unless (ref($privileged{$domain}) eq 'HASH') {
3068: my %dompersonnel =
1.998 raeburn 3069: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3070: $privileged{$domain} = {};
3071: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3072: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3073: foreach my $user (keys(%{$dompersonnel{$server}})) {
3074: my ($trole,$uname,$udom) = split(/:/,$user);
3075: $privileged{$udom}{$uname} = 1;
3076: }
3077: }
3078: }
3079: }
3080: if ((exists($privileged{$domain}{$username})) &&
3081: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3082: if ($role eq 'cr') { next; }
1.948 raeburn 3083: if ($codes) {
3084: if ($section) { $role .= ':'.$section; }
3085: if ($returnhash{$role}) {
3086: $returnhash{$role}.=','.$username.':'.$domain;
3087: } else {
3088: $returnhash{$role}=$username.':'.$domain;
3089: }
1.351 www 3090: } else {
1.988 raeburn 3091: my $key=&plaintext($role,$crstype);
1.973 bisitz 3092: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3093: if ($returnhash{$key}) {
3094: $returnhash{$key}.=','.$username.':'.$domain;
3095: } else {
3096: $returnhash{$key}=$username.':'.$domain;
3097: }
1.351 www 3098: }
1.948 raeburn 3099: }
1.400 www 3100: return %returnhash;
3101: }
3102:
3103: sub get_my_roles {
1.937 raeburn 3104: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3105: unless (defined($uname)) { $uname=$env{'user.name'}; }
3106: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3107: my (%dumphash,%nothide);
1.858 raeburn 3108: if ($context eq 'userroles') {
1.1056.4.10 raeburn 3109: my $extra = &freeze_escape({'skipcheck' => 1});
3110: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3111: } else {
3112: %dumphash=
1.400 www 3113: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3114: if ($hidepriv) {
3115: my %coursehash=&coursedescription($udom.'_'.$uname);
3116: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3117: if ($user !~ /:/) {
3118: $nothide{join(':',split(/[\@]/,$user))} = 1;
3119: } else {
3120: $nothide{$user} = 1;
3121: }
3122: }
3123: }
1.858 raeburn 3124: }
1.400 www 3125: my %returnhash=();
3126: my $now=time;
1.999 raeburn 3127: my %privileged;
1.800 albertel 3128: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3129: my ($role,$tend,$tstart);
3130: if ($context eq 'userroles') {
3131: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3132: } else {
3133: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3134: }
1.400 www 3135: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3136: my $status = 'active';
1.939 raeburn 3137: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3138: $status = 'previous';
3139: }
3140: if (($tstart) && ($now<$tstart)) {
3141: $status = 'future';
3142: }
3143: if (ref($types) eq 'ARRAY') {
3144: if (!grep(/^\Q$status\E$/,@{$types})) {
3145: next;
3146: }
3147: } else {
3148: if ($status ne 'active') {
3149: next;
3150: }
3151: }
1.867 raeburn 3152: my ($rolecode,$username,$domain,$section,$area);
3153: if ($context eq 'userroles') {
3154: ($area,$rolecode) = split(/_/,$entry);
3155: (undef,$domain,$username,$section) = split(/\//,$area);
3156: } else {
3157: ($role,$username,$domain,$section) = split(/\:/,$entry);
3158: }
1.832 raeburn 3159: if (ref($roledoms) eq 'ARRAY') {
3160: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3161: next;
3162: }
3163: }
3164: if (ref($roles) eq 'ARRAY') {
3165: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3166: if ($role =~ /^cr\//) {
3167: if (!grep(/^cr$/,@{$roles})) {
3168: next;
3169: }
3170: } else {
3171: next;
3172: }
1.832 raeburn 3173: }
1.867 raeburn 3174: }
1.937 raeburn 3175: if ($hidepriv) {
1.999 raeburn 3176: if ($context eq 'userroles') {
3177: if ((&privileged($username,$domain)) &&
3178: (!$nothide{$username.':'.$domain})) {
3179: next;
3180: }
3181: } else {
3182: unless (ref($privileged{$domain}) eq 'HASH') {
3183: my %dompersonnel =
3184: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3185: $privileged{$domain} = {};
3186: if (keys(%dompersonnel)) {
3187: foreach my $server (keys(%dompersonnel)) {
3188: if (ref($dompersonnel{$server}) eq 'HASH') {
3189: foreach my $user (keys(%{$dompersonnel{$server}})) {
3190: my ($trole,$uname,$udom) = split(/:/,$user);
3191: $privileged{$udom}{$uname} = $trole;
3192: }
3193: }
3194: }
3195: }
3196: }
3197: if (exists($privileged{$domain}{$username})) {
3198: if (!$nothide{$username.':'.$domain}) {
3199: next;
3200: }
3201: }
1.937 raeburn 3202: }
3203: }
1.933 raeburn 3204: if ($withsec) {
3205: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3206: $tstart.':'.$tend;
3207: } else {
3208: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3209: }
1.832 raeburn 3210: }
1.373 www 3211: return %returnhash;
1.399 www 3212: }
3213:
3214: # ----------------------------------------------------- Frontpage Announcements
3215: #
3216: #
3217:
3218: sub postannounce {
3219: my ($server,$text)=@_;
1.844 albertel 3220: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3221: unless ($text=~/\w/) { $text=''; }
3222: return &reply('setannounce:'.&escape($text),$server);
3223: }
3224:
3225: sub getannounce {
1.448 albertel 3226:
3227: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3228: my $announcement='';
1.800 albertel 3229: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3230: close($fh);
1.399 www 3231: if ($announcement=~/\w/) {
3232: return
3233: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3234: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3235: } else {
3236: return '';
3237: }
3238: } else {
3239: return '';
3240: }
1.351 www 3241: }
1.353 www 3242:
3243: # ---------------------------------------------------------- Course ID routines
3244: # Deal with domain's nohist_courseid.db files
3245: #
3246:
3247: sub courseidput {
1.921 raeburn 3248: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3249: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3250: my $outcome;
3251: if ($caller eq 'timeonly') {
3252: my $cids = '';
3253: foreach my $item (keys(%$storehash)) {
3254: $cids.=&escape($item).'&';
3255: }
3256: $cids=~s/\&$//;
3257: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3258: $coursehome);
3259: } else {
3260: my $items = '';
3261: foreach my $item (keys(%$storehash)) {
3262: $items.= &escape($item).'='.
3263: &freeze_escape($$storehash{$item}).'&';
3264: }
3265: $items=~s/\&$//;
3266: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3267: $coursehome);
1.918 raeburn 3268: }
3269: if ($outcome eq 'unknown_cmd') {
3270: my $what;
3271: foreach my $cid (keys(%$storehash)) {
3272: $what .= &escape($cid).'=';
1.921 raeburn 3273: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3274: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3275: }
3276: $what =~ s/\:$/&/;
3277: }
3278: $what =~ s/\&$//;
3279: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3280: } else {
3281: return $outcome;
3282: }
1.353 www 3283: }
3284:
3285: sub courseiddump {
1.921 raeburn 3286: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3287: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3288: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3 raeburn 3289: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3290: my $as_hash = 1;
3291: my %returnhash;
3292: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3293: my %libserv = &all_library();
3294: foreach my $tryserver (keys(%libserv)) {
3295: if ( ( $hostidflag == 1
3296: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3297: || (!defined($hostidflag)) ) {
3298:
1.918 raeburn 3299: if (($domfilter eq '') ||
3300: (&host_domain($tryserver) eq $domfilter)) {
3301: my $rep =
3302: &reply('courseiddump:'.&host_domain($tryserver).':'.
3303: $sincefilter.':'.&escape($descfilter).':'.
3304: &escape($instcodefilter).':'.&escape($ownerfilter).
3305: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3306: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3307: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3308: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3309: &escape($cc_clone).':'.$cloneonly.':'.
3310: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3 raeburn 3311: &escape($creationcontext).':'.$domcloner,
3312: $tryserver);
1.918 raeburn 3313: my @pairs=split(/\&/,$rep);
3314: foreach my $item (@pairs) {
3315: my ($key,$value)=split(/\=/,$item,2);
3316: $key = &unescape($key);
3317: next if ($key =~ /^error: 2 /);
3318: my $result = &thaw_unescape($value);
3319: if (ref($result) eq 'HASH') {
3320: $returnhash{$key}=$result;
3321: } else {
1.921 raeburn 3322: my @responses = split(/:/,$value);
3323: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3324: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3325: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3326: }
1.1008 raeburn 3327: }
1.353 www 3328: }
3329: }
3330: }
3331: }
3332: return %returnhash;
3333: }
3334:
1.1055 raeburn 3335: sub courselastaccess {
3336: my ($cdom,$cnum,$hostidref) = @_;
3337: my %returnhash;
3338: if ($cdom && $cnum) {
3339: my $chome = &homeserver($cnum,$cdom);
3340: if ($chome ne 'no_host') {
3341: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3342: &extract_lastaccess(\%returnhash,$rep);
3343: }
3344: } else {
3345: if (!$cdom) { $cdom=''; }
3346: my %libserv = &all_library();
3347: foreach my $tryserver (keys(%libserv)) {
3348: if (ref($hostidref) eq 'ARRAY') {
3349: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3350: }
3351: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3352: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3353: &extract_lastaccess(\%returnhash,$rep);
3354: }
3355: }
3356: }
3357: return %returnhash;
3358: }
3359:
3360: sub extract_lastaccess {
3361: my ($returnhash,$rep) = @_;
3362: if (ref($returnhash) eq 'HASH') {
3363: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3364: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3365: $rep eq '') {
3366: my @pairs=split(/\&/,$rep);
3367: foreach my $item (@pairs) {
3368: my ($key,$value)=split(/\=/,$item,2);
3369: $key = &unescape($key);
3370: next if ($key =~ /^error: 2 /);
3371: $returnhash->{$key} = &thaw_unescape($value);
3372: }
3373: }
3374: }
3375: return;
3376: }
3377:
1.658 raeburn 3378: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3379:
3380: sub dcmailput {
1.685 raeburn 3381: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3382: my $status = &Apache::lonnet::critical(
1.740 www 3383: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3384: &escape($message),$server);
1.662 raeburn 3385: return $status;
3386: }
3387:
1.658 raeburn 3388: sub dcmaildump {
3389: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3390: my %returnhash=();
1.846 albertel 3391:
3392: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3393: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3394: &escape($enddate).':';
3395: my @esc_senders=map { &escape($_)} @$senders;
3396: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3397: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3398: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3399: if (($key) && ($value)) {
3400: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3401: }
3402: }
3403: }
3404: return %returnhash;
3405: }
1.662 raeburn 3406: # ---------------------------------------------------------- Domain roles
3407:
3408: sub get_domain_roles {
3409: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3410: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3411: $startdate = '.';
3412: }
1.1018 raeburn 3413: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3414: $enddate = '.';
3415: }
1.922 raeburn 3416: my $rolelist;
3417: if (ref($roles) eq 'ARRAY') {
3418: $rolelist = join(':',@{$roles});
3419: }
1.662 raeburn 3420: my %personnel = ();
1.841 albertel 3421:
3422: my %servers = &get_servers($dom,'library');
3423: foreach my $tryserver (keys(%servers)) {
3424: %{$personnel{$tryserver}}=();
3425: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3426: &escape($startdate).':'.
3427: &escape($enddate).':'.
3428: &escape($rolelist), $tryserver))) {
3429: my ($key,$value) = split(/\=/,$line,2);
3430: if (($key) && ($value)) {
3431: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3432: }
3433: }
1.662 raeburn 3434: }
3435: return %personnel;
3436: }
1.658 raeburn 3437:
1.149 www 3438: # ----------------------------------------------------------- Check out an item
3439:
1.504 albertel 3440: sub get_first_access {
3441: my ($type,$argsymb)=@_;
1.790 albertel 3442: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3443: if ($argsymb) { $symb=$argsymb; }
3444: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3445: if ($type eq 'course') {
3446: $res='course';
3447: } elsif ($type eq 'map') {
1.588 albertel 3448: $res=&symbread($map);
3449: } else {
3450: $res=$symb;
3451: }
3452: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3453: return $times{"$courseid\0$res"};
1.504 albertel 3454: }
3455:
3456: sub set_first_access {
3457: my ($type)=@_;
1.790 albertel 3458: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3459: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3460: if ($type eq 'course') {
3461: $res='course';
3462: } elsif ($type eq 'map') {
1.588 albertel 3463: $res=&symbread($map);
3464: } else {
3465: $res=$symb;
3466: }
3467: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3468: if (!$firstaccess) {
1.588 albertel 3469: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3470: }
3471: return 'already_set';
1.504 albertel 3472: }
3473:
1.149 www 3474: sub checkout {
3475: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3476: my $now=time;
3477: my $lonhost=$perlvar{'lonHostID'};
3478: my $infostr=&escape(
1.234 www 3479: 'CHECKOUTTOKEN&'.
1.149 www 3480: $tuname.'&'.
3481: $tudom.'&'.
3482: $tcrsid.'&'.
3483: $symb.'&'.
3484: $now.'&'.$ENV{'REMOTE_ADDR'});
3485: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3486: if ($token=~/^error\:/) {
1.672 albertel 3487: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3488: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3489: "</font>");
3490: return '';
3491: }
3492:
1.149 www 3493: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3494: $token=~tr/a-z/A-Z/;
3495:
1.153 www 3496: my %infohash=('resource.0.outtoken' => $token,
3497: 'resource.0.checkouttime' => $now,
3498: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3499:
3500: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3501: return '';
1.151 www 3502: } else {
1.672 albertel 3503: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3504: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3505: "</font>");
1.149 www 3506: }
3507:
3508: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3509: &escape('Checkout '.$infostr.' - '.
3510: $token)) ne 'ok') {
3511: return '';
1.151 www 3512: } else {
1.672 albertel 3513: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3514: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3515: "</font>");
1.149 www 3516: }
1.151 www 3517: return $token;
1.149 www 3518: }
3519:
3520: # ------------------------------------------------------------ Check in an item
3521:
3522: sub checkin {
3523: my $token=shift;
1.150 www 3524: my $now=time;
3525: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3526: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3527: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3528: $dtoken=~s/\W/\_/g;
1.234 www 3529: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3530: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3531:
1.154 www 3532: unless (($tuname) && ($tudom)) {
3533: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3534: return '';
3535: }
3536:
3537: unless (&allowed('mgr',$tcrsid)) {
3538: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3539: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3540: return '';
3541: }
3542:
1.153 www 3543: my %infohash=('resource.0.intoken' => $token,
3544: 'resource.0.checkintime' => $now,
3545: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3546:
3547: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3548: return '';
3549: }
3550:
3551: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3552: &escape('Checkin - '.$token)) ne 'ok') {
3553: return '';
3554: }
3555:
3556: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3557: }
3558:
3559: # --------------------------------------------- Set Expire Date for Spreadsheet
3560:
3561: sub expirespread {
3562: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3563: my $cid=$env{'request.course.id'};
1.110 www 3564: if ($cid) {
3565: my $now=time;
3566: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3567: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3568: $env{'course.'.$cid.'.num'}.
1.110 www 3569: ':nohist_expirationdates:'.
3570: &escape($key).'='.$now,
1.620 albertel 3571: $env{'course.'.$cid.'.home'})
1.110 www 3572: }
3573: return 'ok';
1.14 www 3574: }
3575:
1.109 www 3576: # ----------------------------------------------------- Devalidate Spreadsheets
3577:
3578: sub devalidate {
1.325 www 3579: my ($symb,$uname,$udom)=@_;
1.620 albertel 3580: my $cid=$env{'request.course.id'};
1.109 www 3581: if ($cid) {
1.391 matthew 3582: # delete the stored spreadsheets for
3583: # - the student level sheet of this user in course's homespace
3584: # - the assessment level sheet for this resource
3585: # for this user in user's homespace
1.553 albertel 3586: # - current conditional state info
1.325 www 3587: my $key=$uname.':'.$udom.':';
1.109 www 3588: my $status=
1.299 matthew 3589: &del('nohist_calculatedsheets',
1.391 matthew 3590: [$key.'studentcalc:'],
1.620 albertel 3591: $env{'course.'.$cid.'.domain'},
3592: $env{'course.'.$cid.'.num'})
1.133 albertel 3593: .' '.
3594: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3595: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3596: unless ($status eq 'ok ok') {
3597: &logthis('Could not devalidate spreadsheet '.
1.325 www 3598: $uname.' at '.$udom.' for '.
1.109 www 3599: $symb.': '.$status);
1.133 albertel 3600: }
1.553 albertel 3601: &delenv('user.state.'.$cid);
1.109 www 3602: }
3603: }
3604:
1.265 albertel 3605: sub get_scalar {
3606: my ($string,$end) = @_;
3607: my $value;
3608: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3609: $value = $1;
3610: } elsif ($$string =~ s/^([^&]*?)&//) {
3611: $value = $1;
3612: }
3613: return &unescape($value);
3614: }
3615:
3616: sub array2str {
3617: my (@array) = @_;
3618: my $result=&arrayref2str(\@array);
3619: $result=~s/^__ARRAY_REF__//;
3620: $result=~s/__END_ARRAY_REF__$//;
3621: return $result;
3622: }
3623:
1.204 albertel 3624: sub arrayref2str {
3625: my ($arrayref) = @_;
1.265 albertel 3626: my $result='__ARRAY_REF__';
1.204 albertel 3627: foreach my $elem (@$arrayref) {
1.265 albertel 3628: if(ref($elem) eq 'ARRAY') {
3629: $result.=&arrayref2str($elem).'&';
3630: } elsif(ref($elem) eq 'HASH') {
3631: $result.=&hashref2str($elem).'&';
3632: } elsif(ref($elem)) {
3633: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3634: } else {
3635: $result.=&escape($elem).'&';
3636: }
3637: }
3638: $result=~s/\&$//;
1.265 albertel 3639: $result .= '__END_ARRAY_REF__';
1.204 albertel 3640: return $result;
3641: }
3642:
1.168 albertel 3643: sub hash2str {
1.204 albertel 3644: my (%hash) = @_;
3645: my $result=&hashref2str(\%hash);
1.265 albertel 3646: $result=~s/^__HASH_REF__//;
3647: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3648: return $result;
3649: }
3650:
3651: sub hashref2str {
3652: my ($hashref)=@_;
1.265 albertel 3653: my $result='__HASH_REF__';
1.800 albertel 3654: foreach my $key (sort(keys(%$hashref))) {
3655: if (ref($key) eq 'ARRAY') {
3656: $result.=&arrayref2str($key).'=';
3657: } elsif (ref($key) eq 'HASH') {
3658: $result.=&hashref2str($key).'=';
3659: } elsif (ref($key)) {
1.265 albertel 3660: $result.='=';
1.800 albertel 3661: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3662: } else {
1.800 albertel 3663: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3664: }
3665:
1.800 albertel 3666: if(ref($hashref->{$key}) eq 'ARRAY') {
3667: $result.=&arrayref2str($hashref->{$key}).'&';
3668: } elsif(ref($hashref->{$key}) eq 'HASH') {
3669: $result.=&hashref2str($hashref->{$key}).'&';
3670: } elsif(ref($hashref->{$key})) {
1.265 albertel 3671: $result.='&';
1.800 albertel 3672: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3673: } else {
1.800 albertel 3674: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3675: }
3676: }
1.168 albertel 3677: $result=~s/\&$//;
1.265 albertel 3678: $result .= '__END_HASH_REF__';
1.168 albertel 3679: return $result;
3680: }
3681:
3682: sub str2hash {
1.265 albertel 3683: my ($string)=@_;
3684: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3685: return %$hash;
3686: }
3687:
3688: sub str2hashref {
1.168 albertel 3689: my ($string) = @_;
1.265 albertel 3690:
3691: my %hash;
3692:
3693: if($string !~ /^__HASH_REF__/) {
3694: if (! ($string eq '' || !defined($string))) {
3695: $hash{'error'}='Not hash reference';
3696: }
3697: return (\%hash, $string);
3698: }
3699:
3700: $string =~ s/^__HASH_REF__//;
3701:
3702: while($string !~ /^__END_HASH_REF__/) {
3703: #key
3704: my $key='';
3705: if($string =~ /^__HASH_REF__/) {
3706: ($key, $string)=&str2hashref($string);
3707: if(defined($key->{'error'})) {
3708: $hash{'error'}='Bad data';
3709: return (\%hash, $string);
3710: }
3711: } elsif($string =~ /^__ARRAY_REF__/) {
3712: ($key, $string)=&str2arrayref($string);
3713: if($key->[0] eq 'Array reference error') {
3714: $hash{'error'}='Bad data';
3715: return (\%hash, $string);
3716: }
3717: } else {
3718: $string =~ s/^(.*?)=//;
1.267 albertel 3719: $key=&unescape($1);
1.265 albertel 3720: }
3721: $string =~ s/^=//;
3722:
3723: #value
3724: my $value='';
3725: if($string =~ /^__HASH_REF__/) {
3726: ($value, $string)=&str2hashref($string);
3727: if(defined($value->{'error'})) {
3728: $hash{'error'}='Bad data';
3729: return (\%hash, $string);
3730: }
3731: } elsif($string =~ /^__ARRAY_REF__/) {
3732: ($value, $string)=&str2arrayref($string);
3733: if($value->[0] eq 'Array reference error') {
3734: $hash{'error'}='Bad data';
3735: return (\%hash, $string);
3736: }
3737: } else {
3738: $value=&get_scalar(\$string,'__END_HASH_REF__');
3739: }
3740: $string =~ s/^&//;
3741:
3742: $hash{$key}=$value;
1.204 albertel 3743: }
1.265 albertel 3744:
3745: $string =~ s/^__END_HASH_REF__//;
3746:
3747: return (\%hash, $string);
1.204 albertel 3748: }
3749:
3750: sub str2array {
1.265 albertel 3751: my ($string)=@_;
3752: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3753: return @$array;
3754: }
3755:
3756: sub str2arrayref {
1.204 albertel 3757: my ($string) = @_;
1.265 albertel 3758: my @array;
3759:
3760: if($string !~ /^__ARRAY_REF__/) {
3761: if (! ($string eq '' || !defined($string))) {
3762: $array[0]='Array reference error';
3763: }
3764: return (\@array, $string);
3765: }
3766:
3767: $string =~ s/^__ARRAY_REF__//;
3768:
3769: while($string !~ /^__END_ARRAY_REF__/) {
3770: my $value='';
3771: if($string =~ /^__HASH_REF__/) {
3772: ($value, $string)=&str2hashref($string);
3773: if(defined($value->{'error'})) {
3774: $array[0] ='Array reference error';
3775: return (\@array, $string);
3776: }
3777: } elsif($string =~ /^__ARRAY_REF__/) {
3778: ($value, $string)=&str2arrayref($string);
3779: if($value->[0] eq 'Array reference error') {
3780: $array[0] ='Array reference error';
3781: return (\@array, $string);
3782: }
3783: } else {
3784: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3785: }
3786: $string =~ s/^&//;
3787:
3788: push(@array, $value);
1.191 harris41 3789: }
1.265 albertel 3790:
3791: $string =~ s/^__END_ARRAY_REF__//;
3792:
3793: return (\@array, $string);
1.168 albertel 3794: }
3795:
1.167 albertel 3796: # -------------------------------------------------------------------Temp Store
3797:
1.168 albertel 3798: sub tmpreset {
3799: my ($symb,$namespace,$domain,$stuname) = @_;
3800: if (!$symb) {
3801: $symb=&symbread();
1.620 albertel 3802: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3803: }
3804: $symb=escape($symb);
3805:
1.620 albertel 3806: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3807: $namespace=~s/\//\_/g;
3808: $namespace=~s/\W//g;
3809:
1.620 albertel 3810: if (!$domain) { $domain=$env{'user.domain'}; }
3811: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3812: if ($domain eq 'public' && $stuname eq 'public') {
3813: $stuname=$ENV{'REMOTE_ADDR'};
3814: }
1.168 albertel 3815: my $path=$perlvar{'lonDaemons'}.'/tmp';
3816: my %hash;
3817: if (tie(%hash,'GDBM_File',
3818: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3819: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3820: foreach my $key (keys(%hash)) {
1.180 albertel 3821: if ($key=~ /:$symb/) {
1.168 albertel 3822: delete($hash{$key});
3823: }
3824: }
3825: }
3826: }
3827:
1.167 albertel 3828: sub tmpstore {
1.168 albertel 3829: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3830:
3831: if (!$symb) {
3832: $symb=&symbread();
1.620 albertel 3833: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3834: }
3835: $symb=escape($symb);
3836:
3837: if (!$namespace) {
3838: # I don't think we would ever want to store this for a course.
3839: # it seems this will only be used if we don't have a course.
1.620 albertel 3840: #$namespace=$env{'request.course.id'};
1.168 albertel 3841: #if (!$namespace) {
1.620 albertel 3842: $namespace=$env{'request.state'};
1.168 albertel 3843: #}
3844: }
3845: $namespace=~s/\//\_/g;
3846: $namespace=~s/\W//g;
1.620 albertel 3847: if (!$domain) { $domain=$env{'user.domain'}; }
3848: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3849: if ($domain eq 'public' && $stuname eq 'public') {
3850: $stuname=$ENV{'REMOTE_ADDR'};
3851: }
1.168 albertel 3852: my $now=time;
3853: my %hash;
3854: my $path=$perlvar{'lonDaemons'}.'/tmp';
3855: if (tie(%hash,'GDBM_File',
3856: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3857: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3858: $hash{"version:$symb"}++;
3859: my $version=$hash{"version:$symb"};
3860: my $allkeys='';
3861: foreach my $key (keys(%$storehash)) {
3862: $allkeys.=$key.':';
1.591 albertel 3863: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3864: }
3865: $hash{"$version:$symb:timestamp"}=$now;
3866: $allkeys.='timestamp';
3867: $hash{"$version:keys:$symb"}=$allkeys;
3868: if (untie(%hash)) {
3869: return 'ok';
3870: } else {
3871: return "error:$!";
3872: }
3873: } else {
3874: return "error:$!";
3875: }
3876: }
1.167 albertel 3877:
1.168 albertel 3878: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3879:
1.168 albertel 3880: sub tmprestore {
3881: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3882:
1.168 albertel 3883: if (!$symb) {
3884: $symb=&symbread();
1.620 albertel 3885: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3886: }
3887: $symb=escape($symb);
3888:
1.620 albertel 3889: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3890:
1.620 albertel 3891: if (!$domain) { $domain=$env{'user.domain'}; }
3892: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3893: if ($domain eq 'public' && $stuname eq 'public') {
3894: $stuname=$ENV{'REMOTE_ADDR'};
3895: }
1.168 albertel 3896: my %returnhash;
3897: $namespace=~s/\//\_/g;
3898: $namespace=~s/\W//g;
3899: my %hash;
3900: my $path=$perlvar{'lonDaemons'}.'/tmp';
3901: if (tie(%hash,'GDBM_File',
3902: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3903: &GDBM_READER(),0640)) {
1.168 albertel 3904: my $version=$hash{"version:$symb"};
3905: $returnhash{'version'}=$version;
3906: my $scope;
3907: for ($scope=1;$scope<=$version;$scope++) {
3908: my $vkeys=$hash{"$scope:keys:$symb"};
3909: my @keys=split(/:/,$vkeys);
3910: my $key;
3911: $returnhash{"$scope:keys"}=$vkeys;
3912: foreach $key (@keys) {
1.591 albertel 3913: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3914: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3915: }
3916: }
1.168 albertel 3917: if (!(untie(%hash))) {
3918: return "error:$!";
3919: }
3920: } else {
3921: return "error:$!";
3922: }
3923: return %returnhash;
1.167 albertel 3924: }
3925:
1.9 www 3926: # ----------------------------------------------------------------------- Store
3927:
3928: sub store {
1.124 www 3929: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3930: my $home='';
3931:
1.168 albertel 3932: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3933:
1.213 www 3934: $symb=&symbclean($symb);
1.122 albertel 3935: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3936:
1.620 albertel 3937: if (!$domain) { $domain=$env{'user.domain'}; }
3938: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3939:
3940: &devalidate($symb,$stuname,$domain);
1.109 www 3941:
3942: $symb=escape($symb);
1.187 www 3943: if (!$namespace) {
1.620 albertel 3944: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3945: return '';
3946: }
3947: }
1.620 albertel 3948: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3949:
3950: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3951: $$storehash{'host'}=$perlvar{'lonHostID'};
3952:
1.12 www 3953: my $namevalue='';
1.800 albertel 3954: foreach my $key (keys(%$storehash)) {
3955: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3956: }
1.12 www 3957: $namevalue=~s/\&$//;
1.187 www 3958: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3959: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3960: }
3961:
1.47 www 3962: # -------------------------------------------------------------- Critical Store
3963:
3964: sub cstore {
1.124 www 3965: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3966: my $home='';
3967:
1.168 albertel 3968: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3969:
1.213 www 3970: $symb=&symbclean($symb);
1.122 albertel 3971: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3972:
1.620 albertel 3973: if (!$domain) { $domain=$env{'user.domain'}; }
3974: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3975:
3976: &devalidate($symb,$stuname,$domain);
1.109 www 3977:
3978: $symb=escape($symb);
1.187 www 3979: if (!$namespace) {
1.620 albertel 3980: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3981: return '';
3982: }
3983: }
1.620 albertel 3984: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3985:
3986: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3987: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3988:
1.47 www 3989: my $namevalue='';
1.800 albertel 3990: foreach my $key (keys(%$storehash)) {
3991: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3992: }
1.47 www 3993: $namevalue=~s/\&$//;
1.187 www 3994: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3995: return critical
3996: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3997: }
3998:
1.9 www 3999: # --------------------------------------------------------------------- Restore
4000:
4001: sub restore {
1.124 www 4002: my ($symb,$namespace,$domain,$stuname) = @_;
4003: my $home='';
4004:
1.168 albertel 4005: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4006:
1.122 albertel 4007: if (!$symb) {
4008: unless ($symb=escape(&symbread())) { return ''; }
4009: } else {
1.213 www 4010: $symb=&escape(&symbclean($symb));
1.122 albertel 4011: }
1.188 www 4012: if (!$namespace) {
1.620 albertel 4013: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4014: return '';
4015: }
4016: }
1.620 albertel 4017: if (!$domain) { $domain=$env{'user.domain'}; }
4018: if (!$stuname) { $stuname=$env{'user.name'}; }
4019: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4020: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4021:
1.12 www 4022: my %returnhash=();
1.800 albertel 4023: foreach my $line (split(/\&/,$answer)) {
4024: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4025: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4026: }
1.75 www 4027: my $version;
4028: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4029: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4030: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4031: }
1.75 www 4032: }
1.13 www 4033: return %returnhash;
1.34 www 4034: }
4035:
4036: # ---------------------------------------------------------- Course Description
4037:
4038: sub coursedescription {
1.731 albertel 4039: my ($courseid,$args)=@_;
1.34 www 4040: $courseid=~s/^\///;
1.49 www 4041: $courseid=~s/\_/\//g;
1.34 www 4042: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4043: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4044: my $normalid=$cdomain.'_'.$cnum;
4045: # need to always cache even if we get errors otherwise we keep
4046: # trying and trying and trying to get the course description.
4047: my %envhash=();
4048: my %returnhash=();
1.731 albertel 4049:
4050: my $expiretime=600;
4051: if ($env{'request.course.id'} eq $normalid) {
4052: $expiretime=120;
4053: }
4054:
4055: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4056: if (!$args->{'freshen_cache'}
4057: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4058: foreach my $key (keys(%env)) {
4059: next if ($key !~ /^\Q$prefix\E(.*)/);
4060: my ($setting) = $1;
4061: $returnhash{$setting} = $env{$key};
4062: }
4063: return %returnhash;
4064: }
4065:
4066: # get the data agin
4067: if (!$args->{'one_time'}) {
4068: $envhash{'course.'.$normalid.'.last_cache'}=time;
4069: }
1.811 albertel 4070:
1.34 www 4071: if ($chome ne 'no_host') {
1.302 albertel 4072: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4073: if (!exists($returnhash{'con_lost'})) {
4074: $returnhash{'home'}= $chome;
4075: $returnhash{'domain'} = $cdomain;
4076: $returnhash{'num'} = $cnum;
1.741 raeburn 4077: if (!defined($returnhash{'type'})) {
4078: $returnhash{'type'} = 'Course';
4079: }
1.130 albertel 4080: while (my ($name,$value) = each %returnhash) {
1.53 www 4081: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4082: }
1.270 www 4083: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4084: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4085: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4086: $envhash{'course.'.$normalid.'.home'}=$chome;
4087: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4088: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4089: }
4090: }
1.731 albertel 4091: if (!$args->{'one_time'}) {
1.949 raeburn 4092: &appenv(\%envhash);
1.731 albertel 4093: }
1.302 albertel 4094: return %returnhash;
1.461 www 4095: }
4096:
1.1056.4.5 raeburn 4097: sub update_released_required {
4098: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4099: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4100: $cid = $env{'request.course.id'};
4101: $cdom = $env{'course.'.$cid.'.domain'};
4102: $cnum = $env{'course.'.$cid.'.num'};
4103: $chome = $env{'course.'.$cid.'.home'};
4104: }
4105: if ($needsrelease) {
4106: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4107: my $needsupdate;
4108: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4109: $needsupdate = 1;
4110: } else {
4111: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4112: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4113: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4114: $needsupdate = 1;
4115: }
4116: }
4117: if ($needsupdate) {
4118: my %needshash = (
4119: 'internal.releaserequired' => $needsrelease,
4120: );
4121: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4122: if ($putresult eq 'ok') {
4123: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4124: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4125: if (ref($crsinfo{$cid}) eq 'HASH') {
4126: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4127: &courseidput($cdom,\%crsinfo,$chome,'notime');
4128: }
4129: }
4130: }
4131: }
4132: return;
4133: }
4134:
1.461 www 4135: # -------------------------------------------------See if a user is privileged
4136:
4137: sub privileged {
4138: my ($username,$domain)=@_;
4139: my $rolesdump=&reply("dump:$domain:$username:roles",
4140: &homeserver($username,$domain));
1.1033 raeburn 4141: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4142: ($rolesdump =~ /^error:/)) {
4143: return 0;
4144: }
1.461 www 4145: my $now=time;
4146: if ($rolesdump ne '') {
1.800 albertel 4147: foreach my $entry (split(/&/,$rolesdump)) {
4148: if ($entry!~/^rolesdef_/) {
4149: my ($area,$role)=split(/=/,$entry);
1.461 www 4150: $area=~s/\_\w\w$//;
4151: my ($trole,$tend,$tstart)=split(/_/,$role);
4152: if (($trole eq 'dc') || ($trole eq 'su')) {
4153: my $active=1;
4154: if ($tend) {
4155: if ($tend<$now) { $active=0; }
4156: }
4157: if ($tstart) {
4158: if ($tstart>$now) { $active=0; }
4159: }
4160: if ($active) { return 1; }
4161: }
4162: }
4163: }
4164: }
4165: return 0;
1.9 www 4166: }
1.1 albertel 4167:
1.103 harris41 4168: # -------------------------------------------------------- Get user privileges
1.11 www 4169:
4170: sub rolesinit {
4171: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4172: my $now=time;
4173: my %userroles = ('user.login.time' => $now);
1.1056.4.10 raeburn 4174: my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3 raeburn 4175: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4176: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1056.4.3 raeburn 4177: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4178: return \%userroles;
4179: }
1.11 www 4180: my %allroles=();
1.678 raeburn 4181: my %allgroups=();
4182: my $group_privs;
1.11 www 4183:
4184: if ($rolesdump ne '') {
1.800 albertel 4185: foreach my $entry (split(/&/,$rolesdump)) {
4186: if ($entry!~/^rolesdef_/) {
4187: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4188: $area=~s/\_\w\w$//;
1.678 raeburn 4189: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4190: if ($role=~/^cr/) {
1.807 albertel 4191: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4192: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4193: ($tend,$tstart)=split('_',$trest);
4194: } else {
4195: $trole=$role;
4196: }
1.678 raeburn 4197: } elsif ($role =~ m|^gr/|) {
4198: ($trole,$tend,$tstart) = split(/_/,$role);
4199: ($trole,$group_privs) = split(/\//,$trole);
4200: $group_privs = &unescape($group_privs);
1.587 albertel 4201: } else {
4202: ($trole,$tend,$tstart)=split(/_/,$role);
4203: }
1.743 albertel 4204: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4205: $username);
4206: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4207: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4208: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4209: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4210: my $spec=$trole.'.'.$area;
4211: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4212: if ($trole =~ /^cr\//) {
1.567 raeburn 4213: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4214: } elsif ($trole eq 'gr') {
4215: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4216: } else {
1.567 raeburn 4217: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4218: }
1.12 www 4219: }
1.662 raeburn 4220: }
1.191 harris41 4221: }
1.743 albertel 4222: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4223: $userroles{'user.adv'} = $adv;
4224: $userroles{'user.author'} = $author;
1.620 albertel 4225: $env{'user.adv'}=$adv;
1.11 www 4226: }
1.743 albertel 4227: return \%userroles;
1.11 www 4228: }
4229:
1.567 raeburn 4230: sub set_arearole {
4231: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4232: # log the associated role with the area
4233: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4234: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4235: }
4236:
4237: sub custom_roleprivs {
4238: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4239: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4240: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4241: if (&hostname($homsvr) ne '') {
1.567 raeburn 4242: my ($rdummy,$roledef)=
4243: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4244: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4245: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4246: if (defined($syspriv)) {
1.1043 raeburn 4247: if ($trest =~ /^$match_community$/) {
4248: $syspriv =~ s/bre\&S//;
4249: }
1.567 raeburn 4250: $$allroles{'cm./'}.=':'.$syspriv;
4251: $$allroles{$spec.'./'}.=':'.$syspriv;
4252: }
4253: if ($tdomain ne '') {
4254: if (defined($dompriv)) {
4255: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4256: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4257: }
4258: if (($trest ne '') && (defined($coursepriv))) {
4259: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4260: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4261: }
4262: }
4263: }
4264: }
4265: }
4266:
1.678 raeburn 4267: sub group_roleprivs {
4268: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4269: my $access = 1;
4270: my $now = time;
4271: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4272: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4273: if ($access) {
1.811 albertel 4274: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4275: $$allgroups{$course}{$group} .=':'.$group_privs;
4276: }
4277: }
1.567 raeburn 4278:
4279: sub standard_roleprivs {
4280: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4281: if (defined($pr{$trole.':s'})) {
4282: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4283: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4284: }
4285: if ($tdomain ne '') {
4286: if (defined($pr{$trole.':d'})) {
4287: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4288: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4289: }
4290: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4291: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4292: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4293: }
4294: }
4295: }
4296:
4297: sub set_userprivs {
1.1056.4.2 raeburn 4298: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4299: my $author=0;
4300: my $adv=0;
1.678 raeburn 4301: my %grouproles = ();
4302: if (keys(%{$allgroups}) > 0) {
1.1056.4.2 raeburn 4303: my @groupkeys;
1.1000 raeburn 4304: foreach my $role (keys(%{$allroles})) {
1.1056.4.2 raeburn 4305: push(@groupkeys,$role);
4306: }
4307: if (ref($groups_roles) eq 'HASH') {
4308: foreach my $key (keys(%{$groups_roles})) {
4309: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4310: push(@groupkeys,$key);
4311: }
4312: }
4313: }
4314: if (@groupkeys > 0) {
4315: foreach my $role (@groupkeys) {
4316: my ($trole,$area,$sec,$extendedarea);
4317: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4318: $trole = $1;
4319: $area = $2;
4320: $sec = $3;
4321: $extendedarea = $area.$sec;
4322: if (exists($$allgroups{$area})) {
4323: foreach my $group (keys(%{$$allgroups{$area}})) {
4324: my $spec = $trole.'.'.$extendedarea;
4325: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4326: $$allgroups{$area}{$group};
1.1056.4.2 raeburn 4327: }
1.678 raeburn 4328: }
4329: }
4330: }
4331: }
4332: }
1.800 albertel 4333: foreach my $group (keys(%grouproles)) {
4334: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4335: }
1.800 albertel 4336: foreach my $role (keys(%{$allroles})) {
4337: my %thesepriv;
1.941 raeburn 4338: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4339: foreach my $item (split(/:/,$$allroles{$role})) {
4340: if ($item ne '') {
4341: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4342: if ($restrictions eq '') {
4343: $thesepriv{$privilege}='F';
4344: } elsif ($thesepriv{$privilege} ne 'F') {
4345: $thesepriv{$privilege}.=$restrictions;
4346: }
4347: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4348: }
4349: }
4350: my $thesestr='';
1.800 albertel 4351: foreach my $priv (keys(%thesepriv)) {
4352: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4353: }
4354: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4355: }
4356: return ($author,$adv);
4357: }
4358:
1.994 raeburn 4359: sub role_status {
1.1002 raeburn 4360: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4361: my @pwhere = ();
4362: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4363: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4364: unless (!defined($$role) || $$role eq '') {
4365: $$where=join('.',@pwhere);
4366: $$trolecode=$$role.'.'.$$where;
4367: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4368: $$tstatus='is';
4369: if ($$tstart && $$tstart>$then) {
4370: $$tstatus='future';
1.1034 raeburn 4371: if ($$tstart<$now) {
4372: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4373: if (($$where ne '') && ($$role ne '')) {
1.1056.4.2 raeburn 4374: my (%allroles,%allgroups,$group_privs,
4375: %groups_roles,@rolecodes);
1.1002 raeburn 4376: my %userroles = (
4377: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4378: );
1.1056.4.2 raeburn 4379: @rolecodes = ('cm');
1.1002 raeburn 4380: my $spec=$$role.'.'.$$where;
4381: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4382: if ($$role =~ /^cr\//) {
4383: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2 raeburn 4384: push(@rolecodes,'cr');
1.1002 raeburn 4385: } elsif ($$role eq 'gr') {
1.1056.4.2 raeburn 4386: push(@rolecodes,$$role);
1.1002 raeburn 4387: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4388: $env{'user.name'});
1.1056.4.2 raeburn 4389: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4390: (undef,my $group_privs) = split(/\//,$trole);
4391: $group_privs = &unescape($group_privs);
4392: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2 raeburn 4393: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4394: if (keys(%course_roles) > 0) {
4395: my ($tnum) = ($trest =~ /^($match_courseid)/);
4396: if ($tdomain ne '' && $tnum ne '') {
4397: foreach my $key (keys(%course_roles)) {
4398: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4399: my $crsrole = $1;
4400: my $crssec = $2;
4401: if ($crsrole =~ /^cr/) {
4402: unless (grep(/^cr$/,@rolecodes)) {
4403: push(@rolecodes,'cr');
4404: }
4405: } else {
4406: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4407: push(@rolecodes,$crsrole);
4408: }
4409: }
4410: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4411: if ($crssec ne '') {
4412: $rolekey .= '/'.$crssec;
4413: }
4414: $rolekey .= './';
4415: $groups_roles{$rolekey} = \@rolecodes;
4416: }
4417: }
4418: }
4419: }
1.1002 raeburn 4420: } else {
1.1056.4.2 raeburn 4421: push(@rolecodes,$$role);
1.1002 raeburn 4422: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4423: }
1.1056.4.2 raeburn 4424: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4425: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4426: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4427: }
4428: }
1.1034 raeburn 4429: $$tstatus = 'is';
1.1002 raeburn 4430: }
1.994 raeburn 4431: }
4432: if ($$tend) {
4433: if ($$tend<$then) {
4434: $$tstatus='expired';
4435: } elsif ($$tend<$now) {
4436: $$tstatus='will_not';
4437: }
4438: }
4439: }
4440: }
4441: }
4442:
4443: sub check_adhoc_privs {
1.1056.4.12 raeburn 4444: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4445: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4446: if ($env{$cckey}) {
4447: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4448: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4449: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12 raeburn 4450: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4451: }
4452: } else {
1.1056.4.12 raeburn 4453: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4454: }
4455: }
4456:
4457: sub set_adhoc_privileges {
4458: # role can be cc or ca
1.1056.4.12 raeburn 4459: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4460: my $area = '/'.$dcdom.'/'.$pickedcourse;
4461: my $spec = $role.'.'.$area;
4462: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4463: $env{'user.name'});
4464: my %ccrole = ();
4465: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4466: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4467: &appenv(\%userroles,[$role,'cm']);
4468: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12 raeburn 4469: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4470: &appenv( {'request.role' => $spec,
4471: 'request.role.domain' => $dcdom,
4472: 'request.course.sec' => ''
4473: }
4474: );
4475: my $tadv=0;
4476: if (&allowed('adv') eq 'F') { $tadv=1; }
4477: &appenv({'request.role.adv' => $tadv});
4478: }
1.994 raeburn 4479: }
4480:
1.12 www 4481: # --------------------------------------------------------------- get interface
4482:
4483: sub get {
1.131 albertel 4484: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4485: my $items='';
1.800 albertel 4486: foreach my $item (@$storearr) {
4487: $items.=&escape($item).'&';
1.191 harris41 4488: }
1.12 www 4489: $items=~s/\&$//;
1.620 albertel 4490: if (!$udomain) { $udomain=$env{'user.domain'}; }
4491: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4492: my $uhome=&homeserver($uname,$udomain);
4493:
1.133 albertel 4494: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4495: my @pairs=split(/\&/,$rep);
1.273 albertel 4496: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4497: return @pairs;
4498: }
1.15 www 4499: my %returnhash=();
1.42 www 4500: my $i=0;
1.800 albertel 4501: foreach my $item (@$storearr) {
4502: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4503: $i++;
1.191 harris41 4504: }
1.15 www 4505: return %returnhash;
1.27 www 4506: }
4507:
4508: # --------------------------------------------------------------- del interface
4509:
4510: sub del {
1.133 albertel 4511: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4512: my $items='';
1.800 albertel 4513: foreach my $item (@$storearr) {
4514: $items.=&escape($item).'&';
1.191 harris41 4515: }
1.984 neumanie 4516:
1.27 www 4517: $items=~s/\&$//;
1.620 albertel 4518: if (!$udomain) { $udomain=$env{'user.domain'}; }
4519: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4520: my $uhome=&homeserver($uname,$udomain);
4521: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4522: }
4523:
4524: # -------------------------------------------------------------- dump interface
4525:
4526: sub dump {
1.1056.4.10 raeburn 4527: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4528: if (!$udomain) { $udomain=$env{'user.domain'}; }
4529: if (!$uname) { $uname=$env{'user.name'}; }
4530: my $uhome=&homeserver($uname,$udomain);
4531: if ($regexp) {
4532: $regexp=&escape($regexp);
4533: } else {
4534: $regexp='.';
4535: }
1.1056.4.10 raeburn 4536: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4537: my @pairs=split(/\&/,$rep);
4538: my %returnhash=();
4539: foreach my $item (@pairs) {
4540: my ($key,$value)=split(/=/,$item,2);
4541: $key = &unescape($key);
4542: next if ($key =~ /^error: 2 /);
4543: $returnhash{$key}=&thaw_unescape($value);
4544: }
4545: return %returnhash;
1.407 www 4546: }
4547:
1.717 albertel 4548: # --------------------------------------------------------- dumpstore interface
4549:
4550: sub dumpstore {
4551: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4552: if (!$udomain) { $udomain=$env{'user.domain'}; }
4553: if (!$uname) { $uname=$env{'user.name'}; }
4554: my $uhome=&homeserver($uname,$udomain);
4555: if ($regexp) {
4556: $regexp=&escape($regexp);
4557: } else {
4558: $regexp='.';
4559: }
4560: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4561: my @pairs=split(/\&/,$rep);
4562: my %returnhash=();
4563: foreach my $item (@pairs) {
4564: my ($key,$value)=split(/=/,$item,2);
4565: next if ($key =~ /^error: 2 /);
4566: $returnhash{$key}=&thaw_unescape($value);
4567: }
4568: return %returnhash;
1.717 albertel 4569: }
4570:
1.407 www 4571: # -------------------------------------------------------------- keys interface
4572:
4573: sub getkeys {
4574: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4575: if (!$udomain) { $udomain=$env{'user.domain'}; }
4576: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4577: my $uhome=&homeserver($uname,$udomain);
4578: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4579: my @keyarray=();
1.800 albertel 4580: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4581: next if ($key =~ /^error: 2 /);
1.800 albertel 4582: push(@keyarray,&unescape($key));
1.407 www 4583: }
4584: return @keyarray;
1.318 matthew 4585: }
4586:
1.319 matthew 4587: # --------------------------------------------------------------- currentdump
4588: sub currentdump {
1.328 matthew 4589: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4590: $courseid = $env{'request.course.id'} if (! defined($courseid));
4591: $sdom = $env{'user.domain'} if (! defined($sdom));
4592: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4593: my $uhome = &homeserver($sname,$sdom);
4594: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4595: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4596: #
1.318 matthew 4597: my %returnhash=();
1.319 matthew 4598: #
4599: if ($rep eq "unknown_cmd") {
4600: # an old lond will not know currentdump
4601: # Do a dump and make it look like a currentdump
1.822 albertel 4602: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4603: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4604: my %hash = @tmp;
4605: @tmp=();
1.424 matthew 4606: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4607: } else {
4608: my @pairs=split(/\&/,$rep);
1.800 albertel 4609: foreach my $pair (@pairs) {
4610: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4611: my ($symb,$param) = split(/:/,$key);
4612: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4613: &thaw_unescape($value);
1.319 matthew 4614: }
1.191 harris41 4615: }
1.12 www 4616: return %returnhash;
1.424 matthew 4617: }
4618:
4619: sub convert_dump_to_currentdump{
4620: my %hash = %{shift()};
4621: my %returnhash;
4622: # Code ripped from lond, essentially. The only difference
4623: # here is the unescaping done by lonnet::dump(). Conceivably
4624: # we might run in to problems with parameter names =~ /^v\./
4625: while (my ($key,$value) = each(%hash)) {
4626: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4627: $symb = &unescape($symb);
4628: $param = &unescape($param);
1.424 matthew 4629: next if ($v eq 'version' || $symb eq 'keys');
4630: next if (exists($returnhash{$symb}) &&
4631: exists($returnhash{$symb}->{$param}) &&
4632: $returnhash{$symb}->{'v.'.$param} > $v);
4633: $returnhash{$symb}->{$param}=$value;
4634: $returnhash{$symb}->{'v.'.$param}=$v;
4635: }
4636: #
4637: # Remove all of the keys in the hashes which keep track of
4638: # the version of the parameter.
4639: while (my ($symb,$param_hash) = each(%returnhash)) {
4640: # use a foreach because we are going to delete from the hash.
4641: foreach my $key (keys(%$param_hash)) {
4642: delete($param_hash->{$key}) if ($key =~ /^v\./);
4643: }
4644: }
4645: return \%returnhash;
1.12 www 4646: }
4647:
1.627 albertel 4648: # ------------------------------------------------------ critical inc interface
4649:
4650: sub cinc {
4651: return &inc(@_,'critical');
4652: }
4653:
1.449 matthew 4654: # --------------------------------------------------------------- inc interface
4655:
4656: sub inc {
1.627 albertel 4657: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4658: if (!$udomain) { $udomain=$env{'user.domain'}; }
4659: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4660: my $uhome=&homeserver($uname,$udomain);
4661: my $items='';
4662: if (! ref($store)) {
4663: # got a single value, so use that instead
4664: $items = &escape($store).'=&';
4665: } elsif (ref($store) eq 'SCALAR') {
4666: $items = &escape($$store).'=&';
4667: } elsif (ref($store) eq 'ARRAY') {
4668: $items = join('=&',map {&escape($_);} @{$store});
4669: } elsif (ref($store) eq 'HASH') {
4670: while (my($key,$value) = each(%{$store})) {
4671: $items.= &escape($key).'='.&escape($value).'&';
4672: }
4673: }
4674: $items=~s/\&$//;
1.627 albertel 4675: if ($critical) {
4676: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4677: } else {
4678: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4679: }
1.449 matthew 4680: }
4681:
1.12 www 4682: # --------------------------------------------------------------- put interface
4683:
4684: sub put {
1.134 albertel 4685: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4686: if (!$udomain) { $udomain=$env{'user.domain'}; }
4687: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4688: my $uhome=&homeserver($uname,$udomain);
1.12 www 4689: my $items='';
1.800 albertel 4690: foreach my $item (keys(%$storehash)) {
4691: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4692: }
1.12 www 4693: $items=~s/\&$//;
1.134 albertel 4694: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4695: }
4696:
1.631 albertel 4697: # ------------------------------------------------------------ newput interface
4698:
4699: sub newput {
4700: my ($namespace,$storehash,$udomain,$uname)=@_;
4701: if (!$udomain) { $udomain=$env{'user.domain'}; }
4702: if (!$uname) { $uname=$env{'user.name'}; }
4703: my $uhome=&homeserver($uname,$udomain);
4704: my $items='';
4705: foreach my $key (keys(%$storehash)) {
4706: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4707: }
4708: $items=~s/\&$//;
4709: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4710: }
4711:
4712: # --------------------------------------------------------- putstore interface
4713:
1.524 raeburn 4714: sub putstore {
1.715 albertel 4715: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4716: if (!$udomain) { $udomain=$env{'user.domain'}; }
4717: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4718: my $uhome=&homeserver($uname,$udomain);
4719: my $items='';
1.715 albertel 4720: foreach my $key (keys(%$storehash)) {
4721: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4722: }
1.715 albertel 4723: $items=~s/\&$//;
1.716 albertel 4724: my $esc_symb=&escape($symb);
4725: my $esc_v=&escape($version);
1.715 albertel 4726: my $reply =
1.716 albertel 4727: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4728: $uhome);
4729: if ($reply eq 'unknown_cmd') {
1.716 albertel 4730: # gfall back to way things use to be done
1.715 albertel 4731: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4732: $uname);
1.524 raeburn 4733: }
1.715 albertel 4734: return $reply;
4735: }
4736:
4737: sub old_putstore {
1.716 albertel 4738: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4739: if (!$udomain) { $udomain=$env{'user.domain'}; }
4740: if (!$uname) { $uname=$env{'user.name'}; }
4741: my $uhome=&homeserver($uname,$udomain);
4742: my %newstorehash;
1.800 albertel 4743: foreach my $item (keys(%$storehash)) {
4744: my $key = $version.':'.&escape($symb).':'.$item;
4745: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4746: }
4747: my $items='';
4748: my %allitems = ();
1.800 albertel 4749: foreach my $item (keys(%newstorehash)) {
4750: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4751: my $key = $1.':keys:'.$2;
4752: $allitems{$key} .= $3.':';
4753: }
1.800 albertel 4754: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4755: }
1.800 albertel 4756: foreach my $item (keys(%allitems)) {
4757: $allitems{$item} =~ s/\:$//;
4758: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4759: }
4760: $items=~s/\&$//;
4761: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4762: }
4763:
1.47 www 4764: # ------------------------------------------------------ critical put interface
4765:
4766: sub cput {
1.134 albertel 4767: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4768: if (!$udomain) { $udomain=$env{'user.domain'}; }
4769: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4770: my $uhome=&homeserver($uname,$udomain);
1.47 www 4771: my $items='';
1.800 albertel 4772: foreach my $item (keys(%$storehash)) {
4773: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4774: }
1.47 www 4775: $items=~s/\&$//;
1.134 albertel 4776: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4777: }
4778:
4779: # -------------------------------------------------------------- eget interface
4780:
4781: sub eget {
1.133 albertel 4782: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4783: my $items='';
1.800 albertel 4784: foreach my $item (@$storearr) {
4785: $items.=&escape($item).'&';
1.191 harris41 4786: }
1.12 www 4787: $items=~s/\&$//;
1.620 albertel 4788: if (!$udomain) { $udomain=$env{'user.domain'}; }
4789: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4790: my $uhome=&homeserver($uname,$udomain);
4791: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4792: my @pairs=split(/\&/,$rep);
4793: my %returnhash=();
1.42 www 4794: my $i=0;
1.800 albertel 4795: foreach my $item (@$storearr) {
4796: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4797: $i++;
1.191 harris41 4798: }
1.12 www 4799: return %returnhash;
4800: }
4801:
1.667 albertel 4802: # ------------------------------------------------------------ tmpput interface
4803: sub tmpput {
1.802 raeburn 4804: my ($storehash,$server,$context)=@_;
1.667 albertel 4805: my $items='';
1.800 albertel 4806: foreach my $item (keys(%$storehash)) {
4807: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4808: }
4809: $items=~s/\&$//;
1.802 raeburn 4810: if (defined($context)) {
4811: $items .= ':'.&escape($context);
4812: }
1.667 albertel 4813: return &reply("tmpput:$items",$server);
4814: }
4815:
4816: # ------------------------------------------------------------ tmpget interface
4817: sub tmpget {
1.688 albertel 4818: my ($token,$server)=@_;
4819: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4820: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4821: my %returnhash;
4822: foreach my $item (split(/\&/,$rep)) {
4823: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4824: next if ($key =~ /^error: 2 /);
1.667 albertel 4825: $returnhash{&unescape($key)}=&thaw_unescape($value);
4826: }
4827: return %returnhash;
4828: }
4829:
1.688 albertel 4830: # ------------------------------------------------------------ tmpget interface
4831: sub tmpdel {
4832: my ($token,$server)=@_;
4833: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4834: return &reply("tmpdel:$token",$server);
4835: }
4836:
1.765 albertel 4837: # -------------------------------------------------- portfolio access checking
4838:
4839: sub portfolio_access {
1.766 albertel 4840: my ($requrl) = @_;
1.765 albertel 4841: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4842: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4843: if ($result) {
4844: my %setters;
4845: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4846: my ($startblock,$endblock) =
4847: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4848: if ($startblock && $endblock) {
4849: return 'B';
4850: }
4851: } else {
4852: my ($startblock,$endblock) =
4853: &Apache::loncommon::blockcheck(\%setters,'port');
4854: if ($startblock && $endblock) {
4855: return 'B';
4856: }
4857: }
4858: }
1.765 albertel 4859: if ($result eq 'ok') {
1.766 albertel 4860: return 'F';
1.765 albertel 4861: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4862: return 'A';
1.765 albertel 4863: }
1.766 albertel 4864: return '';
1.765 albertel 4865: }
4866:
4867: sub get_portfolio_access {
1.767 albertel 4868: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4869:
4870: if (!ref($access_hash)) {
4871: my $current_perms = &get_portfile_permissions($udom,$unum);
4872: my %access_controls = &get_access_controls($current_perms,$group,
4873: $file_name);
4874: $access_hash = $access_controls{$file_name};
4875: }
4876:
1.765 albertel 4877: my ($public,$guest,@domains,@users,@courses,@groups);
4878: my $now = time;
4879: if (ref($access_hash) eq 'HASH') {
4880: foreach my $key (keys(%{$access_hash})) {
4881: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4882: if ($start > $now) {
4883: next;
4884: }
4885: if ($end && $end<$now) {
4886: next;
4887: }
4888: if ($scope eq 'public') {
4889: $public = $key;
4890: last;
4891: } elsif ($scope eq 'guest') {
4892: $guest = $key;
4893: } elsif ($scope eq 'domains') {
4894: push(@domains,$key);
4895: } elsif ($scope eq 'users') {
4896: push(@users,$key);
4897: } elsif ($scope eq 'course') {
4898: push(@courses,$key);
4899: } elsif ($scope eq 'group') {
4900: push(@groups,$key);
4901: }
4902: }
4903: if ($public) {
4904: return 'ok';
4905: }
4906: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4907: if ($guest) {
4908: return $guest;
4909: }
4910: } else {
4911: if (@domains > 0) {
4912: foreach my $domkey (@domains) {
4913: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4914: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4915: return 'ok';
4916: }
4917: }
4918: }
4919: }
4920: if (@users > 0) {
4921: foreach my $userkey (@users) {
1.865 raeburn 4922: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4923: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4924: if (ref($item) eq 'HASH') {
4925: if (($item->{'uname'} eq $env{'user.name'}) &&
4926: ($item->{'udom'} eq $env{'user.domain'})) {
4927: return 'ok';
4928: }
4929: }
4930: }
4931: }
1.765 albertel 4932: }
4933: }
4934: my %roleshash;
4935: my @courses_and_groups = @courses;
4936: push(@courses_and_groups,@groups);
4937: if (@courses_and_groups > 0) {
4938: my (%allgroups,%allroles);
4939: my ($start,$end,$role,$sec,$group);
4940: foreach my $envkey (%env) {
1.1056.4.1 raeburn 4941: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4942: my $cid = $2.'_'.$3;
4943: if ($1 eq 'gr') {
4944: $group = $4;
4945: $allgroups{$cid}{$group} = $env{$envkey};
4946: } else {
4947: if ($4 eq '') {
4948: $sec = 'none';
4949: } else {
4950: $sec = $4;
4951: }
4952: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4953: }
1.811 albertel 4954: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4955: my $cid = $2.'_'.$3;
4956: if ($4 eq '') {
4957: $sec = 'none';
4958: } else {
4959: $sec = $4;
4960: }
4961: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4962: }
4963: }
4964: if (keys(%allroles) == 0) {
4965: return;
4966: }
4967: foreach my $key (@courses_and_groups) {
4968: my %content = %{$$access_hash{$key}};
4969: my $cnum = $content{'number'};
4970: my $cdom = $content{'domain'};
4971: my $cid = $cdom.'_'.$cnum;
4972: if (!exists($allroles{$cid})) {
4973: next;
4974: }
4975: foreach my $role_id (keys(%{$content{'roles'}})) {
4976: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4977: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4978: my @status = @{$content{'roles'}{$role_id}{'access'}};
4979: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4980: foreach my $role (keys(%{$allroles{$cid}})) {
4981: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4982: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4983: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4984: if (grep/^all$/,@sections) {
4985: return 'ok';
4986: } else {
4987: if (grep/^$sec$/,@sections) {
4988: return 'ok';
4989: }
4990: }
4991: }
4992: }
4993: if (keys(%{$allgroups{$cid}}) == 0) {
4994: if (grep/^none$/,@groups) {
4995: return 'ok';
4996: }
4997: } else {
4998: if (grep/^all$/,@groups) {
4999: return 'ok';
5000: }
5001: foreach my $group (keys(%{$allgroups{$cid}})) {
5002: if (grep/^$group$/,@groups) {
5003: return 'ok';
5004: }
5005: }
5006: }
5007: }
5008: }
5009: }
5010: }
5011: }
5012: if ($guest) {
5013: return $guest;
5014: }
5015: }
5016: }
5017: return;
5018: }
5019:
5020: sub course_group_datechecker {
5021: my ($dates,$now,$status) = @_;
5022: my ($start,$end) = split(/\./,$dates);
5023: if (!$start && !$end) {
5024: return 'ok';
5025: }
5026: if (grep/^active$/,@{$status}) {
5027: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5028: return 'ok';
5029: }
5030: }
5031: if (grep/^previous$/,@{$status}) {
5032: if ($end > $now ) {
5033: return 'ok';
5034: }
5035: }
5036: if (grep/^future$/,@{$status}) {
5037: if ($start > $now) {
5038: return 'ok';
5039: }
5040: }
5041: return;
5042: }
5043:
5044: sub parse_portfolio_url {
5045: my ($url) = @_;
5046:
5047: my ($type,$udom,$unum,$group,$file_name);
5048:
1.823 albertel 5049: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5050: $type = 1;
5051: $udom = $1;
5052: $unum = $2;
5053: $file_name = $3;
1.823 albertel 5054: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5055: $type = 2;
5056: $udom = $1;
5057: $unum = $2;
5058: $group = $3;
5059: $file_name = $3.'/'.$4;
5060: }
5061: if (wantarray) {
5062: return ($type,$udom,$unum,$file_name,$group);
5063: }
5064: return $type;
5065: }
5066:
5067: sub is_portfolio_url {
5068: my ($url) = @_;
5069: return scalar(&parse_portfolio_url($url));
5070: }
5071:
1.798 raeburn 5072: sub is_portfolio_file {
5073: my ($file) = @_;
1.820 raeburn 5074: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5075: return 1;
5076: }
5077: return;
5078: }
5079:
1.976 raeburn 5080: sub usertools_access {
1.1056.4.9 raeburn 5081: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985 raeburn 5082: my ($access,%tools);
5083: if ($context eq '') {
5084: $context = 'tools';
5085: }
5086: if ($context eq 'requestcourses') {
5087: %tools = (
5088: official => 1,
5089: unofficial => 1,
1.1006 raeburn 5090: community => 1,
1.985 raeburn 5091: );
5092: } else {
5093: %tools = (
5094: aboutme => 1,
5095: blog => 1,
5096: portfolio => 1,
5097: );
5098: }
1.976 raeburn 5099: return if (!defined($tools{$tool}));
5100:
5101: if ((!defined($udom)) || (!defined($uname))) {
5102: $udom = $env{'user.domain'};
5103: $uname = $env{'user.name'};
5104: }
5105:
1.978 raeburn 5106: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5107: if ($action ne 'reload') {
1.985 raeburn 5108: if ($context eq 'requestcourses') {
5109: return $env{'environment.canrequest.'.$tool};
5110: } else {
5111: return $env{'environment.availabletools.'.$tool};
5112: }
5113: }
1.976 raeburn 5114: }
5115:
5116: my ($toolstatus,$inststatus);
5117:
1.985 raeburn 5118: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5119: ($action ne 'reload')) {
5120: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5121: $inststatus = $env{'environment.inststatus'};
5122: } else {
1.1056.4.9 raeburn 5123: if (ref($userenvref) eq 'HASH') {
5124: $toolstatus = $userenvref->{$context.'.'.$tool};
5125: $inststatus = $userenvref->{'inststatus'};
5126: } else {
5127: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5128: $toolstatus = $userenv{$context.'.'.$tool};
5129: $inststatus = $userenv{'inststatus'};
5130: }
1.976 raeburn 5131: }
5132:
5133: if ($toolstatus ne '') {
5134: if ($toolstatus) {
5135: $access = 1;
5136: } else {
5137: $access = 0;
5138: }
5139: return $access;
5140: }
5141:
1.1056.4.9 raeburn 5142: my ($is_adv,%domdef);
5143: if (ref($is_advref) eq 'HASH') {
5144: $is_adv = $is_advref->{'is_adv'};
5145: } else {
5146: $is_adv = &is_advanced_user($udom,$uname);
5147: }
5148: if (ref($domdefref) eq 'HASH') {
5149: %domdef = %{$domdefref};
5150: } else {
5151: %domdef = &get_domain_defaults($udom);
5152: }
1.976 raeburn 5153: if (ref($domdef{$tool}) eq 'HASH') {
5154: if ($is_adv) {
5155: if ($domdef{$tool}{'_LC_adv'} ne '') {
5156: if ($domdef{$tool}{'_LC_adv'}) {
5157: $access = 1;
5158: } else {
5159: $access = 0;
5160: }
5161: return $access;
5162: }
5163: }
5164: if ($inststatus ne '') {
5165: my ($hasaccess,$hasnoaccess);
5166: foreach my $affiliation (split(/:/,$inststatus)) {
5167: if ($domdef{$tool}{$affiliation} ne '') {
5168: if ($domdef{$tool}{$affiliation}) {
5169: $hasaccess = 1;
5170: } else {
5171: $hasnoaccess = 1;
5172: }
5173: }
5174: }
5175: if ($hasaccess || $hasnoaccess) {
5176: if ($hasaccess) {
5177: $access = 1;
5178: } elsif ($hasnoaccess) {
5179: $access = 0;
5180: }
5181: return $access;
5182: }
5183: } else {
5184: if ($domdef{$tool}{'default'} ne '') {
5185: if ($domdef{$tool}{'default'}) {
5186: $access = 1;
5187: } elsif ($domdef{$tool}{'default'} == 0) {
5188: $access = 0;
5189: }
5190: return $access;
5191: }
5192: }
5193: } else {
1.985 raeburn 5194: if ($context eq 'tools') {
5195: $access = 1;
5196: } else {
5197: $access = 0;
5198: }
1.976 raeburn 5199: return $access;
5200: }
5201: }
5202:
1.1050 raeburn 5203: sub is_course_owner {
5204: my ($cdom,$cnum,$udom,$uname) = @_;
5205: if (($udom eq '') || ($uname eq '')) {
5206: $udom = $env{'user.domain'};
5207: $uname = $env{'user.name'};
5208: }
5209: unless (($udom eq '') || ($uname eq '')) {
5210: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5211: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5212: return 1;
5213: } else {
5214: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5215: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5216: return 1;
5217: }
5218: }
5219: }
5220: }
5221: return;
5222: }
5223:
1.976 raeburn 5224: sub is_advanced_user {
5225: my ($udom,$uname) = @_;
1.1056.4.10 raeburn 5226: if ($udom ne '' && $uname ne '') {
5227: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5228: return $env{'user.adv'};
5229: }
5230: }
1.976 raeburn 5231: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5232: my %allroles;
5233: my $is_adv;
5234: foreach my $role (keys(%roleshash)) {
5235: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5236: my $area = '/'.$tdomain.'/'.$trest;
5237: if ($sec ne '') {
5238: $area .= '/'.$sec;
5239: }
5240: if (($area ne '') && ($trole ne '')) {
5241: my $spec=$trole.'.'.$area;
5242: if ($trole =~ /^cr\//) {
5243: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5244: } elsif ($trole ne 'gr') {
5245: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5246: }
5247: }
5248: }
5249: foreach my $role (keys(%allroles)) {
5250: last if ($is_adv);
5251: foreach my $item (split(/:/,$allroles{$role})) {
5252: if ($item ne '') {
5253: my ($privilege,$restrictions)=split(/&/,$item);
5254: if ($privilege eq 'adv') {
5255: $is_adv = 1;
5256: last;
5257: }
5258: }
5259: }
5260: }
5261: return $is_adv;
5262: }
1.798 raeburn 5263:
1.1035 raeburn 5264: sub check_can_request {
1.1036 raeburn 5265: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5266: my $canreq = 0;
5267: my ($types,$typename) = &Apache::loncommon::course_types();
5268: my @options = ('approval','validate','autolimit');
5269: my $optregex = join('|',@options);
5270: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5271: foreach my $type (@{$types}) {
5272: if (&usertools_access($env{'user.name'},
5273: $env{'user.domain'},
5274: $type,undef,'requestcourses')) {
5275: $canreq ++;
1.1036 raeburn 5276: if (ref($request_domains) eq 'HASH') {
5277: push(@{$request_domains->{$type}},$env{'user.domain'});
5278: }
1.1035 raeburn 5279: if ($dom eq $env{'user.domain'}) {
5280: $can_request->{$type} = 1;
5281: }
5282: }
5283: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5284: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5285: if (@curr > 0) {
1.1036 raeburn 5286: foreach my $item (@curr) {
5287: if (ref($request_domains) eq 'HASH') {
5288: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5289: if ($otherdom ne '') {
5290: if (ref($request_domains->{$type}) eq 'ARRAY') {
5291: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5292: push(@{$request_domains->{$type}},$otherdom);
5293: }
5294: } else {
5295: push(@{$request_domains->{$type}},$otherdom);
5296: }
5297: }
5298: }
5299: }
5300: unless($dom eq $env{'user.domain'}) {
5301: $canreq ++;
1.1035 raeburn 5302: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5303: $can_request->{$type} = 1;
5304: }
5305: }
5306: }
5307: }
5308: }
5309: }
5310: return $canreq;
5311: }
5312:
1.341 www 5313: # ---------------------------------------------- Custom access rule evaluation
5314:
5315: sub customaccess {
5316: my ($priv,$uri)=@_;
1.807 albertel 5317: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5318: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5319: $udom = &LONCAPA::clean_domain($udom);
5320: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5321: my $access=0;
1.800 albertel 5322: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5323: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5324: if ($type eq 'user') {
5325: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5326: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5327: if ($tdom) {
5328: if ($tdom ne $env{'user.domain'}) { next; }
5329: }
1.896 albertel 5330: if ($tuname) {
5331: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5332: }
5333: $access=($effect eq 'allow');
5334: last;
5335: }
5336: } else {
5337: if ($role) {
5338: if ($role ne $urole) { next; }
5339: }
5340: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5341: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5342: if ($tdom) {
5343: if ($tdom ne $udom) { next; }
5344: }
5345: if ($tcrs) {
5346: if ($tcrs ne $ucrs) { next; }
5347: }
5348: if ($tsec) {
5349: if ($tsec ne $usec) { next; }
5350: }
5351: $access=($effect eq 'allow');
5352: last;
5353: }
5354: if ($realm eq '' && $role eq '') {
5355: $access=($effect eq 'allow');
5356: }
1.402 bowersj2 5357: }
1.341 www 5358: }
5359: return $access;
5360: }
5361:
1.103 harris41 5362: # ------------------------------------------------- Check for a user privilege
1.12 www 5363:
5364: sub allowed {
1.810 raeburn 5365: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5366: my $ver_orguri=$uri;
1.439 www 5367: $uri=&deversion($uri);
1.152 www 5368: my $orguri=$uri;
1.52 www 5369: $uri=&declutter($uri);
1.809 raeburn 5370:
1.810 raeburn 5371: if ($priv eq 'evb') {
5372: # Evade communication block restrictions for specified role in a course
5373: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5374: return $1;
5375: } else {
5376: return;
5377: }
5378: }
5379:
1.620 albertel 5380: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5381: # Free bre access to adm and meta resources
1.775 albertel 5382: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5383: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5384: && ($priv eq 'bre')) {
1.14 www 5385: return 'F';
1.159 www 5386: }
5387:
1.545 banghart 5388: # Free bre access to user's own portfolio contents
1.714 raeburn 5389: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5390: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5391: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5392: my %setters;
5393: my ($startblock,$endblock) =
5394: &Apache::loncommon::blockcheck(\%setters,'port');
5395: if ($startblock && $endblock) {
5396: return 'B';
5397: } else {
5398: return 'F';
5399: }
1.545 banghart 5400: }
5401:
1.762 raeburn 5402: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5403: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5404: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5405: if (exists($env{'request.course.id'})) {
5406: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5407: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5408: if (($domain eq $cdom) && ($name eq $cnum)) {
5409: my $courseprivid=$env{'request.course.id'};
5410: $courseprivid=~s/\_/\//;
5411: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5412: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5413: return $1;
1.762 raeburn 5414: } else {
5415: if ($env{'request.course.sec'}) {
5416: $courseprivid.='/'.$env{'request.course.sec'};
5417: }
5418: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5419: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5420: return $2;
5421: }
1.714 raeburn 5422: }
5423: }
5424: }
5425: }
5426:
1.159 www 5427: # Free bre to public access
5428:
5429: if ($priv eq 'bre') {
1.238 www 5430: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5431: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5432: return 'F';
5433: }
1.238 www 5434: if ($copyright eq 'priv') {
5435: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5436: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5437: return '';
5438: }
5439: }
5440: if ($copyright eq 'domain') {
5441: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5442: unless (($env{'user.domain'} eq $1) ||
5443: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5444: return '';
5445: }
1.262 matthew 5446: }
1.620 albertel 5447: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5448: # Library role, so allow browsing of resources in this domain.
5449: return 'F';
1.238 www 5450: }
1.341 www 5451: if ($copyright eq 'custom') {
5452: unless (&customaccess($priv,$uri)) { return ''; }
5453: }
1.14 www 5454: }
1.264 matthew 5455: # Domain coordinator is trying to create a course
1.620 albertel 5456: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5457: # uri is the requested domain in this case.
5458: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5459: # a role of dc for the domain in question.
1.620 albertel 5460: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5461: }
1.29 www 5462:
1.52 www 5463: my $thisallowed='';
5464: my $statecond=0;
5465: my $courseprivid='';
5466:
1.1039 raeburn 5467: my $ownaccess;
1.1043 raeburn 5468: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5469: if (($priv eq 'bro') && ($env{'user.author'})) {
5470: if ($uri eq '') {
5471: $ownaccess = 1;
5472: } else {
5473: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5474: my $udom = $env{'user.domain'};
5475: my $uname = $env{'user.name'};
5476: if ($uri =~ m{^\Q$udom\E/?$}) {
5477: $ownaccess = 1;
1.1040 raeburn 5478: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5479: unless ($uri =~ m{\.\./}) {
5480: $ownaccess = 1;
5481: }
5482: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5483: my $now = time;
5484: if ($uri =~ m{^([^/]+)/?$}) {
5485: my $adom = $1;
5486: foreach my $key (keys(%env)) {
1.1042 raeburn 5487: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5488: my ($start,$end) = split('.',$env{$key});
5489: if (($now >= $start) && (!$end || $end < $now)) {
5490: $ownaccess = 1;
5491: last;
5492: }
5493: }
5494: }
5495: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5496: my $adom = $1;
5497: my $aname = $2;
1.1042 raeburn 5498: foreach my $role ('ca','aa') {
5499: if ($env{"user.role.$role./$adom/$aname"}) {
5500: my ($start,$end) =
5501: split('.',$env{"user.role.$role./$adom/$aname"});
5502: if (($now >= $start) && (!$end || $end < $now)) {
5503: $ownaccess = 1;
5504: last;
5505: }
1.1039 raeburn 5506: }
5507: }
5508: }
5509: }
5510: }
5511: }
5512: }
5513:
1.52 www 5514: # Course
5515:
1.620 albertel 5516: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5517: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5518: $thisallowed.=$1;
5519: }
1.52 www 5520: }
1.29 www 5521:
1.52 www 5522: # Domain
5523:
1.620 albertel 5524: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5525: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5526: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5527: $thisallowed.=$1;
5528: }
1.12 www 5529: }
1.52 www 5530:
5531: # Course: uri itself is a course
1.66 www 5532: my $courseuri=$uri;
5533: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5534: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5535:
1.620 albertel 5536: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5537: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5538: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5539: $thisallowed.=$1;
5540: }
1.12 www 5541: }
1.29 www 5542:
1.665 albertel 5543: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5544: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5545: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5546: $thisallowed='';
1.671 raeburn 5547: my ($match)=&is_on_map($uri);
5548: if ($match) {
5549: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5550: =~/\Q$priv\E\&([^\:]*)/) {
5551: $thisallowed.=$1;
5552: }
5553: } else {
1.705 albertel 5554: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5555: if ($refuri) {
5556: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5557: $thisallowed='F';
1.671 raeburn 5558: } else {
5559: $refuri=&declutter($refuri);
5560: my ($match) = &is_on_map($refuri);
5561: if ($match) {
5562: $thisallowed='F';
5563: }
1.669 raeburn 5564: }
1.671 raeburn 5565: }
5566: }
1.314 www 5567: }
1.492 albertel 5568:
1.766 albertel 5569: if ($priv eq 'bre'
5570: && $thisallowed ne 'F'
5571: && $thisallowed ne '2'
5572: && &is_portfolio_url($uri)) {
5573: $thisallowed = &portfolio_access($uri);
5574: }
5575:
1.52 www 5576: # Full access at system, domain or course-wide level? Exit.
1.29 www 5577: if ($thisallowed=~/F/) {
5578: return 'F';
5579: }
5580:
1.52 www 5581: # If this is generating or modifying users, exit with special codes
1.29 www 5582:
1.643 www 5583: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5584: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5585: my ($audom,$auname)=split('/',$uri);
1.643 www 5586: # no author name given, so this just checks on the general right to make a co-author in this domain
5587: unless ($auname) { return $thisallowed; }
5588: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5589: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5590: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5591: ($audom ne $env{'request.role.domain'}))) { return ''; }
5592: }
1.52 www 5593: return $thisallowed;
5594: }
5595: #
1.103 harris41 5596: # Gathered so far: system, domain and course wide privileges
1.52 www 5597: #
5598: # Course: See if uri or referer is an individual resource that is part of
5599: # the course
5600:
1.620 albertel 5601: if ($env{'request.course.id'}) {
1.232 www 5602:
1.620 albertel 5603: $courseprivid=$env{'request.course.id'};
5604: if ($env{'request.course.sec'}) {
5605: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5606: }
5607: $courseprivid=~s/\_/\//;
5608: my $checkreferer=1;
1.232 www 5609: my ($match,$cond)=&is_on_map($uri);
5610: if ($match) {
5611: $statecond=$cond;
1.620 albertel 5612: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5613: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5614: $thisallowed.=$1;
5615: $checkreferer=0;
5616: }
1.29 www 5617: }
1.83 www 5618:
1.148 www 5619: if ($checkreferer) {
1.620 albertel 5620: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5621: unless ($refuri) {
1.800 albertel 5622: foreach my $key (keys(%env)) {
5623: if ($key=~/^httpref\..*\*/) {
5624: my $pattern=$key;
1.156 www 5625: $pattern=~s/^httpref\.\/res\///;
1.148 www 5626: $pattern=~s/\*/\[\^\/\]\+/g;
5627: $pattern=~s/\//\\\//g;
1.152 www 5628: if ($orguri=~/$pattern/) {
1.800 albertel 5629: $refuri=$env{$key};
1.148 www 5630: }
5631: }
1.191 harris41 5632: }
1.148 www 5633: }
1.232 www 5634:
1.148 www 5635: if ($refuri) {
1.152 www 5636: $refuri=&declutter($refuri);
1.232 www 5637: my ($match,$cond)=&is_on_map($refuri);
5638: if ($match) {
5639: my $refstatecond=$cond;
1.620 albertel 5640: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5641: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5642: $thisallowed.=$1;
1.53 www 5643: $uri=$refuri;
5644: $statecond=$refstatecond;
1.52 www 5645: }
5646: }
1.148 www 5647: }
1.29 www 5648: }
1.52 www 5649: }
1.29 www 5650:
1.52 www 5651: #
1.103 harris41 5652: # Gathered now: all privileges that could apply, and condition number
1.52 www 5653: #
5654: #
5655: # Full or no access?
5656: #
1.29 www 5657:
1.52 www 5658: if ($thisallowed=~/F/) {
5659: return 'F';
5660: }
1.29 www 5661:
1.52 www 5662: unless ($thisallowed) {
5663: return '';
5664: }
1.29 www 5665:
1.52 www 5666: # Restrictions exist, deal with them
5667: #
5668: # C:according to course preferences
5669: # R:according to resource settings
5670: # L:unless locked
5671: # X:according to user session state
5672: #
5673:
5674: # Possibly locked functionality, check all courses
1.54 www 5675: # Locks might take effect only after 10 minutes cache expiration for other
5676: # courses, and 2 minutes for current course
1.52 www 5677:
5678: my $envkey;
5679: if ($thisallowed=~/L/) {
1.1000 raeburn 5680: foreach $envkey (keys(%env)) {
1.54 www 5681: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5682: my $courseid=$2;
5683: my $roleid=$1.'.'.$2;
1.92 www 5684: $courseid=~s/^\///;
1.54 www 5685: my $expiretime=600;
1.620 albertel 5686: if ($env{'request.role'} eq $roleid) {
1.54 www 5687: $expiretime=120;
5688: }
5689: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5690: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5691: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5692: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5693: }
1.620 albertel 5694: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5695: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5696: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5697: &log($env{'user.domain'},$env{'user.name'},
5698: $env{'user.home'},
1.57 www 5699: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5700: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5701: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5702: return '';
5703: }
5704: }
1.620 albertel 5705: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5706: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5707: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5708: &log($env{'user.domain'},$env{'user.name'},
5709: $env{'user.home'},
1.57 www 5710: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5711: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5712: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5713: return '';
5714: }
5715: }
5716: }
1.29 www 5717: }
1.52 www 5718: }
5719:
5720: #
5721: # Rest of the restrictions depend on selected course
5722: #
5723:
1.620 albertel 5724: unless ($env{'request.course.id'}) {
1.766 albertel 5725: if ($thisallowed eq 'A') {
5726: return 'A';
1.814 raeburn 5727: } elsif ($thisallowed eq 'B') {
5728: return 'B';
1.766 albertel 5729: } else {
5730: return '1';
5731: }
1.52 www 5732: }
1.29 www 5733:
1.52 www 5734: #
5735: # Now user is definitely in a course
5736: #
1.53 www 5737:
5738:
5739: # Course preferences
5740:
5741: if ($thisallowed=~/C/) {
1.620 albertel 5742: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5743: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5744: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5745: =~/\Q$rolecode\E/) {
1.689 albertel 5746: if ($priv ne 'pch') {
5747: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5748: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5749: $env{'request.course.id'});
5750: }
1.237 www 5751: return '';
5752: }
5753:
1.620 albertel 5754: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5755: =~/\Q$unamedom\E/) {
1.689 albertel 5756: if ($priv ne 'pch') {
5757: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5758: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5759: $env{'request.course.id'});
5760: }
1.54 www 5761: return '';
5762: }
1.53 www 5763: }
5764:
5765: # Resource preferences
5766:
5767: if ($thisallowed=~/R/) {
1.620 albertel 5768: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5769: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5770: if ($priv ne 'pch') {
5771: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5772: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5773: }
5774: return '';
1.54 www 5775: }
1.53 www 5776: }
1.30 www 5777:
1.246 www 5778: # Restricted by state or randomout?
1.30 www 5779:
1.52 www 5780: if ($thisallowed=~/X/) {
1.620 albertel 5781: if ($env{'acc.randomout'}) {
1.579 albertel 5782: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5783: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5784: return '';
5785: }
1.247 www 5786: }
5787: if (&condval($statecond)) {
1.52 www 5788: return '2';
5789: } else {
5790: return '';
5791: }
5792: }
1.30 www 5793:
1.766 albertel 5794: if ($thisallowed eq 'A') {
5795: return 'A';
1.814 raeburn 5796: } elsif ($thisallowed eq 'B') {
5797: return 'B';
1.766 albertel 5798: }
1.52 www 5799: return 'F';
1.232 www 5800: }
5801:
1.710 albertel 5802: sub split_uri_for_cond {
5803: my $uri=&deversion(&declutter(shift));
5804: my @uriparts=split(/\//,$uri);
5805: my $filename=pop(@uriparts);
5806: my $pathname=join('/',@uriparts);
5807: return ($pathname,$filename);
5808: }
1.232 www 5809: # --------------------------------------------------- Is a resource on the map?
5810:
5811: sub is_on_map {
1.710 albertel 5812: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5813: #Trying to find the conditional for the file
1.620 albertel 5814: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5815: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5816: if ($match) {
1.289 bowersj2 5817: return (1,$1);
5818: } else {
1.434 www 5819: return (0,0);
1.289 bowersj2 5820: }
1.12 www 5821: }
5822:
1.427 www 5823: # --------------------------------------------------------- Get symb from alias
5824:
5825: sub get_symb_from_alias {
5826: my $symb=shift;
5827: my ($map,$resid,$url)=&decode_symb($symb);
5828: # Already is a symb
5829: if ($url) { return $symb; }
5830: # Must be an alias
5831: my $aliassymb='';
5832: my %bighash;
1.620 albertel 5833: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5834: &GDBM_READER(),0640)) {
5835: my $rid=$bighash{'mapalias_'.$symb};
5836: if ($rid) {
5837: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5838: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5839: $resid,$bighash{'src_'.$rid});
1.427 www 5840: }
5841: untie %bighash;
5842: }
5843: return $aliassymb;
5844: }
5845:
1.12 www 5846: # ----------------------------------------------------------------- Define Role
5847:
5848: sub definerole {
5849: if (allowed('mcr','/')) {
5850: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5851: foreach my $role (split(':',$sysrole)) {
5852: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5853: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5854: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5855: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5856: return "refused:s:$crole&$cqual";
5857: }
5858: }
1.191 harris41 5859: }
1.800 albertel 5860: foreach my $role (split(':',$domrole)) {
5861: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5862: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5863: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5864: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5865: return "refused:d:$crole&$cqual";
5866: }
5867: }
1.191 harris41 5868: }
1.800 albertel 5869: foreach my $role (split(':',$courole)) {
5870: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5871: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5872: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5873: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5874: return "refused:c:$crole&$cqual";
5875: }
5876: }
1.191 harris41 5877: }
1.620 albertel 5878: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5879: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5880: "rolesdef_$rolename=".
5881: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5882: return reply($command,$env{'user.home'});
1.12 www 5883: } else {
5884: return 'refused';
5885: }
1.105 harris41 5886: }
5887:
5888: # ---------------- Make a metadata query against the network of library servers
5889:
5890: sub metadata_query {
1.244 matthew 5891: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5892: my %rhash;
1.845 albertel 5893: my %libserv = &all_library();
1.244 matthew 5894: my @server_list = (defined($server_array) ? @$server_array
5895: : keys(%libserv) );
5896: for my $server (@server_list) {
1.118 harris41 5897: unless ($custom or $customshow) {
5898: my $reply=&reply("querysend:".&escape($query),$server);
5899: $rhash{$server}=$reply;
5900: }
5901: else {
5902: my $reply=&reply("querysend:".&escape($query).':'.
5903: &escape($custom).':'.&escape($customshow),
5904: $server);
5905: $rhash{$server}=$reply;
5906: }
1.112 harris41 5907: }
1.118 harris41 5908: return \%rhash;
1.240 www 5909: }
5910:
5911: # ----------------------------------------- Send log queries and wait for reply
5912:
5913: sub log_query {
5914: my ($uname,$udom,$query,%filters)=@_;
5915: my $uhome=&homeserver($uname,$udom);
5916: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5917: my $uhost=&hostname($uhome);
1.800 albertel 5918: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5919: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5920: $uhome);
1.479 albertel 5921: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5922: return get_query_reply($queryid);
5923: }
5924:
1.818 raeburn 5925: # -------------------------- Update MySQL table for portfolio file
5926:
5927: sub update_portfolio_table {
1.821 raeburn 5928: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5929: if ($group ne '') {
5930: $file_name =~s /^\Q$group\E//;
5931: }
1.818 raeburn 5932: my $homeserver = &homeserver($uname,$udom);
5933: my $queryid=
1.821 raeburn 5934: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5935: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5936: my $reply = &get_query_reply($queryid);
5937: return $reply;
5938: }
5939:
1.899 raeburn 5940: # -------------------------- Update MySQL allusers table
5941:
5942: sub update_allusers_table {
5943: my ($uname,$udom,$names) = @_;
5944: my $homeserver = &homeserver($uname,$udom);
5945: my $queryid=
5946: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5947: 'lastname='.&escape($names->{'lastname'}).'%%'.
5948: 'firstname='.&escape($names->{'firstname'}).'%%'.
5949: 'middlename='.&escape($names->{'middlename'}).'%%'.
5950: 'generation='.&escape($names->{'generation'}).'%%'.
5951: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5952: 'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4 raeburn 5953: return;
1.899 raeburn 5954: }
5955:
1.508 raeburn 5956: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5957:
5958: sub fetch_enrollment_query {
1.511 raeburn 5959: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5960: my $homeserver;
1.547 raeburn 5961: my $maxtries = 1;
1.508 raeburn 5962: if ($context eq 'automated') {
5963: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5964: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5965: } else {
5966: $homeserver = &homeserver($cnum,$dom);
5967: }
1.838 albertel 5968: my $host=&hostname($homeserver);
1.506 raeburn 5969: my $cmd = '';
1.1000 raeburn 5970: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5971: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5972: }
5973: $cmd =~ s/%%$//;
5974: $cmd = &escape($cmd);
5975: my $query = 'fetchenrollment';
1.620 albertel 5976: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5977: unless ($queryid=~/^\Q$host\E\_/) {
5978: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5979: return 'error: '.$queryid;
5980: }
1.506 raeburn 5981: my $reply = &get_query_reply($queryid);
1.547 raeburn 5982: my $tries = 1;
5983: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5984: $reply = &get_query_reply($queryid);
5985: $tries ++;
5986: }
1.526 raeburn 5987: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5988: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5989: } else {
1.901 albertel 5990: my @responses = split(/:/,$reply);
1.515 raeburn 5991: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5992: foreach my $line (@responses) {
5993: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5994: $$replyref{$key} = $value;
5995: }
5996: } else {
1.506 raeburn 5997: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5998: foreach my $line (@responses) {
5999: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6000: $$replyref{$key} = $value;
6001: if ($value > 0) {
1.800 albertel 6002: foreach my $item (@{$$affiliatesref{$key}}) {
6003: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6004: my $destname = $pathname.'/'.$filename;
6005: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6006: if ($xml_classlist =~ /^error/) {
6007: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6008: } else {
1.506 raeburn 6009: if ( open(FILE,">$destname") ) {
6010: print FILE &unescape($xml_classlist);
6011: close(FILE);
1.526 raeburn 6012: } else {
6013: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6014: }
6015: }
6016: }
6017: }
6018: }
6019: }
6020: return 'ok';
6021: }
6022: return 'error';
6023: }
6024:
1.242 www 6025: sub get_query_reply {
6026: my $queryid=shift;
1.240 www 6027: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
6028: my $reply='';
6029: for (1..100) {
6030: sleep 2;
6031: if (-e $replyfile.'.end') {
1.448 albertel 6032: if (open(my $fh,$replyfile)) {
1.904 albertel 6033: $reply = join('',<$fh>);
6034: close($fh);
1.240 www 6035: } else { return 'error: reply_file_error'; }
1.242 www 6036: return &unescape($reply);
6037: }
1.240 www 6038: }
1.242 www 6039: return 'timeout:'.$queryid;
1.240 www 6040: }
6041:
6042: sub courselog_query {
1.241 www 6043: #
6044: # possible filters:
6045: # url: url or symb
6046: # username
6047: # domain
6048: # action: view, submit, grade
6049: # start: timestamp
6050: # end: timestamp
6051: #
1.240 www 6052: my (%filters)=@_;
1.620 albertel 6053: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6054: if ($filters{'url'}) {
6055: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6056: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6057: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6058: }
1.620 albertel 6059: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6060: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6061: return &log_query($cname,$cdom,'courselog',%filters);
6062: }
6063:
6064: sub userlog_query {
1.858 raeburn 6065: #
6066: # possible filters:
6067: # action: log check role
6068: # start: timestamp
6069: # end: timestamp
6070: #
1.240 www 6071: my ($uname,$udom,%filters)=@_;
6072: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6073: }
6074:
1.506 raeburn 6075: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6076:
6077: sub auto_run {
1.508 raeburn 6078: my ($cnum,$cdom) = @_;
1.876 raeburn 6079: my $response = 0;
6080: my $settings;
6081: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6082: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6083: $settings = $domconfig{'autoenroll'};
6084: if ($settings->{'run'} eq '1') {
6085: $response = 1;
6086: }
6087: } else {
1.934 raeburn 6088: my $homeserver;
6089: if (&is_course($cdom,$cnum)) {
6090: $homeserver = &homeserver($cnum,$cdom);
6091: } else {
6092: $homeserver = &domain($cdom,'primary');
6093: }
6094: if ($homeserver ne 'no_host') {
6095: $response = &reply('autorun:'.$cdom,$homeserver);
6096: }
1.876 raeburn 6097: }
1.506 raeburn 6098: return $response;
6099: }
1.776 albertel 6100:
1.506 raeburn 6101: sub auto_get_sections {
1.508 raeburn 6102: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6103: my $homeserver;
6104: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6105: $homeserver = &homeserver($cnum,$cdom);
6106: }
6107: if (!defined($homeserver)) {
6108: if ($cdom =~ /^$match_domain$/) {
6109: $homeserver = &domain($cdom,'primary');
6110: }
6111: }
6112: my @secs;
6113: if (defined($homeserver)) {
6114: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6115: unless ($response eq 'refused') {
6116: @secs = split(/:/,$response);
6117: }
1.506 raeburn 6118: }
6119: return @secs;
6120: }
1.776 albertel 6121:
1.506 raeburn 6122: sub auto_new_course {
1.508 raeburn 6123: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
6124: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 6125: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 6126: return $response;
6127: }
1.776 albertel 6128:
1.506 raeburn 6129: sub auto_validate_courseID {
1.508 raeburn 6130: my ($cnum,$cdom,$inst_course_id) = @_;
6131: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6132: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6133: return $response;
6134: }
1.776 albertel 6135:
1.1007 raeburn 6136: sub auto_validate_instcode {
1.1020 raeburn 6137: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6138: my ($homeserver,$response);
6139: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6140: $homeserver = &homeserver($cnum,$cdom);
6141: }
6142: if (!defined($homeserver)) {
6143: if ($cdom =~ /^$match_domain$/) {
6144: $homeserver = &domain($cdom,'primary');
6145: }
6146: }
1.1056.4.2 raeburn 6147: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6148: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6149: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6150: return ($outcome,$description);
1.1007 raeburn 6151: }
6152:
1.506 raeburn 6153: sub auto_create_password {
1.873 raeburn 6154: my ($cnum,$cdom,$authparam,$udom) = @_;
6155: my ($homeserver,$response);
1.506 raeburn 6156: my $create_passwd = 0;
6157: my $authchk = '';
1.873 raeburn 6158: if ($udom =~ /^$match_domain$/) {
6159: $homeserver = &domain($udom,'primary');
6160: }
6161: if ($homeserver eq '') {
6162: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6163: $homeserver = &homeserver($cnum,$cdom);
6164: }
6165: }
6166: if ($homeserver eq '') {
6167: $authchk = 'nodomain';
1.506 raeburn 6168: } else {
1.873 raeburn 6169: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6170: if ($response eq 'refused') {
6171: $authchk = 'refused';
6172: } else {
1.901 albertel 6173: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6174: }
1.506 raeburn 6175: }
6176: return ($authparam,$create_passwd,$authchk);
6177: }
6178:
1.706 raeburn 6179: sub auto_photo_permission {
6180: my ($cnum,$cdom,$students) = @_;
6181: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6182: my ($outcome,$perm_reqd,$conditions) =
6183: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6184: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6185: return (undef,undef);
6186: }
1.706 raeburn 6187: return ($outcome,$perm_reqd,$conditions);
6188: }
6189:
6190: sub auto_checkphotos {
6191: my ($uname,$udom,$pid) = @_;
6192: my $homeserver = &homeserver($uname,$udom);
6193: my ($result,$resulttype);
6194: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6195: &escape($uname).':'.&escape($pid),
6196: $homeserver));
1.709 albertel 6197: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6198: return (undef,undef);
6199: }
1.706 raeburn 6200: if ($outcome) {
6201: ($result,$resulttype) = split(/:/,$outcome);
6202: }
6203: return ($result,$resulttype);
6204: }
6205:
6206: sub auto_photochoice {
6207: my ($cnum,$cdom) = @_;
6208: my $homeserver = &homeserver($cnum,$cdom);
6209: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6210: &escape($cdom),
6211: $homeserver)));
1.709 albertel 6212: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6213: return (undef,undef);
6214: }
1.706 raeburn 6215: return ($update,$comment);
6216: }
6217:
6218: sub auto_photoupdate {
6219: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6220: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6221: my $host=&hostname($homeserver);
1.706 raeburn 6222: my $cmd = '';
6223: my $maxtries = 1;
1.800 albertel 6224: foreach my $affiliate (keys(%{$affiliatesref})) {
6225: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6226: }
6227: $cmd =~ s/%%$//;
6228: $cmd = &escape($cmd);
6229: my $query = 'institutionalphotos';
6230: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6231: unless ($queryid=~/^\Q$host\E\_/) {
6232: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6233: return 'error: '.$queryid;
6234: }
6235: my $reply = &get_query_reply($queryid);
6236: my $tries = 1;
6237: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6238: $reply = &get_query_reply($queryid);
6239: $tries ++;
6240: }
6241: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6242: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6243: } else {
6244: my @responses = split(/:/,$reply);
6245: my $outcome = shift(@responses);
6246: foreach my $item (@responses) {
6247: my ($key,$value) = split(/=/,$item);
6248: $$photo{$key} = $value;
6249: }
6250: return $outcome;
6251: }
6252: return 'error';
6253: }
6254:
1.521 raeburn 6255: sub auto_instcode_format {
1.793 albertel 6256: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6257: $cat_order) = @_;
1.521 raeburn 6258: my $courses = '';
1.772 raeburn 6259: my @homeservers;
1.521 raeburn 6260: if ($caller eq 'global') {
1.841 albertel 6261: my %servers = &get_servers($codedom,'library');
6262: foreach my $tryserver (keys(%servers)) {
6263: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6264: push(@homeservers,$tryserver);
6265: }
1.584 raeburn 6266: }
1.1022 raeburn 6267: } elsif ($caller eq 'requests') {
6268: if ($codedom =~ /^$match_domain$/) {
6269: my $chome = &domain($codedom,'primary');
6270: unless ($chome eq 'no_host') {
6271: push(@homeservers,$chome);
6272: }
6273: }
1.521 raeburn 6274: } else {
1.772 raeburn 6275: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6276: }
1.793 albertel 6277: foreach my $code (keys(%{$instcodes})) {
6278: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6279: }
6280: chop($courses);
1.772 raeburn 6281: my $ok_response = 0;
6282: my $response;
6283: while (@homeservers > 0 && $ok_response == 0) {
6284: my $server = shift(@homeservers);
6285: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6286: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6287: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6288: split(/:/,$response);
1.772 raeburn 6289: %{$codes} = (%{$codes},&str2hash($codes_str));
6290: push(@{$codetitles},&str2array($codetitles_str));
6291: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6292: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6293: $ok_response = 1;
6294: }
6295: }
6296: if ($ok_response) {
1.521 raeburn 6297: return 'ok';
1.772 raeburn 6298: } else {
6299: return $response;
1.521 raeburn 6300: }
6301: }
6302:
1.792 raeburn 6303: sub auto_instcode_defaults {
6304: my ($domain,$returnhash,$code_order) = @_;
6305: my @homeservers;
1.841 albertel 6306:
6307: my %servers = &get_servers($domain,'library');
6308: foreach my $tryserver (keys(%servers)) {
6309: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6310: push(@homeservers,$tryserver);
6311: }
1.792 raeburn 6312: }
1.841 albertel 6313:
1.792 raeburn 6314: my $response;
1.841 albertel 6315: foreach my $server (@homeservers) {
1.792 raeburn 6316: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6317: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6318:
6319: foreach my $pair (split(/\&/,$response)) {
6320: my ($name,$value)=split(/\=/,$pair);
6321: if ($name eq 'code_order') {
6322: @{$code_order} = split(/\&/,&unescape($value));
6323: } else {
6324: $returnhash->{&unescape($name)}=&unescape($value);
6325: }
6326: }
6327: return 'ok';
1.792 raeburn 6328: }
1.841 albertel 6329:
6330: return $response;
1.1003 raeburn 6331: }
6332:
6333: sub auto_possible_instcodes {
1.1007 raeburn 6334: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6335: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6336: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6337: return;
6338: }
1.1003 raeburn 6339: my (@homeservers,$uhome);
6340: if (defined(&domain($domain,'primary'))) {
6341: $uhome=&domain($domain,'primary');
6342: push(@homeservers,&domain($domain,'primary'));
6343: } else {
6344: my %servers = &get_servers($domain,'library');
6345: foreach my $tryserver (keys(%servers)) {
6346: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6347: push(@homeservers,$tryserver);
6348: }
6349: }
6350: }
6351: my $response;
6352: foreach my $server (@homeservers) {
6353: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6354: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6355: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6356: split(':',$response);
6357: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6358: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6359: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6360: my ($name,$value)=split('=',$item);
6361: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6362: }
6363: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6364: my ($name,$value)=split('=',$item);
6365: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6366: }
6367: return 'ok';
6368: }
6369: return $response;
6370: }
1.792 raeburn 6371:
1.1010 raeburn 6372: sub auto_courserequest_checks {
6373: my ($dom) = @_;
1.1020 raeburn 6374: my ($homeserver,%validations);
6375: if ($dom =~ /^$match_domain$/) {
6376: $homeserver = &domain($dom,'primary');
6377: }
6378: unless ($homeserver eq 'no_host') {
6379: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6380: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6381: my @items = split(/&/,$response);
6382: foreach my $item (@items) {
6383: my ($key,$value) = split('=',$item);
6384: $validations{&unescape($key)} = &thaw_unescape($value);
6385: }
6386: }
6387: }
1.1010 raeburn 6388: return %validations;
6389: }
6390:
1.1020 raeburn 6391: sub auto_courserequest_validation {
6392: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6393: my ($homeserver,$response);
6394: if ($dom =~ /^$match_domain$/) {
6395: $homeserver = &domain($dom,'primary');
6396: }
6397: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6398:
1.1020 raeburn 6399: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6400: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6401: ':'.&escape($instcode).':'.&escape($instseclist),
6402: $homeserver));
6403: }
6404: return $response;
6405: }
6406:
1.777 albertel 6407: sub auto_validate_class_sec {
1.918 raeburn 6408: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6409: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6410: my $ownerlist;
6411: if (ref($owners) eq 'ARRAY') {
6412: $ownerlist = join(',',@{$owners});
6413: } else {
6414: $ownerlist = $owners;
6415: }
1.773 raeburn 6416: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6417: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6418: return $response;
6419: }
6420:
1.679 raeburn 6421: # ------------------------------------------------------- Course Group routines
6422:
6423: sub get_coursegroups {
1.809 raeburn 6424: my ($cdom,$cnum,$group,$namespace) = @_;
6425: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6426: }
6427:
1.679 raeburn 6428: sub modify_coursegroup {
6429: my ($cdom,$cnum,$groupsettings) = @_;
6430: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6431: }
6432:
1.809 raeburn 6433: sub toggle_coursegroup_status {
6434: my ($cdom,$cnum,$group,$action) = @_;
6435: my ($from_namespace,$to_namespace);
6436: if ($action eq 'delete') {
6437: $from_namespace = 'coursegroups';
6438: $to_namespace = 'deleted_groups';
6439: } else {
6440: $from_namespace = 'deleted_groups';
6441: $to_namespace = 'coursegroups';
6442: }
6443: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6444: if (my $tmp = &error(%curr_group)) {
6445: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6446: return ('read error',$tmp);
6447: } else {
6448: my %savedsettings = %curr_group;
1.809 raeburn 6449: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6450: my $deloutcome;
6451: if ($result eq 'ok') {
1.809 raeburn 6452: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6453: } else {
6454: return ('write error',$result);
6455: }
6456: if ($deloutcome eq 'ok') {
6457: return 'ok';
6458: } else {
6459: return ('delete error',$deloutcome);
6460: }
6461: }
6462: }
6463:
1.679 raeburn 6464: sub modify_group_roles {
1.957 raeburn 6465: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6466: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6467: my $role = 'gr/'.&escape($userprivs);
6468: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6469: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6470: if ($result eq 'ok') {
6471: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6472: }
1.679 raeburn 6473: return $result;
6474: }
6475:
6476: sub modify_coursegroup_membership {
6477: my ($cdom,$cnum,$membership) = @_;
6478: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6479: return $result;
6480: }
6481:
1.682 raeburn 6482: sub get_active_groups {
6483: my ($udom,$uname,$cdom,$cnum) = @_;
6484: my $now = time;
6485: my %groups = ();
6486: foreach my $key (keys(%env)) {
1.811 albertel 6487: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6488: my ($start,$end) = split(/\./,$env{$key});
6489: if (($end!=0) && ($end<$now)) { next; }
6490: if (($start!=0) && ($start>$now)) { next; }
6491: if ($1 eq $cdom && $2 eq $cnum) {
6492: $groups{$3} = $env{$key} ;
6493: }
6494: }
6495: }
6496: return %groups;
6497: }
6498:
1.683 raeburn 6499: sub get_group_membership {
6500: my ($cdom,$cnum,$group) = @_;
6501: return(&dump('groupmembership',$cdom,$cnum,$group));
6502: }
6503:
6504: sub get_users_groups {
6505: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6506: my @usersgroups;
1.683 raeburn 6507: my $cachetime=1800;
6508:
6509: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6510: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6511: if (defined($cached)) {
1.734 albertel 6512: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6513: } else {
6514: $grouplist = '';
1.816 raeburn 6515: my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 6516: my $extra = &freeze_escape({'skipcheck' => 1});
6517: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6518: my $access_end = $env{'course.'.$courseid.
6519: '.default_enrollment_end_date'};
6520: my $now = time;
6521: foreach my $key (keys(%roleshash)) {
6522: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6523: my $group = $1;
6524: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6525: my $start = $2;
6526: my $end = $1;
6527: if ($start == -1) { next; } # deleted from group
6528: if (($start!=0) && ($start>$now)) { next; }
6529: if (($end!=0) && ($end<$now)) {
6530: if ($access_end && $access_end < $now) {
6531: if ($access_end - $end < 86400) {
6532: push(@usersgroups,$group);
1.733 raeburn 6533: }
6534: }
1.817 raeburn 6535: next;
1.733 raeburn 6536: }
1.817 raeburn 6537: push(@usersgroups,$group);
1.683 raeburn 6538: }
6539: }
6540: }
1.817 raeburn 6541: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6542: $grouplist = join(':',@usersgroups);
6543: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6544: }
1.733 raeburn 6545: return @usersgroups;
1.683 raeburn 6546: }
6547:
6548: sub devalidate_getgroups_cache {
6549: my ($udom,$uname,$cdom,$cnum)=@_;
6550: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6551:
1.683 raeburn 6552: my $hashid="$udom:$uname:$courseid";
6553: &devalidate_cache_new('getgroups',$hashid);
6554: }
6555:
1.12 www 6556: # ------------------------------------------------------------------ Plain Text
6557:
6558: sub plaintext {
1.988 raeburn 6559: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6560: if ($short =~ m{^cr/}) {
1.758 albertel 6561: return (split('/',$short))[-1];
6562: }
1.742 raeburn 6563: if (!defined($cid)) {
6564: $cid = $env{'request.course.id'};
6565: }
6566: my %rolenames = (
1.1008 raeburn 6567: Course => 'std',
6568: Community => 'alt1',
1.742 raeburn 6569: );
1.1037 raeburn 6570: if ($cid ne '') {
6571: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6572: unless ($forcedefault) {
6573: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6574: &Apache::lonlocal::mt_escape(\$roletext);
6575: return &Apache::lonlocal::mt($roletext);
6576: }
6577: }
6578: }
6579: if ((defined($type)) && (defined($rolenames{$type})) &&
6580: (defined($rolenames{$type})) &&
6581: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6582: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6583: } elsif ($cid ne '') {
6584: my $crstype = $env{'course.'.$cid.'.type'};
6585: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6586: (defined($prp{$short}{$rolenames{$crstype}}))) {
6587: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6588: }
1.742 raeburn 6589: }
1.1037 raeburn 6590: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6591: }
6592:
6593: # ----------------------------------------------------------------- Assign Role
6594:
6595: sub assignrole {
1.957 raeburn 6596: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6597: $context)=@_;
1.21 www 6598: my $mrole;
6599: if ($role =~ /^cr\//) {
1.393 www 6600: my $cwosec=$url;
1.811 albertel 6601: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6602: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6603: my $refused = 1;
6604: if ($context eq 'requestcourses') {
6605: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6606: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6607: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6608: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6609: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6610: if ($crsenv{'internal.courseowner'} eq
6611: $env{'user.name'}.':'.$env{'user.domain'}) {
6612: $refused = '';
6613: }
6614: }
6615: }
6616: }
6617: }
6618: if ($refused) {
6619: &logthis('Refused custom assignrole: '.
6620: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6621: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6622: return 'refused';
6623: }
1.104 www 6624: }
1.21 www 6625: $mrole='cr';
1.678 raeburn 6626: } elsif ($role =~ /^gr\//) {
6627: my $cwogrp=$url;
1.811 albertel 6628: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6629: unless (&allowed('mdg',$cwogrp)) {
6630: &logthis('Refused group assignrole: '.
6631: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6632: $env{'user.name'}.' at '.$env{'user.domain'});
6633: return 'refused';
6634: }
6635: $mrole='gr';
1.21 www 6636: } else {
1.82 www 6637: my $cwosec=$url;
1.811 albertel 6638: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6639: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6640: my $refused;
6641: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6642: if (!(&allowed('c'.$role,$url))) {
6643: $refused = 1;
6644: }
6645: } else {
6646: $refused = 1;
6647: }
1.947 raeburn 6648: if ($refused) {
1.1045 raeburn 6649: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6650: if (!$selfenroll && $context eq 'course') {
6651: my %crsenv;
6652: if ($role eq 'cc' || $role eq 'co') {
6653: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6654: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6655: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6656: if ($crsenv{'internal.courseowner'} eq
6657: $env{'user.name'}.':'.$env{'user.domain'}) {
6658: $refused = '';
6659: }
6660: }
6661: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6662: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6663: if ($crsenv{'internal.courseowner'} eq
6664: $env{'user.name'}.':'.$env{'user.domain'}) {
6665: $refused = '';
6666: }
6667: }
6668: }
6669: }
6670: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6671: $refused = '';
1.1017 raeburn 6672: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6673: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6674: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6675: my $wrongcc;
6676: if ($cnum =~ /^$match_community$/) {
6677: $wrongcc = 1 if ($role eq 'cc');
6678: } else {
6679: $wrongcc = 1 if ($role eq 'co');
6680: }
6681: unless ($wrongcc) {
6682: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6683: if ($crsenv{'internal.courseowner'} eq
6684: $env{'user.name'}.':'.$env{'user.domain'}) {
6685: $refused = '';
6686: }
1.1017 raeburn 6687: }
6688: }
6689: }
6690: if ($refused) {
1.947 raeburn 6691: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6692: ' '.$role.' '.$end.' '.$start.' by '.
6693: $env{'user.name'}.' at '.$env{'user.domain'});
6694: return 'refused';
6695: }
1.932 raeburn 6696: }
1.104 www 6697: }
1.21 www 6698: $mrole=$role;
6699: }
1.620 albertel 6700: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6701: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6702: if ($end) { $command.='_'.$end; }
1.21 www 6703: if ($start) {
6704: if ($end) {
1.81 www 6705: $command.='_'.$start;
1.21 www 6706: } else {
1.81 www 6707: $command.='_0_'.$start;
1.21 www 6708: }
6709: }
1.739 raeburn 6710: my $origstart = $start;
6711: my $origend = $end;
1.957 raeburn 6712: my $delflag;
1.357 www 6713: # actually delete
6714: if ($deleteflag) {
1.373 www 6715: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6716: # modify command to delete the role
1.620 albertel 6717: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6718: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6719: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6720: # set start and finish to negative values for userrolelog
6721: $start=-1;
6722: $end=-1;
1.957 raeburn 6723: $delflag = 1;
1.357 www 6724: }
6725: }
6726: # send command
1.349 www 6727: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6728: # log new user role if status is ok
1.349 www 6729: if ($answer eq 'ok') {
1.663 raeburn 6730: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6731: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6732: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6733: unless ($role =~ /^gr/) {
6734: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6735: $origstart,$selfenroll,$context);
1.739 raeburn 6736: }
1.1053 raeburn 6737: if ($role eq 'cc') {
6738: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6739: }
1.349 www 6740: }
6741: return $answer;
1.169 harris41 6742: }
6743:
1.1053 raeburn 6744: sub autoupdate_coowners {
6745: my ($url,$end,$start,$uname,$udom) = @_;
6746: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6747: if (($cdom ne '') && ($cnum ne '')) {
6748: my $now = time;
6749: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6750: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6751: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6752: my $instcode = $coursehash{'internal.coursecode'};
6753: if ($instcode ne '') {
1.1056 raeburn 6754: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6755: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6756: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6757: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6758: if ($result eq 'valid') {
6759: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6760: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6761: push(@newcoowners,$coowner);
6762: }
6763: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6764: push(@newcoowners,$uname.':'.$udom);
6765: }
6766: @newcoowners = sort(@newcoowners);
6767: } else {
6768: push(@newcoowners,$uname.':'.$udom);
6769: }
6770: } else {
6771: if ($coursehash{'internal.co-owners'}) {
6772: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6773: unless ($coowner eq $uname.':'.$udom) {
6774: push(@newcoowners,$coowner);
6775: }
6776: }
6777: unless (@newcoowners > 0) {
6778: $delcoowners = 1;
6779: $coowners = '';
6780: }
6781: }
6782: }
6783: if (@newcoowners || $delcoowners) {
6784: &store_coowners($cdom,$cnum,$coursehash{'home'},
6785: $delcoowners,@newcoowners);
6786: }
6787: }
6788: }
6789: }
6790: }
6791: }
6792: }
6793:
6794: sub store_coowners {
6795: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6796: my $cid = $cdom.'_'.$cnum;
6797: my ($coowners,$delresult,$putresult);
6798: if (@newcoowners) {
6799: $coowners = join(',',@newcoowners);
6800: my %coownershash = (
6801: 'internal.co-owners' => $coowners,
6802: );
6803: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6804: if ($putresult eq 'ok') {
6805: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6806: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6807: }
6808: }
6809: }
6810: if ($delcoowners) {
6811: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6812: if ($delresult eq 'ok') {
6813: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6814: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6815: }
6816: }
6817: }
6818: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6819: my %crsinfo =
6820: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6821: if (ref($crsinfo{$cid}) eq 'HASH') {
6822: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6823: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6824: }
6825: }
6826: }
6827:
1.169 harris41 6828: # -------------------------------------------------- Modify user authentication
1.197 www 6829: # Overrides without validation
6830:
1.169 harris41 6831: sub modifyuserauth {
6832: my ($udom,$uname,$umode,$upass)=@_;
6833: my $uhome=&homeserver($uname,$udom);
1.197 www 6834: unless (&allowed('mau',$udom)) { return 'refused'; }
6835: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6836: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6837: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6838: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6839: &escape($upass),$uhome);
1.620 albertel 6840: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6841: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6842: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6843: &log($udom,,$uname,$uhome,
1.620 albertel 6844: 'Authentication changed by '.$env{'user.domain'}.', '.
6845: $env{'user.name'}.', '.$umode.
1.197 www 6846: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6847: unless ($reply eq 'ok') {
1.197 www 6848: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6849: return 'error: '.$reply;
6850: }
1.170 harris41 6851: return 'ok';
1.80 www 6852: }
6853:
1.81 www 6854: # --------------------------------------------------------------- Modify a user
1.80 www 6855:
1.81 www 6856: sub modifyuser {
1.206 matthew 6857: my ($udom, $uname, $uid,
6858: $umode, $upass, $first,
6859: $middle, $last, $gene,
1.1056.4.1 raeburn 6860: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6861: $udom= &LONCAPA::clean_domain($udom);
6862: $uname=&LONCAPA::clean_username($uname);
1.1056.4.1 raeburn 6863: my $showcandelete = 'none';
6864: if (ref($candelete) eq 'ARRAY') {
6865: if (@{$candelete} > 0) {
6866: $showcandelete = join(', ',@{$candelete});
6867: }
6868: }
1.81 www 6869: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6870: $umode.', '.$first.', '.$middle.', '.
1.1056.4.1 raeburn 6871: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6872: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6873: ' desiredhome not specified').
1.620 albertel 6874: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6875: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6876: my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4 raeburn 6877: my $newuser;
6878: if ($uhome eq 'no_host') {
6879: $newuser = 1;
6880: }
1.80 www 6881: # ----------------------------------------------------------------- Create User
1.406 albertel 6882: if (($uhome eq 'no_host') &&
6883: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6884: my $unhome='';
1.844 albertel 6885: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6886: $unhome = $desiredhome;
1.620 albertel 6887: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6888: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6889: } else { # load balancing routine for determining $unhome
1.81 www 6890: my $loadm=10000000;
1.841 albertel 6891: my %servers = &get_servers($udom,'library');
6892: foreach my $tryserver (keys(%servers)) {
6893: my $answer=reply('load',$tryserver);
6894: if (($answer=~/\d+/) && ($answer<$loadm)) {
6895: $loadm=$answer;
6896: $unhome=$tryserver;
6897: }
1.80 www 6898: }
6899: }
6900: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6901: return 'error: unable to find a home server for '.$uname.
6902: ' in domain '.$udom;
1.80 www 6903: }
6904: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6905: &escape($upass),$unhome);
6906: unless ($reply eq 'ok') {
6907: return 'error: '.$reply;
6908: }
1.230 stredwic 6909: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6910: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6911: return 'error: unable verify users home machine.';
1.80 www 6912: }
1.209 matthew 6913: } # End of creation of new user
1.80 www 6914: # ---------------------------------------------------------------------- Add ID
6915: if ($uid) {
6916: $uid=~tr/A-Z/a-z/;
6917: my %uidhash=&idrget($udom,$uname);
1.196 www 6918: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6919: && (!$forceid)) {
1.80 www 6920: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6921: return 'error: user id "'.$uid.'" does not match '.
6922: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6923: }
6924: } else {
6925: &idput($udom,($uname => $uid));
6926: }
6927: }
6928: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6929: my @tmp=&get('environment',
1.899 raeburn 6930: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6931: 'permanentemail','inststatus'],
1.134 albertel 6932: $udom,$uname);
1.1056.4.4 raeburn 6933: my (%names,%oldnames);
1.313 matthew 6934: if ($tmp[0] =~ m/^error:.*/) {
6935: %names=();
6936: } else {
6937: %names = @tmp;
1.1056.4.4 raeburn 6938: %oldnames = %names;
1.313 matthew 6939: }
1.1056.4.6 raeburn 6940: #
1.1056.4.1 raeburn 6941: # If name, email and/or uid are blank (e.g., because an uploaded file
6942: # of users did not contain them), do not overwrite existing values
6943: # unless field is in $candelete array ref.
6944: #
6945:
6946: my @fields = ('firstname','middlename','lastname','generation',
6947: 'permanentemail','id');
6948: my %newvalues;
6949: if (ref($candelete) eq 'ARRAY') {
6950: foreach my $field (@fields) {
6951: if (grep(/^\Q$field\E$/,@{$candelete})) {
6952: if ($field eq 'firstname') {
6953: $names{$field} = $first;
6954: } elsif ($field eq 'middlename') {
6955: $names{$field} = $middle;
6956: } elsif ($field eq 'lastname') {
6957: $names{$field} = $last;
6958: } elsif ($field eq 'generation') {
6959: $names{$field} = $gene;
6960: } elsif ($field eq 'permanentemail') {
6961: $names{$field} = $email;
6962: } elsif ($field eq 'id') {
6963: $names{$field} = $uid;
6964: }
6965: }
6966: }
6967: }
1.388 www 6968: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6969: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6970: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6971: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6972: if ($email) {
6973: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6974: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6975: }
1.899 raeburn 6976: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6977: if (defined($inststatus)) {
6978: $names{'inststatus'} = '';
6979: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6980: if (ref($usertypes) eq 'HASH') {
6981: my @okstatuses;
6982: foreach my $item (split(/:/,$inststatus)) {
6983: if (defined($usertypes->{$item})) {
6984: push(@okstatuses,$item);
6985: }
6986: }
6987: if (@okstatuses) {
6988: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6989: }
6990: }
6991: }
1.1056.4.4 raeburn 6992: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6993: $umode.', '.$first.', '.$middle.', '.
1.1056.4.4 raeburn 6994: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6995: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6996: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6997: } else {
6998: $logmsg .= ' during self creation';
6999: }
1.1056.4.4 raeburn 7000: my $changed;
7001: if ($newuser) {
7002: $changed = 1;
7003: } else {
7004: foreach my $field (@fields) {
7005: if ($names{$field} ne $oldnames{$field}) {
7006: $changed = 1;
7007: last;
7008: }
7009: }
7010: }
7011: unless ($changed) {
7012: $logmsg = 'No changes in user information needed for: '.$logmsg;
7013: &logthis($logmsg);
7014: return 'ok';
7015: }
7016: my $reply = &put('environment', \%names, $udom,$uname);
7017: if ($reply ne 'ok') {
7018: return 'error: '.$reply;
7019: }
1.1056.4.11 raeburn 7020: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7021: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7022: }
1.1056.4.4 raeburn 7023: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7024: &devalidate_cache_new('namescache',$uname.':'.$udom);
7025: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7026: &logthis($logmsg);
1.134 albertel 7027: return 'ok';
1.80 www 7028: }
7029:
1.81 www 7030: # -------------------------------------------------------------- Modify student
1.80 www 7031:
1.81 www 7032: sub modifystudent {
7033: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7034: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7035: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7036: if (!$cid) {
1.620 albertel 7037: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7038: return 'not_in_class';
7039: }
1.80 www 7040: }
7041: # --------------------------------------------------------------- Make the user
1.81 www 7042: my $reply=&modifyuser
1.209 matthew 7043: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7044: $desiredhome,$email,$inststatus);
1.80 www 7045: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7046: # This will cause &modify_student_enrollment to get the uid from the
7047: # students environment
7048: $uid = undef if (!$forceid);
1.455 albertel 7049: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7050: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7051: return $reply;
7052: }
7053:
7054: sub modify_student_enrollment {
1.957 raeburn 7055: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7056: my ($cdom,$cnum,$chome);
7057: if (!$cid) {
1.620 albertel 7058: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7059: return 'not_in_class';
7060: }
1.620 albertel 7061: $cdom=$env{'course.'.$cid.'.domain'};
7062: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7063: } else {
7064: ($cdom,$cnum)=split(/_/,$cid);
7065: }
1.620 albertel 7066: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7067: if (!$chome) {
1.457 raeburn 7068: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7069: }
1.455 albertel 7070: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7071: # Make sure the user exists
1.81 www 7072: my $uhome=&homeserver($uname,$udom);
7073: if (($uhome eq '') || ($uhome eq 'no_host')) {
7074: return 'error: no such user';
7075: }
1.297 matthew 7076: # Get student data if we were not given enough information
7077: if (!defined($first) || $first eq '' ||
7078: !defined($last) || $last eq '' ||
7079: !defined($uid) || $uid eq '' ||
7080: !defined($middle) || $middle eq '' ||
7081: !defined($gene) || $gene eq '') {
1.294 matthew 7082: # They did not supply us with enough data to enroll the student, so
7083: # we need to pick up more information.
1.297 matthew 7084: my %tmp = &get('environment',
1.294 matthew 7085: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7086: ,$udom,$uname);
7087:
1.800 albertel 7088: #foreach my $key (keys(%tmp)) {
7089: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7090: #}
1.294 matthew 7091: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7092: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7093: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7094: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7095: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7096: }
1.556 albertel 7097: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7098: my $reply=cput('classlist',
7099: {"$uname:$udom" =>
1.515 raeburn 7100: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7101: $cdom,$cnum);
1.81 www 7102: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7103: return 'error: '.$reply;
1.652 albertel 7104: } else {
7105: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7106: }
1.297 matthew 7107: # Add student role to user
1.83 www 7108: my $uurl='/'.$cid;
1.81 www 7109: $uurl=~s/\_/\//g;
7110: if ($usec) {
7111: $uurl.='/'.$usec;
7112: }
1.957 raeburn 7113: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7114: }
7115:
1.556 albertel 7116: sub format_name {
7117: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7118: my $name;
7119: if ($first ne 'lastname') {
7120: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7121: } else {
7122: if ($lastname=~/\S/) {
7123: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7124: $name=~s/\s+,/,/;
7125: } else {
7126: $name.= $firstname.' '.$middlename.' '.$generation;
7127: }
7128: }
7129: $name=~s/^\s+//;
7130: $name=~s/\s+$//;
7131: $name=~s/\s+/ /g;
7132: return $name;
7133: }
7134:
1.84 www 7135: # ------------------------------------------------- Write to course preferences
7136:
7137: sub writecoursepref {
7138: my ($courseid,%prefs)=@_;
7139: $courseid=~s/^\///;
7140: $courseid=~s/\_/\//g;
7141: my ($cdomain,$cnum)=split(/\//,$courseid);
7142: my $chome=homeserver($cnum,$cdomain);
7143: if (($chome eq '') || ($chome eq 'no_host')) {
7144: return 'error: no such course';
7145: }
7146: my $cstring='';
1.800 albertel 7147: foreach my $pref (keys(%prefs)) {
7148: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7149: }
1.84 www 7150: $cstring=~s/\&$//;
7151: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7152: }
7153:
7154: # ---------------------------------------------------------- Make/modify course
7155:
7156: sub createcourse {
1.741 raeburn 7157: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7158: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7159: $url=&declutter($url);
7160: my $cid='';
1.1028 raeburn 7161: if ($context eq 'requestcourses') {
7162: my $can_create = 0;
7163: my ($ownername,$ownerdom) = split(':',$course_owner);
7164: if ($udom eq $ownerdom) {
7165: if (&usertools_access($ownername,$ownerdom,$category,undef,
7166: $context)) {
7167: $can_create = 1;
7168: }
7169: } else {
7170: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7171: $category);
7172: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7173: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7174: if (@curr > 0) {
7175: my @options = qw(approval validate autolimit);
7176: my $optregex = join('|',@options);
7177: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7178: $can_create = 1;
7179: }
7180: }
7181: }
7182: }
7183: if ($can_create) {
7184: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7185: unless (&allowed('ccc',$udom)) {
7186: return 'refused';
7187: }
1.1017 raeburn 7188: }
7189: } else {
7190: return 'refused';
7191: }
1.1028 raeburn 7192: } elsif (!&allowed('ccc',$udom)) {
7193: return 'refused';
1.84 www 7194: }
1.1011 raeburn 7195: # --------------------------------------------------------------- Get Unique ID
7196: my $uname;
7197: if ($cnum =~ /^$match_courseid$/) {
7198: my $chome=&homeserver($cnum,$udom,'true');
7199: if (($chome eq '') || ($chome eq 'no_host')) {
7200: $uname = $cnum;
7201: } else {
1.1038 raeburn 7202: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7203: }
7204: } else {
1.1038 raeburn 7205: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7206: }
7207: return $uname if ($uname =~ /^error/);
7208: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7209: if (!defined($course_server)) {
7210: if (defined(&domain($udom,'primary'))) {
7211: $course_server = &domain($udom,'primary');
7212: } else {
7213: $course_server = $env{'user.home'};
7214: }
7215: }
7216: my %host_servers =
7217: &Apache::lonnet::get_servers($udom,'library');
7218: unless ($host_servers{$course_server}) {
7219: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7220: }
1.84 www 7221: # ------------------------------------------------------------- Make the course
7222: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7223: $course_server);
1.84 www 7224: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7225: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7226: if (($uhome eq '') || ($uhome eq 'no_host')) {
7227: return 'error: no such course';
7228: }
1.271 www 7229: # ----------------------------------------------------------------- Course made
1.516 raeburn 7230: # log existence
1.1029 raeburn 7231: my $now = time;
1.918 raeburn 7232: my $newcourse = {
7233: $udom.'_'.$uname => {
1.921 raeburn 7234: description => $description,
7235: inst_code => $inst_code,
7236: owner => $course_owner,
7237: type => $crstype,
1.1029 raeburn 7238: creator => $env{'user.name'}.':'.
7239: $env{'user.domain'},
7240: created => $now,
7241: context => $context,
1.918 raeburn 7242: },
7243: };
1.921 raeburn 7244: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7245: # set toplevel url
1.271 www 7246: my $topurl=$url;
7247: unless ($nonstandard) {
7248: # ------------------------------------------ For standard courses, make top url
7249: my $mapurl=&clutter($url);
1.278 www 7250: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7251: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7252: <map>
7253: <resource id="1" type="start"></resource>
7254: <resource id="2" src="$mapurl"></resource>
7255: <resource id="3" type="finish"></resource>
7256: <link index="1" from="1" to="2"></link>
7257: <link index="2" from="2" to="3"></link>
7258: </map>
7259: ENDINITMAP
7260: $topurl=&declutter(
1.638 albertel 7261: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7262: );
7263: }
7264: # ----------------------------------------------------------- Write preferences
1.84 www 7265: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7266: ('description' => $description,
7267: 'url' => $topurl,
7268: 'internal.creator' => $env{'user.name'}.':'.
7269: $env{'user.domain'},
7270: 'internal.created' => $now,
7271: 'internal.creationcontext' => $context)
7272: );
1.84 www 7273: return '/'.$udom.'/'.$uname;
7274: }
7275:
1.1011 raeburn 7276: # ------------------------------------------------------------------- Create ID
7277: sub generate_coursenum {
1.1038 raeburn 7278: my ($udom,$crstype) = @_;
1.1011 raeburn 7279: my $domdesc = &domain($udom);
7280: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7281: my $first;
7282: if ($crstype eq 'Community') {
7283: $first = '0';
7284: } else {
7285: $first = int(1+rand(9));
7286: }
7287: my $uname=$first.
1.1011 raeburn 7288: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7289: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7290: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7291: # ----------------------------------------------- Make sure that does not exist
7292: my $uhome=&homeserver($uname,$udom,'true');
7293: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7294: if ($crstype eq 'Community') {
7295: $first = '0';
7296: } else {
7297: $first = int(1+rand(9));
7298: }
7299: $uname=$first.
1.1011 raeburn 7300: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7301: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7302: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7303: $uhome=&homeserver($uname,$udom,'true');
7304: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7305: return 'error: unable to generate unique course-ID';
7306: }
7307: }
7308: return $uname;
7309: }
7310:
1.813 albertel 7311: sub is_course {
7312: my ($cdom,$cnum) = @_;
7313: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7314: undef,'.');
1.813 albertel 7315: if (exists($courses{$cdom.'_'.$cnum})) {
7316: return 1;
7317: }
7318: return 0;
7319: }
7320:
1.1015 raeburn 7321: sub store_userdata {
7322: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7323: my $result;
1.1016 raeburn 7324: if ($datakey ne '') {
1.1013 raeburn 7325: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7326: if ($udom eq '' || $uname eq '') {
7327: $udom = $env{'user.domain'};
7328: $uname = $env{'user.name'};
7329: }
7330: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7331: if (($uhome eq '') || ($uhome eq 'no_host')) {
7332: $result = 'error: no_host';
7333: } else {
7334: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7335: $storehash->{'host'} = $perlvar{'lonHostID'};
7336:
7337: my $namevalue='';
7338: foreach my $key (keys(%{$storehash})) {
7339: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7340: }
7341: $namevalue=~s/\&$//;
7342: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7343: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7344: }
7345: } else {
7346: $result = 'error: data to store was not a hash reference';
7347: }
7348: } else {
7349: $result= 'error: invalid requestkey';
7350: }
7351: return $result;
7352: }
7353:
1.21 www 7354: # ---------------------------------------------------------- Assign Custom Role
7355:
7356: sub assigncustomrole {
1.957 raeburn 7357: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7358: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7359: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7360: }
7361:
7362: # ----------------------------------------------------------------- Revoke Role
7363:
7364: sub revokerole {
1.957 raeburn 7365: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7366: my $now=time;
1.965 raeburn 7367: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7368: }
7369:
7370: # ---------------------------------------------------------- Revoke Custom Role
7371:
7372: sub revokecustomrole {
1.957 raeburn 7373: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7374: my $now=time;
1.357 www 7375: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7376: $deleteflag,$selfenroll,$context);
1.17 www 7377: }
7378:
1.533 banghart 7379: # ------------------------------------------------------------ Disk usage
1.535 albertel 7380: sub diskusage {
1.955 raeburn 7381: my ($udom,$uname,$directorypath,$getpropath)=@_;
7382: $directorypath =~ s/\/$//;
7383: my $listing=&reply('du2:'.&escape($directorypath).':'
7384: .&escape($getpropath).':'.&escape($uname).':'
7385: .&escape($udom),homeserver($uname,$udom));
7386: if ($listing eq 'unknown_cmd') {
7387: if ($getpropath) {
7388: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7389: }
7390: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7391: }
1.514 albertel 7392: return $listing;
1.512 banghart 7393: }
7394:
1.566 banghart 7395: sub is_locked {
7396: my ($file_name, $domain, $user) = @_;
7397: my @check;
7398: my $is_locked;
1.1056.4.14 raeburn 7399: push(@check,$file_name);
1.613 albertel 7400: my %locked = &get('file_permissions',\@check,
1.620 albertel 7401: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7402: my ($tmp)=keys(%locked);
7403: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7404:
1.566 banghart 7405: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7406: $is_locked = 'false';
7407: foreach my $entry (@{$locked{$file_name}}) {
7408: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7409: $is_locked = 'true';
7410: last;
1.745 raeburn 7411: }
7412: }
1.566 banghart 7413: } else {
7414: $is_locked = 'false';
7415: }
1.1056.4.14 raeburn 7416: return $is_locked;
1.566 banghart 7417: }
7418:
1.759 albertel 7419: sub declutter_portfile {
7420: my ($file) = @_;
1.833 albertel 7421: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7422: return $file;
7423: }
7424:
1.559 banghart 7425: # ------------------------------------------------------------- Mark as Read Only
7426:
7427: sub mark_as_readonly {
7428: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7429: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7430: my ($tmp)=keys(%current_permissions);
7431: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7432: foreach my $file (@{$files}) {
1.759 albertel 7433: $file = &declutter_portfile($file);
1.561 banghart 7434: push(@{$current_permissions{$file}},$what);
1.559 banghart 7435: }
1.613 albertel 7436: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7437: return;
7438: }
7439:
1.572 banghart 7440: # ------------------------------------------------------------Save Selected Files
7441:
7442: sub save_selected_files {
7443: my ($user, $path, @files) = @_;
7444: my $filename = $user."savedfiles";
1.573 banghart 7445: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7446: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7447: foreach my $file (@files) {
1.620 albertel 7448: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7449: }
7450: foreach my $file (@other_files) {
1.574 banghart 7451: print (OUT $file."\n");
1.572 banghart 7452: }
1.574 banghart 7453: close (OUT);
1.572 banghart 7454: return 'ok';
7455: }
7456:
1.574 banghart 7457: sub clear_selected_files {
7458: my ($user) = @_;
7459: my $filename = $user."savedfiles";
7460: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7461: print (OUT undef);
7462: close (OUT);
7463: return ("ok");
7464: }
7465:
1.572 banghart 7466: sub files_in_path {
7467: my ($user, $path) = @_;
7468: my $filename = $user."savedfiles";
7469: my %return_files;
1.574 banghart 7470: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7471: while (my $line_in = <IN>) {
1.574 banghart 7472: chomp ($line_in);
7473: my @paths_and_file = split (m!/!, $line_in);
7474: my $file_part = pop (@paths_and_file);
7475: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7476: $path_part.='/';
7477: my $path_and_file = $path_part.$file_part;
7478: if ($path_part eq $path) {
7479: $return_files{$file_part}= 'selected';
7480: }
7481: }
1.574 banghart 7482: close (IN);
7483: return (\%return_files);
1.572 banghart 7484: }
7485:
7486: # called in portfolio select mode, to show files selected NOT in current directory
7487: sub files_not_in_path {
7488: my ($user, $path) = @_;
7489: my $filename = $user."savedfiles";
7490: my @return_files;
7491: my $path_part;
1.800 albertel 7492: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7493: while (my $line = <IN>) {
1.572 banghart 7494: #ok, I know it's clunky, but I want it to work
1.800 albertel 7495: my @paths_and_file = split(m|/|, $line);
7496: my $file_part = pop(@paths_and_file);
7497: chomp($file_part);
7498: my $path_part = join('/', @paths_and_file);
1.572 banghart 7499: $path_part .= '/';
7500: my $path_and_file = $path_part.$file_part;
7501: if ($path_part ne $path) {
1.800 albertel 7502: push(@return_files, ($path_and_file));
1.572 banghart 7503: }
7504: }
1.800 albertel 7505: close(OUT);
1.574 banghart 7506: return (@return_files);
1.572 banghart 7507: }
7508:
1.745 raeburn 7509: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7510:
1.745 raeburn 7511: sub get_portfile_permissions {
7512: my ($domain,$user) = @_;
1.613 albertel 7513: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7514: my ($tmp)=keys(%current_permissions);
7515: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7516: return \%current_permissions;
7517: }
7518:
7519: #---------------------------------------------Get portfolio file access controls
7520:
1.749 raeburn 7521: sub get_access_controls {
1.745 raeburn 7522: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7523: my %access;
7524: my $real_file = $file;
7525: $file =~ s/\.meta$//;
1.745 raeburn 7526: if (defined($file)) {
1.749 raeburn 7527: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7528: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7529: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7530: }
7531: }
1.745 raeburn 7532: } else {
1.749 raeburn 7533: foreach my $key (keys(%{$current_permissions})) {
7534: if ($key =~ /\0accesscontrol$/) {
7535: if (defined($group)) {
7536: if ($key !~ m-^\Q$group\E/-) {
7537: next;
7538: }
7539: }
7540: my ($fullpath) = split(/\0/,$key);
7541: if (ref($$current_permissions{$key}) eq 'HASH') {
7542: foreach my $control (keys(%{$$current_permissions{$key}})) {
7543: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7544: }
7545: }
7546: }
7547: }
7548: }
7549: return %access;
7550: }
7551:
7552: sub modify_access_controls {
7553: my ($file_name,$changes,$domain,$user)=@_;
7554: my ($outcome,$deloutcome);
7555: my %store_permissions;
7556: my %new_values;
7557: my %new_control;
7558: my %translation;
7559: my @deletions = ();
7560: my $now = time;
7561: if (exists($$changes{'activate'})) {
7562: if (ref($$changes{'activate'}) eq 'HASH') {
7563: my @newitems = sort(keys(%{$$changes{'activate'}}));
7564: my $numnew = scalar(@newitems);
7565: for (my $i=0; $i<$numnew; $i++) {
7566: my $newkey = $newitems[$i];
7567: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7568: if ($newkey =~ /^\d+:/) {
7569: $newkey =~ s/^(\d+)/$newid/;
7570: $translation{$1} = $newid;
7571: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7572: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7573: $translation{$1} = $newid;
7574: }
1.749 raeburn 7575: $new_values{$file_name."\0".$newkey} =
7576: $$changes{'activate'}{$newitems[$i]};
7577: $new_control{$newkey} = $now;
7578: }
7579: }
7580: }
7581: my %todelete;
7582: my %changed_items;
7583: foreach my $action ('delete','update') {
7584: if (exists($$changes{$action})) {
7585: if (ref($$changes{$action}) eq 'HASH') {
7586: foreach my $key (keys(%{$$changes{$action}})) {
7587: my ($itemnum) = ($key =~ /^([^:]+):/);
7588: if ($action eq 'delete') {
7589: $todelete{$itemnum} = 1;
7590: } else {
7591: $changed_items{$itemnum} = $key;
7592: }
7593: }
1.745 raeburn 7594: }
7595: }
1.749 raeburn 7596: }
7597: # get lock on access controls for file.
7598: my $lockhash = {
7599: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7600: ':'.$env{'user.domain'},
7601: };
7602: my $tries = 0;
7603: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7604:
7605: while (($gotlock ne 'ok') && $tries <3) {
7606: $tries ++;
7607: sleep 1;
7608: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7609: }
7610: if ($gotlock eq 'ok') {
7611: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7612: my ($tmp)=keys(%curr_permissions);
7613: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7614: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7615: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7616: if (ref($curr_controls) eq 'HASH') {
7617: foreach my $control_item (keys(%{$curr_controls})) {
7618: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7619: if (defined($todelete{$itemnum})) {
7620: push(@deletions,$file_name."\0".$control_item);
7621: } else {
7622: if (defined($changed_items{$itemnum})) {
7623: $new_control{$changed_items{$itemnum}} = $now;
7624: push(@deletions,$file_name."\0".$control_item);
7625: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7626: } else {
7627: $new_control{$control_item} = $$curr_controls{$control_item};
7628: }
7629: }
1.745 raeburn 7630: }
7631: }
7632: }
1.970 raeburn 7633: my ($group);
7634: if (&is_course($domain,$user)) {
7635: ($group,my $file) = split(/\//,$file_name,2);
7636: }
1.749 raeburn 7637: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7638: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7639: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7640: # remove lock
7641: my @del_lock = ($file_name."\0".'locked_access_records');
7642: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7643: my $sqlresult =
1.970 raeburn 7644: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7645: $group);
1.749 raeburn 7646: } else {
7647: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7648: }
1.749 raeburn 7649: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7650: }
7651:
1.827 raeburn 7652: sub make_public_indefinitely {
7653: my ($requrl) = @_;
7654: my $now = time;
7655: my $action = 'activate';
7656: my $aclnum = 0;
7657: if (&is_portfolio_url($requrl)) {
7658: my (undef,$udom,$unum,$file_name,$group) =
7659: &parse_portfolio_url($requrl);
7660: my $current_perms = &get_portfile_permissions($udom,$unum);
7661: my %access_controls = &get_access_controls($current_perms,
7662: $group,$file_name);
7663: foreach my $key (keys(%{$access_controls{$file_name}})) {
7664: my ($num,$scope,$end,$start) =
7665: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7666: if ($scope eq 'public') {
7667: if ($start <= $now && $end == 0) {
7668: $action = 'none';
7669: } else {
7670: $action = 'update';
7671: $aclnum = $num;
7672: }
7673: last;
7674: }
7675: }
7676: if ($action eq 'none') {
7677: return 'ok';
7678: } else {
7679: my %changes;
7680: my $newend = 0;
7681: my $newstart = $now;
7682: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7683: $changes{$action}{$newkey} = {
7684: type => 'public',
7685: time => {
7686: start => $newstart,
7687: end => $newend,
7688: },
7689: };
7690: my ($outcome,$deloutcome,$new_values,$translation) =
7691: &modify_access_controls($file_name,\%changes,$udom,$unum);
7692: return $outcome;
7693: }
7694: } else {
7695: return 'invalid';
7696: }
7697: }
7698:
1.745 raeburn 7699: #------------------------------------------------------Get Marked as Read Only
7700:
7701: sub get_marked_as_readonly {
7702: my ($domain,$user,$what,$group) = @_;
7703: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7704: my @readonly_files;
1.629 banghart 7705: my $cmp1=$what;
7706: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7707: while (my ($file_name,$value) = each(%{$current_permissions})) {
7708: if (defined($group)) {
7709: if ($file_name !~ m-^\Q$group\E/-) {
7710: next;
7711: }
7712: }
1.561 banghart 7713: if (ref($value) eq "ARRAY"){
7714: foreach my $stored_what (@{$value}) {
1.629 banghart 7715: my $cmp2=$stored_what;
1.759 albertel 7716: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7717: $cmp2=join('',@{$stored_what});
1.745 raeburn 7718: }
1.629 banghart 7719: if ($cmp1 eq $cmp2) {
1.561 banghart 7720: push(@readonly_files, $file_name);
1.745 raeburn 7721: last;
1.563 banghart 7722: } elsif (!defined($what)) {
7723: push(@readonly_files, $file_name);
1.745 raeburn 7724: last;
1.561 banghart 7725: }
7726: }
1.745 raeburn 7727: }
1.561 banghart 7728: }
7729: return @readonly_files;
7730: }
1.577 banghart 7731: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7732:
1.577 banghart 7733: sub get_marked_as_readonly_hash {
1.745 raeburn 7734: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7735: my %readonly_files;
1.745 raeburn 7736: while (my ($file_name,$value) = each(%{$current_permissions})) {
7737: if (defined($group)) {
7738: if ($file_name !~ m-^\Q$group\E/-) {
7739: next;
7740: }
7741: }
1.577 banghart 7742: if (ref($value) eq "ARRAY"){
7743: foreach my $stored_what (@{$value}) {
1.745 raeburn 7744: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7745: foreach my $lock_descriptor(@{$stored_what}) {
7746: if ($lock_descriptor eq 'graded') {
7747: $readonly_files{$file_name} = 'graded';
7748: } elsif ($lock_descriptor eq 'handback') {
7749: $readonly_files{$file_name} = 'handback';
7750: } else {
7751: if (!exists($readonly_files{$file_name})) {
7752: $readonly_files{$file_name} = 'locked';
7753: }
7754: }
1.745 raeburn 7755: }
1.750 banghart 7756: }
1.577 banghart 7757: }
7758: }
7759: }
7760: return %readonly_files;
7761: }
1.559 banghart 7762: # ------------------------------------------------------------ Unmark as Read Only
7763:
7764: sub unmark_as_readonly {
1.629 banghart 7765: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7766: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7767: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7768: $file_name = &declutter_portfile($file_name);
1.634 albertel 7769: my $symb_crs = $what;
7770: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7771: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7772: my ($tmp)=keys(%current_permissions);
7773: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7774: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7775: foreach my $file (@readonly_files) {
1.759 albertel 7776: my $clean_file = &declutter_portfile($file);
7777: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7778: my $current_locks = $current_permissions{$file};
1.563 banghart 7779: my @new_locks;
7780: my @del_keys;
7781: if (ref($current_locks) eq "ARRAY"){
7782: foreach my $locker (@{$current_locks}) {
1.632 albertel 7783: my $compare=$locker;
1.749 raeburn 7784: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7785: $compare=join('',@{$locker});
1.746 raeburn 7786: if ($compare ne $symb_crs) {
7787: push(@new_locks, $locker);
7788: }
1.563 banghart 7789: }
7790: }
1.650 albertel 7791: if (scalar(@new_locks) > 0) {
1.563 banghart 7792: $current_permissions{$file} = \@new_locks;
7793: } else {
7794: push(@del_keys, $file);
1.613 albertel 7795: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7796: delete($current_permissions{$file});
1.563 banghart 7797: }
7798: }
1.561 banghart 7799: }
1.613 albertel 7800: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7801: return;
7802: }
1.512 banghart 7803:
1.17 www 7804: # ------------------------------------------------------------ Directory lister
7805:
7806: sub dirlist {
1.955 raeburn 7807: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7808: $uri=~s/^\///;
7809: $uri=~s/\/$//;
1.253 stredwic 7810: my ($udom, $uname);
1.955 raeburn 7811: if ($getuserdir) {
1.253 stredwic 7812: $udom = $userdomain;
7813: $uname = $username;
1.955 raeburn 7814: } else {
7815: (undef,$udom,$uname)=split(/\//,$uri);
7816: if(defined($userdomain)) {
7817: $udom = $userdomain;
7818: }
7819: if(defined($username)) {
7820: $uname = $username;
7821: }
1.253 stredwic 7822: }
1.955 raeburn 7823: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7824:
1.955 raeburn 7825: $dirRoot = $perlvar{'lonDocRoot'};
7826: if (defined($getpropath)) {
7827: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7828: $dirRoot =~ s/\/$//;
1.955 raeburn 7829: } elsif (defined($getuserdir)) {
7830: my $subdir=$uname.'__';
7831: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7832: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7833: ."/$udom/$subdir/$uname";
7834: } elsif (defined($alternateRoot)) {
7835: $dirRoot = $alternateRoot;
1.751 banghart 7836: }
1.253 stredwic 7837:
7838: if($udom) {
7839: if($uname) {
1.955 raeburn 7840: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7841: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7842: .':'.&escape($uname).':'.&escape($udom),
7843: &homeserver($uname,$udom));
7844: if ($listing eq 'unknown_cmd') {
7845: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7846: &homeserver($uname,$udom));
7847: } else {
7848: @listing_results = map { &unescape($_); } split(/:/,$listing);
7849: }
1.605 matthew 7850: if ($listing eq 'unknown_cmd') {
1.800 albertel 7851: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7852: &homeserver($uname,$udom));
1.605 matthew 7853: @listing_results = split(/:/,$listing);
7854: } else {
7855: @listing_results = map { &unescape($_); } split(/:/,$listing);
7856: }
7857: return @listing_results;
1.955 raeburn 7858: } elsif(!$alternateRoot) {
1.800 albertel 7859: my %allusers;
1.841 albertel 7860: my %servers = &get_servers($udom,'library');
1.955 raeburn 7861: foreach my $tryserver (keys(%servers)) {
7862: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7863: &escape($udom),$tryserver);
7864: if ($listing eq 'unknown_cmd') {
7865: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7866: $udom, $tryserver);
7867: } else {
7868: @listing_results = map { &unescape($_); } split(/:/,$listing);
7869: }
1.841 albertel 7870: if ($listing eq 'unknown_cmd') {
7871: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7872: $udom, $tryserver);
7873: @listing_results = split(/:/,$listing);
7874: } else {
7875: @listing_results =
7876: map { &unescape($_); } split(/:/,$listing);
7877: }
7878: if ($listing_results[0] ne 'no_such_dir' &&
7879: $listing_results[0] ne 'empty' &&
7880: $listing_results[0] ne 'con_lost') {
7881: foreach my $line (@listing_results) {
7882: my ($entry) = split(/&/,$line,2);
7883: $allusers{$entry} = 1;
7884: }
7885: }
1.253 stredwic 7886: }
7887: my $alluserstr='';
1.800 albertel 7888: foreach my $user (sort(keys(%allusers))) {
7889: $alluserstr.=$user.'&user:';
1.253 stredwic 7890: }
7891: $alluserstr=~s/:$//;
7892: return split(/:/,$alluserstr);
7893: } else {
1.800 albertel 7894: return ('missing user name');
1.253 stredwic 7895: }
1.955 raeburn 7896: } elsif(!defined($getpropath)) {
1.841 albertel 7897: my @all_domains = sort(&all_domains());
1.955 raeburn 7898: foreach my $domain (@all_domains) {
7899: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7900: }
7901: return @all_domains;
7902: } else {
1.800 albertel 7903: return ('missing domain');
1.275 stredwic 7904: }
7905: }
7906:
7907: # --------------------------------------------- GetFileTimestamp
7908: # This function utilizes dirlist and returns the date stamp for
7909: # when it was last modified. It will also return an error of -1
7910: # if an error occurs
7911:
7912: sub GetFileTimestamp {
1.955 raeburn 7913: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7914: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7915: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7916: my ($fileStat) =
7917: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7918: undef,$getuserdir);
1.275 stredwic 7919: my @stats = split('&', $fileStat);
7920: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7921: # @stats contains first the filename, then the stat output
7922: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7923: } else {
7924: return -1;
1.253 stredwic 7925: }
1.26 www 7926: }
7927:
1.712 albertel 7928: sub stat_file {
7929: my ($uri) = @_;
1.787 albertel 7930: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7931:
1.955 raeburn 7932: my ($udom,$uname,$file);
1.712 albertel 7933: if ($uri =~ m-^/(uploaded|editupload)/-) {
7934: ($udom,$uname,$file) =
1.811 albertel 7935: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7936: $file = 'userfiles/'.$file;
7937: }
7938: if ($uri =~ m-^/res/-) {
7939: ($udom,$uname) =
1.807 albertel 7940: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7941: $file = $uri;
7942: }
7943:
7944: if (!$udom || !$uname || !$file) {
7945: # unable to handle the uri
7946: return ();
7947: }
1.956 raeburn 7948: my $getpropath;
7949: if ($file =~ /^userfiles\//) {
7950: $getpropath = 1;
7951: }
1.955 raeburn 7952: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7953: my @stats = split('&', $result);
1.721 banghart 7954:
1.712 albertel 7955: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7956: shift(@stats); #filename is first
7957: return @stats;
7958: }
7959: return ();
7960: }
7961:
1.26 www 7962: # -------------------------------------------------------- Value of a Condition
7963:
1.713 albertel 7964: # gets the value of a specific preevaluated condition
7965: # stored in the string $env{user.state.<cid>}
7966: # or looks up a condition reference in the bighash and if if hasn't
7967: # already been evaluated recurses into docondval to get the value of
7968: # the condition, then memoizing it to
7969: # $env{user.state.<cid>.<condition>}
1.40 www 7970: sub directcondval {
7971: my $number=shift;
1.620 albertel 7972: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7973: &Apache::lonuserstate::evalstate();
7974: }
1.713 albertel 7975: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7976: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7977: } elsif ($number =~ /^_/) {
7978: my $sub_condition;
7979: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7980: &GDBM_READER(),0640)) {
7981: $sub_condition=$bighash{'conditions'.$number};
7982: untie(%bighash);
7983: }
7984: my $value = &docondval($sub_condition);
1.949 raeburn 7985: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7986: return $value;
7987: }
1.620 albertel 7988: if ($env{'user.state.'.$env{'request.course.id'}}) {
7989: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7990: } else {
7991: return 2;
7992: }
7993: }
7994:
1.713 albertel 7995: # get the collection of conditions for this resource
1.26 www 7996: sub condval {
7997: my $condidx=shift;
1.54 www 7998: my $allpathcond='';
1.713 albertel 7999: foreach my $cond (split(/\|/,$condidx)) {
8000: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8001: $allpathcond.=
8002: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8003: }
1.191 harris41 8004: }
1.54 www 8005: $allpathcond=~s/\|$//;
1.713 albertel 8006: return &docondval($allpathcond);
8007: }
8008:
8009: #evaluates an expression of conditions
8010: sub docondval {
8011: my ($allpathcond) = @_;
8012: my $result=0;
8013: if ($env{'request.course.id'}
8014: && defined($allpathcond)) {
8015: my $operand='|';
8016: my @stack;
8017: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8018: if ($chunk eq '(') {
8019: push @stack,($operand,$result);
8020: } elsif ($chunk eq ')') {
8021: my $before=pop @stack;
8022: if (pop @stack eq '&') {
8023: $result=$result>$before?$before:$result;
8024: } else {
8025: $result=$result>$before?$result:$before;
8026: }
8027: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8028: $operand=$chunk;
8029: } else {
8030: my $new=directcondval($chunk);
8031: if ($operand eq '&') {
8032: $result=$result>$new?$new:$result;
8033: } else {
8034: $result=$result>$new?$result:$new;
8035: }
8036: }
8037: }
1.26 www 8038: }
8039: return $result;
1.421 albertel 8040: }
8041:
8042: # ---------------------------------------------------- Devalidate courseresdata
8043:
8044: sub devalidatecourseresdata {
8045: my ($coursenum,$coursedomain)=@_;
8046: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8047: &devalidate_cache_new('courseres',$hashid);
1.28 www 8048: }
8049:
1.763 www 8050:
1.200 www 8051: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8052: #
8053: # Parameters:
8054: # $coursenum - Number of the course.
8055: # $coursedomain - Domain at which the course was created.
8056: # Returns:
8057: # A hash of the course parameters along (I think) with timestamps
8058: # and version info.
1.877 foxr 8059:
1.624 albertel 8060: sub get_courseresdata {
8061: my ($coursenum,$coursedomain)=@_;
1.200 www 8062: my $coursehom=&homeserver($coursenum,$coursedomain);
8063: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8064: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8065: my %dumpreply;
1.417 albertel 8066: unless (defined($cached)) {
1.624 albertel 8067: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8068: $result=\%dumpreply;
1.251 albertel 8069: my ($tmp) = keys(%dumpreply);
8070: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8071: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8072: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8073: return $tmp;
1.416 albertel 8074: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8075: $result=undef;
1.599 albertel 8076: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8077: }
8078: }
1.624 albertel 8079: return $result;
8080: }
8081:
1.633 albertel 8082: sub devalidateuserresdata {
8083: my ($uname,$udom)=@_;
8084: my $hashid="$udom:$uname";
8085: &devalidate_cache_new('userres',$hashid);
8086: }
8087:
1.624 albertel 8088: sub get_userresdata {
8089: my ($uname,$udom)=@_;
8090: #most student don\'t have any data set, check if there is some data
8091: if (&EXT_cache_status($udom,$uname)) { return undef; }
8092:
8093: my $hashid="$udom:$uname";
8094: my ($result,$cached)=&is_cached_new('userres',$hashid);
8095: if (!defined($cached)) {
8096: my %resourcedata=&dump('resourcedata',$udom,$uname);
8097: $result=\%resourcedata;
8098: &do_cache_new('userres',$hashid,$result,600);
8099: }
8100: my ($tmp)=keys(%$result);
8101: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8102: return $result;
8103: }
8104: #error 2 occurs when the .db doesn't exist
8105: if ($tmp!~/error: 2 /) {
1.672 albertel 8106: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8107: " Trying to get resource data for ".
8108: $uname." at ".$udom.": ".
8109: $tmp."</font>");
8110: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8111: #&EXT_cache_set($udom,$uname);
8112: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8113: undef($tmp); # not really an error so don't send it back
1.624 albertel 8114: }
8115: return $tmp;
8116: }
1.879 foxr 8117: #----------------------------------------------- resdata - return resource data
8118: # Purpose:
8119: # Return resource data for either users or for a course.
8120: # Parameters:
8121: # $name - Course/user name.
8122: # $domain - Name of the domain the user/course is registered on.
8123: # $type - Type of thing $name is (must be 'course' or 'user'
8124: # @which - Array of names of resources desired.
8125: # Returns:
8126: # The value of the first reasource in @which that is found in the
8127: # resource hash.
8128: # Exceptional Conditions:
8129: # If the $type passed in is not valid (not the string 'course' or
8130: # 'user', an undefined reference is returned.
8131: # If none of the resources are found, an undef is returned
1.624 albertel 8132: sub resdata {
8133: my ($name,$domain,$type,@which)=@_;
8134: my $result;
8135: if ($type eq 'course') {
8136: $result=&get_courseresdata($name,$domain);
8137: } elsif ($type eq 'user') {
8138: $result=&get_userresdata($name,$domain);
8139: }
8140: if (!ref($result)) { return $result; }
1.251 albertel 8141: foreach my $item (@which) {
1.927 albertel 8142: if (defined($result->{$item->[0]})) {
8143: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8144: }
1.250 albertel 8145: }
1.291 albertel 8146: return undef;
1.200 www 8147: }
8148:
1.379 matthew 8149: #
8150: # EXT resource caching routines
8151: #
8152:
8153: sub clear_EXT_cache_status {
1.383 albertel 8154: &delenv('cache.EXT.');
1.379 matthew 8155: }
8156:
8157: sub EXT_cache_status {
8158: my ($target_domain,$target_user) = @_;
1.383 albertel 8159: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8160: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8161: # We know already the user has no data
8162: return 1;
8163: } else {
8164: return 0;
8165: }
8166: }
8167:
8168: sub EXT_cache_set {
8169: my ($target_domain,$target_user) = @_;
1.383 albertel 8170: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8171: #&appenv({$cachename => time});
1.379 matthew 8172: }
8173:
1.28 www 8174: # --------------------------------------------------------- Value of a Variable
1.58 www 8175: sub EXT {
1.715 albertel 8176:
1.395 albertel 8177: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8178: unless ($varname) { return ''; }
1.218 albertel 8179: #get real user name/domain, courseid and symb
8180: my $courseid;
1.359 albertel 8181: my $publicuser;
1.427 www 8182: if ($symbparm) {
8183: $symbparm=&get_symb_from_alias($symbparm);
8184: }
1.218 albertel 8185: if (!($uname && $udom)) {
1.790 albertel 8186: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8187: if (!$symbparm) { $symbparm=$cursymb; }
8188: } else {
1.620 albertel 8189: $courseid=$env{'request.course.id'};
1.218 albertel 8190: }
1.48 www 8191: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8192: my $rest;
1.320 albertel 8193: if (defined($therest[0])) {
1.48 www 8194: $rest=join('.',@therest);
8195: } else {
8196: $rest='';
8197: }
1.320 albertel 8198:
1.57 www 8199: my $qualifierrest=$qualifier;
8200: if ($rest) { $qualifierrest.='.'.$rest; }
8201: my $spacequalifierrest=$space;
8202: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8203: if ($realm eq 'user') {
1.48 www 8204: # --------------------------------------------------------------- user.resource
8205: if ($space eq 'resource') {
1.651 albertel 8206: if ( (defined($Apache::lonhomework::parsing_a_problem)
8207: || defined($Apache::lonhomework::parsing_a_task))
8208: &&
1.744 albertel 8209: ($symbparm eq &symbread()) ) {
8210: # if we are in the middle of processing the resource the
8211: # get the value we are planning on committing
8212: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8213: return $Apache::lonhomework::results{$qualifierrest};
8214: } else {
8215: return $Apache::lonhomework::history{$qualifierrest};
8216: }
1.335 albertel 8217: } else {
1.359 albertel 8218: my %restored;
1.620 albertel 8219: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8220: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8221: } else {
8222: %restored=&restore($symbparm,$courseid,$udom,$uname);
8223: }
1.335 albertel 8224: return $restored{$qualifierrest};
8225: }
1.48 www 8226: # ----------------------------------------------------------------- user.access
8227: } elsif ($space eq 'access') {
1.218 albertel 8228: # FIXME - not supporting calls for a specific user
1.48 www 8229: return &allowed($qualifier,$rest);
8230: # ------------------------------------------ user.preferences, user.environment
8231: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8232: if (($uname eq $env{'user.name'}) &&
8233: ($udom eq $env{'user.domain'})) {
8234: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8235: } else {
1.359 albertel 8236: my %returnhash;
8237: if (!$publicuser) {
8238: %returnhash=&userenvironment($udom,$uname,
8239: $qualifierrest);
8240: }
1.218 albertel 8241: return $returnhash{$qualifierrest};
8242: }
1.48 www 8243: # ----------------------------------------------------------------- user.course
8244: } elsif ($space eq 'course') {
1.218 albertel 8245: # FIXME - not supporting calls for a specific user
1.620 albertel 8246: return $env{join('.',('request.course',$qualifier))};
1.48 www 8247: # ------------------------------------------------------------------- user.role
8248: } elsif ($space eq 'role') {
1.218 albertel 8249: # FIXME - not supporting calls for a specific user
1.620 albertel 8250: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8251: if ($qualifier eq 'value') {
8252: return $role;
8253: } elsif ($qualifier eq 'extent') {
8254: return $where;
8255: }
8256: # ----------------------------------------------------------------- user.domain
8257: } elsif ($space eq 'domain') {
1.218 albertel 8258: return $udom;
1.48 www 8259: # ------------------------------------------------------------------- user.name
8260: } elsif ($space eq 'name') {
1.218 albertel 8261: return $uname;
1.48 www 8262: # ---------------------------------------------------- Any other user namespace
1.29 www 8263: } else {
1.359 albertel 8264: my %reply;
8265: if (!$publicuser) {
8266: %reply=&get($space,[$qualifierrest],$udom,$uname);
8267: }
8268: return $reply{$qualifierrest};
1.48 www 8269: }
1.236 www 8270: } elsif ($realm eq 'query') {
8271: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8272: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8273: [$spacequalifierrest]);
1.620 albertel 8274: return $env{'form.'.$spacequalifierrest};
1.236 www 8275: } elsif ($realm eq 'request') {
1.48 www 8276: # ------------------------------------------------------------- request.browser
8277: if ($space eq 'browser') {
1.430 www 8278: if ($qualifier eq 'textremote') {
1.676 albertel 8279: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8280: return 1;
8281: } else {
8282: return 0;
8283: }
8284: } else {
1.620 albertel 8285: return $env{'browser.'.$qualifier};
1.430 www 8286: }
1.57 www 8287: # ------------------------------------------------------------ request.filename
8288: } else {
1.620 albertel 8289: return $env{'request.'.$spacequalifierrest};
1.29 www 8290: }
1.28 www 8291: } elsif ($realm eq 'course') {
1.48 www 8292: # ---------------------------------------------------------- course.description
1.620 albertel 8293: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8294: } elsif ($realm eq 'resource') {
1.165 www 8295:
1.620 albertel 8296: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8297: if (!$symbparm) { $symbparm=&symbread(); }
8298: }
1.693 albertel 8299:
8300: if ($space eq 'title') {
8301: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8302: return &gettitle($symbparm);
8303: }
8304:
8305: if ($space eq 'map') {
8306: my ($map) = &decode_symb($symbparm);
8307: return &symbread($map);
8308: }
1.905 albertel 8309: if ($space eq 'filename') {
8310: if ($symbparm) {
8311: return &clutter((&decode_symb($symbparm))[2]);
8312: }
8313: return &hreflocation('',$env{'request.filename'});
8314: }
1.693 albertel 8315:
8316: my ($section, $group, @groups);
1.593 albertel 8317: my ($courselevelm,$courselevel);
1.539 albertel 8318: if ($symbparm && defined($courseid) &&
1.620 albertel 8319: $courseid eq $env{'request.course.id'}) {
1.165 www 8320:
1.218 albertel 8321: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8322:
1.60 www 8323: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8324: my $symbp=$symbparm;
1.735 albertel 8325: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8326:
8327: my $symbparm=$symbp.'.'.$spacequalifierrest;
8328: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8329:
1.620 albertel 8330: if (($env{'user.name'} eq $uname) &&
8331: ($env{'user.domain'} eq $udom)) {
8332: $section=$env{'request.course.sec'};
1.733 raeburn 8333: @groups = split(/:/,$env{'request.course.groups'});
8334: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8335: } else {
1.539 albertel 8336: if (! defined($usection)) {
1.551 albertel 8337: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8338: } else {
8339: $section = $usection;
8340: }
1.733 raeburn 8341: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8342: }
8343:
8344: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8345: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8346: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8347:
1.593 albertel 8348: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8349: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8350: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8351:
1.60 www 8352: # ----------------------------------------------------------- first, check user
1.624 albertel 8353:
8354: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8355: ([$courselevelr,'resource'],
8356: [$courselevelm,'map' ],
8357: [$courselevel, 'course' ]));
1.931 albertel 8358: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8359:
1.594 albertel 8360: # ------------------------------------------------ second, check some of course
1.684 raeburn 8361: my $coursereply;
1.691 raeburn 8362: if (@groups > 0) {
8363: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8364: $mapparm,$spacequalifierrest);
1.927 albertel 8365: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8366: }
1.96 www 8367:
1.684 raeburn 8368: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8369: $env{'course.'.$courseid.'.domain'},
8370: 'course',
8371: ([$seclevelr, 'resource'],
8372: [$seclevelm, 'map' ],
8373: [$seclevel, 'course' ],
8374: [$courselevelr,'resource']));
8375: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8376:
1.60 www 8377: # ------------------------------------------------------ third, check map parms
1.218 albertel 8378: my %parmhash=();
8379: my $thisparm='';
8380: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8381: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8382: &GDBM_READER(),0640)) {
1.218 albertel 8383: $thisparm=$parmhash{$symbparm};
8384: untie(%parmhash);
8385: }
1.927 albertel 8386: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8387: }
1.594 albertel 8388: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8389:
1.218 albertel 8390: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8391: my $filename;
8392: if (!$symbparm) { $symbparm=&symbread(); }
8393: if ($symbparm) {
1.409 www 8394: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8395: } else {
1.620 albertel 8396: $filename=$env{'request.filename'};
1.282 albertel 8397: }
8398: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8399: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8400: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8401: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8402:
1.927 albertel 8403: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8404: if ($symbparm && defined($courseid) &&
1.620 albertel 8405: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8406: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8407: $env{'course.'.$courseid.'.domain'},
8408: 'course',
1.927 albertel 8409: ([$courselevelm,'map' ],
8410: [$courselevel, 'course']));
8411: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8412: }
1.145 www 8413: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8414: unless ($space eq '0') {
1.336 albertel 8415: my @parts=split(/_/,$space);
8416: my $id=pop(@parts);
8417: my $part=join('_',@parts);
8418: if ($part eq '') { $part='0'; }
1.927 albertel 8419: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8420: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8421: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8422: }
1.395 albertel 8423: if ($recurse) { return undef; }
8424: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8425: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8426: # ---------------------------------------------------- Any other user namespace
8427: } elsif ($realm eq 'environment') {
8428: # ----------------------------------------------------------------- environment
1.620 albertel 8429: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8430: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8431: } else {
1.770 albertel 8432: if ($uname eq 'anonymous' && $udom eq '') {
8433: return '';
8434: }
1.219 albertel 8435: my %returnhash=&userenvironment($udom,$uname,
8436: $spacequalifierrest);
8437: return $returnhash{$spacequalifierrest};
8438: }
1.28 www 8439: } elsif ($realm eq 'system') {
1.48 www 8440: # ----------------------------------------------------------------- system.time
8441: if ($space eq 'time') {
8442: return time;
8443: }
1.696 albertel 8444: } elsif ($realm eq 'server') {
8445: # ----------------------------------------------------------------- system.time
8446: if ($space eq 'name') {
8447: return $ENV{'SERVER_NAME'};
8448: }
1.28 www 8449: }
1.48 www 8450: return '';
1.61 www 8451: }
8452:
1.927 albertel 8453: sub get_reply {
8454: my ($reply_value) = @_;
1.940 raeburn 8455: if (ref($reply_value) eq 'ARRAY') {
8456: if (wantarray) {
8457: return @$reply_value;
8458: }
8459: return $reply_value->[0];
8460: } else {
8461: return $reply_value;
1.927 albertel 8462: }
8463: }
8464:
1.691 raeburn 8465: sub check_group_parms {
8466: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8467: my @groupitems = ();
8468: my $resultitem;
1.927 albertel 8469: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8470: foreach my $group (@{$groups}) {
8471: foreach my $level (@levels) {
1.927 albertel 8472: my $item = $courseid.'.['.$group.'].'.$level->[0];
8473: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8474: }
8475: }
8476: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8477: $env{'course.'.$courseid.'.domain'},
8478: 'course',@groupitems);
8479: return $coursereply;
8480: }
8481:
8482: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8483: my ($courseid,@groups) = @_;
8484: @groups = sort(@groups);
1.691 raeburn 8485: return @groups;
8486: }
8487:
1.395 albertel 8488: sub packages_tab_default {
8489: my ($uri,$varname)=@_;
8490: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8491:
8492: my (@extension,@specifics,$do_default);
8493: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8494: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8495: if ($pack_type eq 'default') {
8496: $do_default=1;
8497: } elsif ($pack_type eq 'extension') {
8498: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8499: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8500: # only look at packages defaults for packages that this id is
1.738 albertel 8501: push(@specifics,[$package,$pack_type,$pack_part]);
8502: }
8503: }
8504: # first look for a package that matches the requested part id
8505: foreach my $package (@specifics) {
8506: my (undef,$pack_type,$pack_part)=@{$package};
8507: next if ($pack_part ne $part);
8508: if (defined($packagetab{"$pack_type&$name&default"})) {
8509: return $packagetab{"$pack_type&$name&default"};
8510: }
8511: }
8512: # look for any possible matching non extension_ package
8513: foreach my $package (@specifics) {
8514: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8515: if (defined($packagetab{"$pack_type&$name&default"})) {
8516: return $packagetab{"$pack_type&$name&default"};
8517: }
1.585 albertel 8518: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8519: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8520: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8521: }
8522: }
1.738 albertel 8523: # look for any posible extension_ match
8524: foreach my $package (@extension) {
8525: my ($package,$pack_type)=@{$package};
8526: if (defined($packagetab{"$pack_type&$name&default"})) {
8527: return $packagetab{"$pack_type&$name&default"};
8528: }
8529: if (defined($packagetab{$package."&$name&default"})) {
8530: return $packagetab{$package."&$name&default"};
8531: }
8532: }
8533: # look for a global default setting
8534: if ($do_default && defined($packagetab{"default&$name&default"})) {
8535: return $packagetab{"default&$name&default"};
8536: }
1.395 albertel 8537: return undef;
8538: }
8539:
1.334 albertel 8540: sub add_prefix_and_part {
8541: my ($prefix,$part)=@_;
8542: my $keyroot;
8543: if (defined($prefix) && $prefix !~ /^__/) {
8544: # prefix that has a part already
8545: $keyroot=$prefix;
8546: } elsif (defined($prefix)) {
8547: # prefix that is missing a part
8548: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8549: } else {
8550: # no prefix at all
8551: if (defined($part)) { $keyroot='_'.$part; }
8552: }
8553: return $keyroot;
8554: }
8555:
1.71 www 8556: # ---------------------------------------------------------------- Get metadata
8557:
1.599 albertel 8558: my %metaentry;
1.71 www 8559: sub metadata {
1.176 www 8560: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8561: $uri=&declutter($uri);
1.288 albertel 8562: # if it is a non metadata possible uri return quickly
1.529 albertel 8563: if (($uri eq '') ||
8564: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8565: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.13 raeburn 8566: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^\*uploaded\/.+\.sequence$/) ) {
1.924 albertel 8567: return undef;
8568: }
8569: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8570: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8571: return undef;
1.288 albertel 8572: }
1.73 www 8573: my $filename=$uri;
8574: $uri=~s/\.meta$//;
1.172 www 8575: #
8576: # Is the metadata already cached?
1.177 www 8577: # Look at timestamp of caching
1.172 www 8578: # Everything is cached by the main uri, libraries are never directly cached
8579: #
1.428 albertel 8580: if (!defined($liburi)) {
1.599 albertel 8581: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8582: if (defined($cached)) { return $result->{':'.$what}; }
8583: }
8584: {
1.172 www 8585: #
8586: # Is this a recursive call for a library?
8587: #
1.599 albertel 8588: # if (! exists($metacache{$uri})) {
8589: # $metacache{$uri}={};
8590: # }
1.924 albertel 8591: my $cachetime = 60*60;
1.171 www 8592: if ($liburi) {
8593: $liburi=&declutter($liburi);
8594: $filename=$liburi;
1.401 bowersj2 8595: } else {
1.599 albertel 8596: &devalidate_cache_new('meta',$uri);
8597: undef(%metaentry);
1.401 bowersj2 8598: }
1.140 www 8599: my %metathesekeys=();
1.73 www 8600: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8601: my $metastring;
1.924 albertel 8602: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8603: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8604: $metastring =
1.929 albertel 8605: &Apache::lonnet::ssi_body($which,
1.924 albertel 8606: ('grade_target' => 'meta'));
8607: $cachetime = 1; # only want this cached in the child not long term
8608: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8609: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8610: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8611: $metastring=&getfile($file);
1.489 albertel 8612: }
1.208 albertel 8613: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8614: my $token;
1.140 www 8615: undef %metathesekeys;
1.71 www 8616: while ($token=$parser->get_token) {
1.339 albertel 8617: if ($token->[0] eq 'S') {
8618: if (defined($token->[2]->{'package'})) {
1.172 www 8619: #
8620: # This is a package - get package info
8621: #
1.339 albertel 8622: my $package=$token->[2]->{'package'};
8623: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8624: if (defined($token->[2]->{'id'})) {
8625: $keyroot.='_'.$token->[2]->{'id'};
8626: }
1.599 albertel 8627: if ($metaentry{':packages'}) {
8628: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8629: } else {
1.599 albertel 8630: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8631: }
1.736 albertel 8632: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8633: my $part=$keyroot;
8634: $part=~s/^\_//;
1.736 albertel 8635: if ($pack_entry=~/^\Q$package\E\&/ ||
8636: $pack_entry=~/^\Q$package\E_0\&/) {
8637: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8638: # ignore package.tab specified default values
8639: # here &package_tab_default() will fetch those
8640: if ($subp eq 'default') { next; }
1.736 albertel 8641: my $value=$packagetab{$pack_entry};
1.432 albertel 8642: my $unikey;
8643: if ($pack =~ /_0$/) {
8644: $unikey='parameter_0_'.$name;
8645: $part=0;
8646: } else {
8647: $unikey='parameter'.$keyroot.'_'.$name;
8648: }
1.339 albertel 8649: if ($subp eq 'display') {
8650: $value.=' [Part: '.$part.']';
8651: }
1.599 albertel 8652: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8653: $metathesekeys{$unikey}=1;
1.599 albertel 8654: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8655: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8656: }
1.599 albertel 8657: if (defined($metaentry{':'.$unikey.'.default'})) {
8658: $metaentry{':'.$unikey}=
8659: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8660: }
1.339 albertel 8661: }
8662: }
8663: } else {
1.172 www 8664: #
8665: # This is not a package - some other kind of start tag
1.339 albertel 8666: #
8667: my $entry=$token->[1];
8668: my $unikey;
8669: if ($entry eq 'import') {
8670: $unikey='';
8671: } else {
8672: $unikey=$entry;
8673: }
8674: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8675:
8676: if (defined($token->[2]->{'id'})) {
8677: $unikey.='_'.$token->[2]->{'id'};
8678: }
1.175 www 8679:
1.339 albertel 8680: if ($entry eq 'import') {
1.175 www 8681: #
8682: # Importing a library here
1.339 albertel 8683: #
8684: if ($depthcount<20) {
8685: my $location=$parser->get_text('/import');
8686: my $dir=$filename;
8687: $dir=~s|[^/]*$||;
8688: $location=&filelocation($dir,$location);
1.736 albertel 8689: my $metadata =
8690: &metadata($uri,'keys', $location,$unikey,
8691: $depthcount+1);
8692: foreach my $meta (split(',',$metadata)) {
8693: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8694: $metathesekeys{$meta}=1;
1.339 albertel 8695: }
8696: }
8697: } else {
8698: if (defined($token->[2]->{'name'})) {
8699: $unikey.='_'.$token->[2]->{'name'};
8700: }
8701: $metathesekeys{$unikey}=1;
1.736 albertel 8702: foreach my $param (@{$token->[3]}) {
8703: $metaentry{':'.$unikey.'.'.$param} =
8704: $token->[2]->{$param};
1.339 albertel 8705: }
8706: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8707: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8708: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8709: # only ws inside the tag, and not in default, so use default
8710: # as value
1.599 albertel 8711: $metaentry{':'.$unikey}=$default;
1.908 albertel 8712: } elsif ( $internaltext =~ /\S/ ) {
8713: # something interesting inside the tag
8714: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8715: } else {
1.908 albertel 8716: # no interesting values, don't set a default
1.339 albertel 8717: }
1.172 www 8718: # end of not-a-package not-a-library import
1.339 albertel 8719: }
1.172 www 8720: # end of not-a-package start tag
1.339 albertel 8721: }
1.172 www 8722: # the next is the end of "start tag"
1.339 albertel 8723: }
8724: }
1.483 albertel 8725: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8726: $extension = lc($extension);
8727: if ($extension eq 'htm') { $extension='html'; }
8728:
1.737 albertel 8729: foreach my $key (keys(%packagetab)) {
1.483 albertel 8730: #no specific packages #how's our extension
8731: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8732: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8733: \%metathesekeys);
8734: }
1.883 albertel 8735:
8736: if (!exists($metaentry{':packages'})
8737: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8738: foreach my $key (keys(%packagetab)) {
1.483 albertel 8739: #no specific packages well let's get default then
8740: if ($key!~/^default&/) { next; }
1.488 albertel 8741: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8742: \%metathesekeys);
8743: }
8744: }
1.338 www 8745: # are there custom rights to evaluate
1.599 albertel 8746: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8747:
1.338 www 8748: #
8749: # Importing a rights file here
1.339 albertel 8750: #
8751: unless ($depthcount) {
1.599 albertel 8752: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8753: my $dir=$filename;
8754: $dir=~s|[^/]*$||;
8755: $location=&filelocation($dir,$location);
1.736 albertel 8756: my $rights_metadata =
8757: &metadata($uri,'keys',$location,'_rights',
8758: $depthcount+1);
8759: foreach my $rights (split(',',$rights_metadata)) {
8760: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8761: $metathesekeys{$rights}=1;
1.339 albertel 8762: }
8763: }
8764: }
1.737 albertel 8765: # uniqifiy package listing
8766: my %seen;
8767: my @uniq_packages =
8768: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8769: $metaentry{':packages'} = join(',',@uniq_packages);
8770:
8771: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8772: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8773: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8774: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8775: # this is the end of "was not already recently cached
1.71 www 8776: }
1.599 albertel 8777: return $metaentry{':'.$what};
1.261 albertel 8778: }
8779:
1.488 albertel 8780: sub metadata_create_package_def {
1.483 albertel 8781: my ($uri,$key,$package,$metathesekeys)=@_;
8782: my ($pack,$name,$subp)=split(/\&/,$key);
8783: if ($subp eq 'default') { next; }
8784:
1.599 albertel 8785: if (defined($metaentry{':packages'})) {
8786: $metaentry{':packages'}.=','.$package;
1.483 albertel 8787: } else {
1.599 albertel 8788: $metaentry{':packages'}=$package;
1.483 albertel 8789: }
8790: my $value=$packagetab{$key};
8791: my $unikey;
8792: $unikey='parameter_0_'.$name;
1.599 albertel 8793: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8794: $$metathesekeys{$unikey}=1;
1.599 albertel 8795: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8796: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8797: }
1.599 albertel 8798: if (defined($metaentry{':'.$unikey.'.default'})) {
8799: $metaentry{':'.$unikey}=
8800: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8801: }
8802: }
8803:
1.261 albertel 8804: sub metadata_generate_part0 {
8805: my ($metadata,$metacache,$uri) = @_;
8806: my %allnames;
1.737 albertel 8807: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8808: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8809: my $part=$$metacache{':'.$metakey.'.part'};
8810: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8811: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8812: $allnames{$name}=$part;
8813: }
8814: }
8815: }
8816: foreach my $name (keys(%allnames)) {
8817: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8818: my $key=":parameter_0_$name";
1.261 albertel 8819: $$metacache{"$key.part"}='0';
8820: $$metacache{"$key.name"}=$name;
1.428 albertel 8821: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8822: $allnames{$name}.'_'.$name.
8823: '.type'};
1.428 albertel 8824: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8825: '.display'};
1.644 www 8826: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8827: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8828: $$metacache{"$key.display"}=$olddis;
8829: }
1.71 www 8830: }
8831:
1.764 albertel 8832: # ------------------------------------------------------ Devalidate title cache
8833:
8834: sub devalidate_title_cache {
8835: my ($url)=@_;
8836: if (!$env{'request.course.id'}) { return; }
8837: my $symb=&symbread($url);
8838: if (!$symb) { return; }
8839: my $key=$env{'request.course.id'}."\0".$symb;
8840: &devalidate_cache_new('title',$key);
8841: }
8842:
1.1014 droeschl 8843: # ------------------------------------------------- Get the title of a course
8844:
8845: sub current_course_title {
8846: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8847: }
1.301 www 8848: # ------------------------------------------------- Get the title of a resource
8849:
8850: sub gettitle {
8851: my $urlsymb=shift;
8852: my $symb=&symbread($urlsymb);
1.534 albertel 8853: if ($symb) {
1.620 albertel 8854: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8855: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8856: if (defined($cached)) {
8857: return $result;
8858: }
1.534 albertel 8859: my ($map,$resid,$url)=&decode_symb($symb);
8860: my $title='';
1.907 albertel 8861: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8862: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8863: } else {
8864: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8865: &GDBM_READER(),0640)) {
8866: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8867: $title=$bighash{'title_'.$mapid.'.'.$resid};
8868: untie(%bighash);
8869: }
1.534 albertel 8870: }
8871: $title=~s/\&colon\;/\:/gs;
8872: if ($title) {
1.599 albertel 8873: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8874: }
8875: $urlsymb=$url;
8876: }
8877: my $title=&metadata($urlsymb,'title');
8878: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8879: return $title;
1.301 www 8880: }
1.613 albertel 8881:
1.614 albertel 8882: sub get_slot {
8883: my ($which,$cnum,$cdom)=@_;
8884: if (!$cnum || !$cdom) {
1.790 albertel 8885: (undef,my $courseid)=&whichuser();
1.620 albertel 8886: $cdom=$env{'course.'.$courseid.'.domain'};
8887: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8888: }
1.703 albertel 8889: my $key=join("\0",'slots',$cdom,$cnum,$which);
8890: my %slotinfo;
8891: if (exists($remembered{$key})) {
8892: $slotinfo{$which} = $remembered{$key};
8893: } else {
8894: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8895: &Apache::lonhomework::showhash(%slotinfo);
8896: my ($tmp)=keys(%slotinfo);
8897: if ($tmp=~/^error:/) { return (); }
8898: $remembered{$key} = $slotinfo{$which};
8899: }
1.616 albertel 8900: if (ref($slotinfo{$which}) eq 'HASH') {
8901: return %{$slotinfo{$which}};
8902: }
8903: return $slotinfo{$which};
1.614 albertel 8904: }
1.31 www 8905: # ------------------------------------------------- Update symbolic store links
8906:
8907: sub symblist {
8908: my ($mapname,%newhash)=@_;
1.438 www 8909: $mapname=&deversion(&declutter($mapname));
1.31 www 8910: my %hash;
1.620 albertel 8911: if (($env{'request.course.fn'}) && (%newhash)) {
8912: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8913: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8914: foreach my $url (keys(%newhash)) {
1.711 albertel 8915: next if ($url eq 'last_known'
8916: && $env{'form.no_update_last_known'});
8917: $hash{declutter($url)}=&encode_symb($mapname,
8918: $newhash{$url}->[1],
8919: $newhash{$url}->[0]);
1.191 harris41 8920: }
1.31 www 8921: if (untie(%hash)) {
8922: return 'ok';
8923: }
8924: }
8925: }
8926: return 'error';
1.212 www 8927: }
8928:
8929: # --------------------------------------------------------------- Verify a symb
8930:
8931: sub symbverify {
1.510 www 8932: my ($symb,$thisurl)=@_;
8933: my $thisfn=$thisurl;
1.439 www 8934: $thisfn=&declutter($thisfn);
1.215 www 8935: # direct jump to resource in page or to a sequence - will construct own symbs
8936: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8937: # check URL part
1.409 www 8938: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8939:
1.431 www 8940: unless ($url eq $thisfn) { return 0; }
1.213 www 8941:
1.216 www 8942: $symb=&symbclean($symb);
1.510 www 8943: $thisurl=&deversion($thisurl);
1.439 www 8944: $thisfn=&deversion($thisfn);
1.213 www 8945:
8946: my %bighash;
8947: my $okay=0;
1.431 www 8948:
1.620 albertel 8949: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8950: &GDBM_READER(),0640)) {
1.1032 raeburn 8951: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8952: $thisurl =~ s/\?.+$//;
8953: }
1.510 www 8954: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8955: unless ($ids) {
1.510 www 8956: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8957: }
8958: if ($ids) {
8959: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8960: foreach my $id (split(/\,/,$ids)) {
8961: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8962: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8963: $symb =~ s/\?.+$//;
8964: }
1.216 www 8965: if (
8966: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8967: eq $symb) {
1.620 albertel 8968: if (($env{'request.role.adv'}) ||
1.800 albertel 8969: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8970: $okay=1;
8971: }
8972: }
1.216 www 8973: }
8974: }
1.213 www 8975: untie(%bighash);
8976: }
8977: return $okay;
1.31 www 8978: }
8979:
1.210 www 8980: # --------------------------------------------------------------- Clean-up symb
8981:
8982: sub symbclean {
8983: my $symb=shift;
1.568 albertel 8984: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8985: # remove version from map
8986: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8987:
1.210 www 8988: # remove version from URL
8989: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8990:
1.507 www 8991: # remove wrapper
8992:
1.510 www 8993: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8994: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8995: return $symb;
1.409 www 8996: }
8997:
8998: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8999:
9000: sub encode_symb {
9001: my ($map,$resid,$url)=@_;
9002: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9003: }
1.409 www 9004:
9005: sub decode_symb {
1.568 albertel 9006: my $symb=shift;
9007: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9008: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9009: return (&fixversion($map),$resid,&fixversion($url));
9010: }
9011:
9012: sub fixversion {
9013: my $fn=shift;
1.609 banghart 9014: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9015: my %bighash;
9016: my $uri=&clutter($fn);
1.620 albertel 9017: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9018: # is this cached?
1.599 albertel 9019: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9020: if (defined($cached)) { return $result; }
9021: # unfortunately not cached, or expired
1.620 albertel 9022: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9023: &GDBM_READER(),0640)) {
9024: if ($bighash{'version_'.$uri}) {
9025: my $version=$bighash{'version_'.$uri};
1.444 www 9026: unless (($version eq 'mostrecent') ||
9027: ($version==&getversion($uri))) {
1.440 www 9028: $uri=~s/\.(\w+)$/\.$version\.$1/;
9029: }
9030: }
9031: untie %bighash;
1.413 www 9032: }
1.599 albertel 9033: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9034: }
9035:
9036: sub deversion {
9037: my $url=shift;
9038: $url=~s/\.\d+\.(\w+)$/\.$1/;
9039: return $url;
1.210 www 9040: }
9041:
1.31 www 9042: # ------------------------------------------------------ Return symb list entry
9043:
9044: sub symbread {
1.249 www 9045: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9046: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9047: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9048: # no filename provided? try from environment
1.44 www 9049: unless ($thisfn) {
1.620 albertel 9050: if ($env{'request.symb'}) {
9051: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9052: }
1.620 albertel 9053: $thisfn=$env{'request.filename'};
1.44 www 9054: }
1.569 albertel 9055: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9056: # is that filename actually a symb? Verify, clean, and return
9057: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9058: if (&symbverify($thisfn,$1)) {
1.620 albertel 9059: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9060: }
1.242 www 9061: }
1.44 www 9062: $thisfn=declutter($thisfn);
1.31 www 9063: my %hash;
1.37 www 9064: my %bighash;
9065: my $syval='';
1.620 albertel 9066: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9067: my $targetfn = $thisfn;
1.609 banghart 9068: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9069: $targetfn = 'adm/wrapper/'.$thisfn;
9070: }
1.687 albertel 9071: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9072: $targetfn=$1;
9073: }
1.620 albertel 9074: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9075: &GDBM_READER(),0640)) {
1.481 raeburn 9076: $syval=$hash{$targetfn};
1.37 www 9077: untie(%hash);
9078: }
9079: # ---------------------------------------------------------- There was an entry
9080: if ($syval) {
1.601 albertel 9081: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9082: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9083: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9084: #return $env{$cache_str}='';
1.601 albertel 9085: #}
9086: #$syval.=$1;
9087: #}
1.37 www 9088: } else {
9089: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9090: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9091: &GDBM_READER(),0640)) {
1.37 www 9092: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9093: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9094: unless ($ids) {
9095: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9096: }
9097: unless ($ids) {
9098: # alias?
9099: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9100: }
1.37 www 9101: if ($ids) {
9102: # ------------------------------------------------------------------- Has ID(s)
9103: my @possibilities=split(/\,/,$ids);
1.39 www 9104: if ($#possibilities==0) {
9105: # ----------------------------------------------- There is only one possibility
1.37 www 9106: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9107: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9108: $resid,$thisfn);
1.249 www 9109: } elsif (!$donotrecurse) {
1.39 www 9110: # ------------------------------------------ There is more than one possibility
9111: my $realpossible=0;
1.800 albertel 9112: foreach my $id (@possibilities) {
9113: my $file=$bighash{'src_'.$id};
1.39 www 9114: if (&allowed('bre',$file)) {
1.800 albertel 9115: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9116: if ($bighash{'map_type_'.$mapid} ne 'page') {
9117: $realpossible++;
1.626 albertel 9118: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9119: $resid,$thisfn);
1.39 www 9120: }
9121: }
1.191 harris41 9122: }
1.39 www 9123: if ($realpossible!=1) { $syval=''; }
1.249 www 9124: } else {
9125: $syval='';
1.37 www 9126: }
9127: }
9128: untie(%bighash)
1.481 raeburn 9129: }
1.31 www 9130: }
1.62 www 9131: if ($syval) {
1.620 albertel 9132: return $env{$cache_str}=$syval;
1.62 www 9133: }
1.31 www 9134: }
1.949 raeburn 9135: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9136: return $env{$cache_str}='';
1.31 www 9137: }
9138:
9139: # ---------------------------------------------------------- Return random seed
9140:
1.32 www 9141: sub numval {
9142: my $txt=shift;
9143: $txt=~tr/A-J/0-9/;
9144: $txt=~tr/a-j/0-9/;
9145: $txt=~tr/K-T/0-9/;
9146: $txt=~tr/k-t/0-9/;
9147: $txt=~tr/U-Z/0-5/;
9148: $txt=~tr/u-z/0-5/;
9149: $txt=~s/\D//g;
1.564 albertel 9150: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9151: return int($txt);
1.368 albertel 9152: }
9153:
1.484 albertel 9154: sub numval2 {
9155: my $txt=shift;
9156: $txt=~tr/A-J/0-9/;
9157: $txt=~tr/a-j/0-9/;
9158: $txt=~tr/K-T/0-9/;
9159: $txt=~tr/k-t/0-9/;
9160: $txt=~tr/U-Z/0-5/;
9161: $txt=~tr/u-z/0-5/;
9162: $txt=~s/\D//g;
9163: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9164: my $total;
9165: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9166: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9167: return int($total);
9168: }
9169:
1.575 albertel 9170: sub numval3 {
9171: use integer;
9172: my $txt=shift;
9173: $txt=~tr/A-J/0-9/;
9174: $txt=~tr/a-j/0-9/;
9175: $txt=~tr/K-T/0-9/;
9176: $txt=~tr/k-t/0-9/;
9177: $txt=~tr/U-Z/0-5/;
9178: $txt=~tr/u-z/0-5/;
9179: $txt=~s/\D//g;
9180: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9181: my $total;
9182: foreach my $val (@txts) { $total+=$val; }
9183: if ($_64bit) { $total=(($total<<32)>>32); }
9184: return $total;
9185: }
9186:
1.675 albertel 9187: sub digest {
9188: my ($data)=@_;
9189: my $digest=&Digest::MD5::md5($data);
9190: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9191: my ($e,$f);
9192: {
9193: use integer;
9194: $e=($a+$b);
9195: $f=($c+$d);
9196: if ($_64bit) {
9197: $e=(($e<<32)>>32);
9198: $f=(($f<<32)>>32);
9199: }
9200: }
9201: if (wantarray) {
9202: return ($e,$f);
9203: } else {
9204: my $g;
9205: {
9206: use integer;
9207: $g=($e+$f);
9208: if ($_64bit) {
9209: $g=(($g<<32)>>32);
9210: }
9211: }
9212: return $g;
9213: }
9214: }
9215:
1.368 albertel 9216: sub latest_rnd_algorithm_id {
1.675 albertel 9217: return '64bit5';
1.366 albertel 9218: }
1.32 www 9219:
1.503 albertel 9220: sub get_rand_alg {
9221: my ($courseid)=@_;
1.790 albertel 9222: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9223: if ($courseid) {
1.620 albertel 9224: return $env{"course.$courseid.rndseed"};
1.503 albertel 9225: }
9226: return &latest_rnd_algorithm_id();
9227: }
9228:
1.562 albertel 9229: sub validCODE {
9230: my ($CODE)=@_;
9231: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9232: return 0;
9233: }
9234:
1.491 albertel 9235: sub getCODE {
1.620 albertel 9236: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9237: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9238: defined($Apache::lonhomework::parsing_a_task) ) &&
9239: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9240: return $Apache::lonhomework::history{'resource.CODE'};
9241: }
9242: return undef;
9243: }
9244:
1.31 www 9245: sub rndseed {
1.155 albertel 9246: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9247: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9248: if (!defined($symb)) {
1.366 albertel 9249: unless ($symb=$wsymb) { return time; }
9250: }
9251: if (!$courseid) { $courseid=$wcourseid; }
9252: if (!$domain) { $domain=$wdomain; }
9253: if (!$username) { $username=$wusername }
1.503 albertel 9254: my $which=&get_rand_alg();
1.803 albertel 9255:
1.491 albertel 9256: if (defined(&getCODE())) {
1.675 albertel 9257: if ($which eq '64bit5') {
9258: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9259: } elsif ($which eq '64bit4') {
1.575 albertel 9260: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9261: } else {
9262: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9263: }
1.675 albertel 9264: } elsif ($which eq '64bit5') {
9265: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9266: } elsif ($which eq '64bit4') {
9267: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9268: } elsif ($which eq '64bit3') {
9269: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9270: } elsif ($which eq '64bit2') {
9271: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9272: } elsif ($which eq '64bit') {
9273: return &rndseed_64bit($symb,$courseid,$domain,$username);
9274: }
9275: return &rndseed_32bit($symb,$courseid,$domain,$username);
9276: }
9277:
9278: sub rndseed_32bit {
9279: my ($symb,$courseid,$domain,$username)=@_;
9280: {
9281: use integer;
9282: my $symbchck=unpack("%32C*",$symb) << 27;
9283: my $symbseed=numval($symb) << 22;
9284: my $namechck=unpack("%32C*",$username) << 17;
9285: my $nameseed=numval($username) << 12;
9286: my $domainseed=unpack("%32C*",$domain) << 7;
9287: my $courseseed=unpack("%32C*",$courseid);
9288: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9289: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9290: #&logthis("rndseed :$num:$symb");
1.564 albertel 9291: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9292: return $num;
9293: }
9294: }
9295:
9296: sub rndseed_64bit {
9297: my ($symb,$courseid,$domain,$username)=@_;
9298: {
9299: use integer;
9300: my $symbchck=unpack("%32S*",$symb) << 21;
9301: my $symbseed=numval($symb) << 10;
9302: my $namechck=unpack("%32S*",$username);
9303:
9304: my $nameseed=numval($username) << 21;
9305: my $domainseed=unpack("%32S*",$domain) << 10;
9306: my $courseseed=unpack("%32S*",$courseid);
9307:
9308: my $num1=$symbchck+$symbseed+$namechck;
9309: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9310: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9311: #&logthis("rndseed :$num:$symb");
1.564 albertel 9312: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9313: return "$num1,$num2";
1.155 albertel 9314: }
1.366 albertel 9315: }
9316:
1.443 albertel 9317: sub rndseed_64bit2 {
9318: my ($symb,$courseid,$domain,$username)=@_;
9319: {
9320: use integer;
9321: # strings need to be an even # of cahracters long, it it is odd the
9322: # last characters gets thrown away
9323: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9324: my $symbseed=numval($symb) << 10;
9325: my $namechck=unpack("%32S*",$username.' ');
9326:
9327: my $nameseed=numval($username) << 21;
1.501 albertel 9328: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9329: my $courseseed=unpack("%32S*",$courseid.' ');
9330:
9331: my $num1=$symbchck+$symbseed+$namechck;
9332: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9333: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9334: #&logthis("rndseed :$num:$symb");
1.803 albertel 9335: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9336: return "$num1,$num2";
9337: }
9338: }
9339:
9340: sub rndseed_64bit3 {
9341: my ($symb,$courseid,$domain,$username)=@_;
9342: {
9343: use integer;
9344: # strings need to be an even # of cahracters long, it it is odd the
9345: # last characters gets thrown away
9346: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9347: my $symbseed=numval2($symb) << 10;
9348: my $namechck=unpack("%32S*",$username.' ');
9349:
9350: my $nameseed=numval2($username) << 21;
1.443 albertel 9351: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9352: my $courseseed=unpack("%32S*",$courseid.' ');
9353:
9354: my $num1=$symbchck+$symbseed+$namechck;
9355: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9356: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9357: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9358: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9359:
1.503 albertel 9360: return "$num1:$num2";
1.443 albertel 9361: }
9362: }
9363:
1.575 albertel 9364: sub rndseed_64bit4 {
9365: my ($symb,$courseid,$domain,$username)=@_;
9366: {
9367: use integer;
9368: # strings need to be an even # of cahracters long, it it is odd the
9369: # last characters gets thrown away
9370: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9371: my $symbseed=numval3($symb) << 10;
9372: my $namechck=unpack("%32S*",$username.' ');
9373:
9374: my $nameseed=numval3($username) << 21;
9375: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9376: my $courseseed=unpack("%32S*",$courseid.' ');
9377:
9378: my $num1=$symbchck+$symbseed+$namechck;
9379: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9380: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9381: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9382: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9383:
9384: return "$num1:$num2";
9385: }
9386: }
9387:
1.675 albertel 9388: sub rndseed_64bit5 {
9389: my ($symb,$courseid,$domain,$username)=@_;
9390: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9391: return "$num1:$num2";
9392: }
9393:
1.366 albertel 9394: sub rndseed_CODE_64bit {
9395: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9396: {
1.366 albertel 9397: use integer;
1.443 albertel 9398: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9399: my $symbseed=numval2($symb);
1.491 albertel 9400: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9401: my $CODEseed=numval(&getCODE());
1.443 albertel 9402: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9403: my $num1=$symbseed+$CODEchck;
9404: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9405: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9406: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9407: if ($_64bit) { $num1=(($num1<<32)>>32); }
9408: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9409: return "$num1:$num2";
1.366 albertel 9410: }
9411: }
9412:
1.575 albertel 9413: sub rndseed_CODE_64bit4 {
9414: my ($symb,$courseid,$domain,$username)=@_;
9415: {
9416: use integer;
9417: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9418: my $symbseed=numval3($symb);
9419: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9420: my $CODEseed=numval3(&getCODE());
9421: my $courseseed=unpack("%32S*",$courseid.' ');
9422: my $num1=$symbseed+$CODEchck;
9423: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9424: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9425: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9426: if ($_64bit) { $num1=(($num1<<32)>>32); }
9427: if ($_64bit) { $num2=(($num2<<32)>>32); }
9428: return "$num1:$num2";
9429: }
9430: }
9431:
1.675 albertel 9432: sub rndseed_CODE_64bit5 {
9433: my ($symb,$courseid,$domain,$username)=@_;
9434: my $code = &getCODE();
9435: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9436: return "$num1:$num2";
9437: }
9438:
1.366 albertel 9439: sub setup_random_from_rndseed {
9440: my ($rndseed)=@_;
1.503 albertel 9441: if ($rndseed =~/([,:])/) {
9442: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9443: &Math::Random::random_set_seed(abs($num1),abs($num2));
9444: } else {
9445: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9446: }
1.36 albertel 9447: }
9448:
1.474 albertel 9449: sub latest_receipt_algorithm_id {
1.835 albertel 9450: return 'receipt3';
1.474 albertel 9451: }
9452:
1.480 www 9453: sub recunique {
9454: my $fucourseid=shift;
9455: my $unique;
1.835 albertel 9456: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9457: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9458: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9459: } else {
9460: $unique=$perlvar{'lonReceipt'};
9461: }
9462: return unpack("%32C*",$unique);
9463: }
9464:
9465: sub recprefix {
9466: my $fucourseid=shift;
9467: my $prefix;
1.835 albertel 9468: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9469: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9470: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9471: } else {
9472: $prefix=$perlvar{'lonHostID'};
9473: }
9474: return unpack("%32C*",$prefix);
9475: }
9476:
1.76 www 9477: sub ireceipt {
1.474 albertel 9478: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9479:
9480: my $return =&recprefix($fucourseid).'-';
9481:
9482: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9483: $env{'request.state'} eq 'construct') {
9484: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9485: return $return;
9486: }
9487:
1.76 www 9488: my $cuname=unpack("%32C*",$funame);
9489: my $cudom=unpack("%32C*",$fudom);
9490: my $cucourseid=unpack("%32C*",$fucourseid);
9491: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9492: my $cunique=&recunique($fucourseid);
1.474 albertel 9493: my $cpart=unpack("%32S*",$part);
1.835 albertel 9494: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9495:
1.790 albertel 9496: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9497:
9498: $return.= ($cunique%$cuname+
9499: $cunique%$cudom+
9500: $cusymb%$cuname+
9501: $cusymb%$cudom+
9502: $cucourseid%$cuname+
9503: $cucourseid%$cudom+
9504: $cpart%$cuname+
9505: $cpart%$cudom);
9506: } else {
9507: $return.= ($cunique%$cuname+
9508: $cunique%$cudom+
9509: $cusymb%$cuname+
9510: $cusymb%$cudom+
9511: $cucourseid%$cuname+
9512: $cucourseid%$cudom);
9513: }
9514: return $return;
1.76 www 9515: }
9516:
9517: sub receipt {
1.474 albertel 9518: my ($part)=@_;
1.790 albertel 9519: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9520: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9521: }
1.260 ng 9522:
1.790 albertel 9523: sub whichuser {
9524: my ($passedsymb)=@_;
9525: my ($symb,$courseid,$domain,$name,$publicuser);
9526: if (defined($env{'form.grade_symb'})) {
9527: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9528: my $allowed=&allowed('vgr',$tmp_courseid);
9529: if (!$allowed &&
9530: exists($env{'request.course.sec'}) &&
9531: $env{'request.course.sec'} !~ /^\s*$/) {
9532: $allowed=&allowed('vgr',$tmp_courseid.
9533: '/'.$env{'request.course.sec'});
9534: }
9535: if ($allowed) {
9536: ($symb)=&get_env_multiple('form.grade_symb');
9537: $courseid=$tmp_courseid;
9538: ($domain)=&get_env_multiple('form.grade_domain');
9539: ($name)=&get_env_multiple('form.grade_username');
9540: return ($symb,$courseid,$domain,$name,$publicuser);
9541: }
9542: }
9543: if (!$passedsymb) {
9544: $symb=&symbread();
9545: } else {
9546: $symb=$passedsymb;
9547: }
9548: $courseid=$env{'request.course.id'};
9549: $domain=$env{'user.domain'};
9550: $name=$env{'user.name'};
9551: if ($name eq 'public' && $domain eq 'public') {
9552: if (!defined($env{'form.username'})) {
9553: $env{'form.username'}.=time.rand(10000000);
9554: }
9555: $name.=$env{'form.username'};
9556: }
9557: return ($symb,$courseid,$domain,$name,$publicuser);
9558:
9559: }
9560:
1.36 albertel 9561: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9562: # returns either the contents of the file or
9563: # -1 if the file doesn't exist
1.481 raeburn 9564: #
9565: # if the target is a file that was uploaded via DOCS,
9566: # a check will be made to see if a current copy exists on the local server,
9567: # if it does this will be served, otherwise a copy will be retrieved from
9568: # the home server for the course and stored in /home/httpd/html/userfiles on
9569: # the local server.
1.472 albertel 9570:
1.36 albertel 9571: sub getfile {
1.538 albertel 9572: my ($file) = @_;
1.609 banghart 9573: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9574: &repcopy($file);
9575: return &readfile($file);
9576: }
9577:
9578: sub repcopy_userfile {
9579: my ($file)=@_;
1.609 banghart 9580: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9581: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9582: my ($cdom,$cnum,$filename) =
1.811 albertel 9583: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9584: my $uri="/uploaded/$cdom/$cnum/$filename";
9585: if (-e "$file") {
1.828 www 9586: # we already have a local copy, check it out
1.538 albertel 9587: my @fileinfo = stat($file);
1.828 www 9588: my $rtncode;
9589: my $info;
1.538 albertel 9590: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9591: if ($lwpresp ne 'ok') {
1.828 www 9592: # there is no such file anymore, even though we had a local copy
1.482 albertel 9593: if ($rtncode eq '404') {
1.538 albertel 9594: unlink($file);
1.482 albertel 9595: }
9596: return -1;
9597: }
9598: if ($info < $fileinfo[9]) {
1.828 www 9599: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9600: return 'ok';
1.828 www 9601: } else {
9602: # the file is outdated, get rid of it
9603: unlink($file);
1.482 albertel 9604: }
1.828 www 9605: }
9606: # one way or the other, at this point, we don't have the file
9607: # construct the correct path for the file
9608: my @parts = ($cdom,$cnum);
9609: if ($filename =~ m|^(.+)/[^/]+$|) {
9610: push @parts, split(/\//,$1);
9611: }
9612: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9613: foreach my $part (@parts) {
9614: $path .= '/'.$part;
9615: if (!-e $path) {
9616: mkdir($path,0770);
1.482 albertel 9617: }
9618: }
1.828 www 9619: # now the path exists for sure
9620: # get a user agent
9621: my $ua=new LWP::UserAgent;
9622: my $transferfile=$file.'.in.transfer';
9623: # FIXME: this should flock
9624: if (-e $transferfile) { return 'ok'; }
9625: my $request;
9626: $uri=~s/^\///;
1.980 raeburn 9627: my $homeserver = &homeserver($cnum,$cdom);
9628: my $protocol = $protocol{$homeserver};
9629: $protocol = 'http' if ($protocol ne 'https');
9630: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9631: my $response=$ua->request($request,$transferfile);
9632: # did it work?
9633: if ($response->is_error()) {
9634: unlink($transferfile);
9635: &logthis("Userfile repcopy failed for $uri");
9636: return -1;
9637: }
9638: # worked, rename the transfer file
9639: rename($transferfile,$file);
1.607 raeburn 9640: return 'ok';
1.481 raeburn 9641: }
9642:
1.517 albertel 9643: sub tokenwrapper {
9644: my $uri=shift;
1.980 raeburn 9645: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9646: $uri=~s|^/||;
1.620 albertel 9647: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9648: my $token=$1;
1.552 albertel 9649: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9650: if ($udom && $uname && $file) {
9651: $file=~s|(\?\.*)*$||;
1.949 raeburn 9652: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9653: my $homeserver = &homeserver($uname,$udom);
9654: my $protocol = $protocol{$homeserver};
9655: $protocol = 'http' if ($protocol ne 'https');
9656: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9657: (($uri=~/\?/)?'&':'?').'token='.$token.
9658: '&tokenissued='.$perlvar{'lonHostID'};
9659: } else {
9660: return '/adm/notfound.html';
9661: }
9662: }
9663:
1.828 www 9664: # call with reqtype HEAD: get last modification time
9665: # call with reqtype GET: get the file contents
9666: # Do not call this with reqtype GET for large files! It loads everything into memory
9667: #
1.481 raeburn 9668: sub getuploaded {
9669: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9670: $uri=~s/^\///;
1.980 raeburn 9671: my $homeserver = &homeserver($cnum,$cdom);
9672: my $protocol = $protocol{$homeserver};
9673: $protocol = 'http' if ($protocol ne 'https');
9674: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9675: my $ua=new LWP::UserAgent;
9676: my $request=new HTTP::Request($reqtype,$uri);
9677: my $response=$ua->request($request);
9678: $$rtncode = $response->code;
1.482 albertel 9679: if (! $response->is_success()) {
9680: return 'failed';
9681: }
9682: if ($reqtype eq 'HEAD') {
1.486 www 9683: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9684: } elsif ($reqtype eq 'GET') {
9685: $$info = $response->content;
1.472 albertel 9686: }
1.482 albertel 9687: return 'ok';
1.36 albertel 9688: }
9689:
1.481 raeburn 9690: sub readfile {
9691: my $file = shift;
9692: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9693: my $fh;
9694: open($fh,"<$file");
9695: my $a='';
1.800 albertel 9696: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9697: return $a;
9698: }
9699:
1.36 albertel 9700: sub filelocation {
1.590 banghart 9701: my ($dir,$file) = @_;
9702: my $location;
9703: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9704:
9705: if ($file =~ m-^/adm/-) {
9706: $file=~s-^/adm/wrapper/-/-;
9707: $file=~s-^/adm/coursedocs/showdoc/-/-;
9708: }
1.882 albertel 9709:
1.590 banghart 9710: if ($file=~m:^/~:) { # is a contruction space reference
9711: $location = $file;
9712: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9713: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9714: # is a correct contruction space reference
9715: $location = $file;
1.956 raeburn 9716: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9717: $location = $file;
1.609 banghart 9718: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9719: my ($udom,$uname,$filename)=
1.811 albertel 9720: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9721: my $home=&homeserver($uname,$udom);
9722: my $is_me=0;
9723: my @ids=¤t_machine_ids();
9724: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9725: if ($is_me) {
1.955 raeburn 9726: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9727: } else {
9728: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9729: $udom.'/'.$uname.'/'.$filename;
9730: }
1.882 albertel 9731: } elsif ($file =~ m-^/adm/-) {
9732: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9733: } else {
9734: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9735: $file=~s:^/res/:/:;
9736: if ( !( $file =~ m:^/:) ) {
9737: $location = $dir. '/'.$file;
9738: } else {
9739: $location = '/home/httpd/html/res'.$file;
9740: }
1.59 albertel 9741: }
1.590 banghart 9742: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9743: while ($location=~m{/\.\./}) {
9744: if ($location =~ m{/[^/]+/\.\./}) {
9745: $location=~ s{/[^/]+/\.\./}{/}g;
9746: } else {
9747: $location=~ s{/\.\./}{/}g;
9748: }
9749: } #remove dir/..
1.590 banghart 9750: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9751: return $location;
1.46 www 9752: }
1.36 albertel 9753:
1.46 www 9754: sub hreflocation {
9755: my ($dir,$file)=@_;
1.980 raeburn 9756: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9757: $file=filelocation($dir,$file);
1.700 albertel 9758: } elsif ($file=~m-^/adm/-) {
9759: $file=~s-^/adm/wrapper/-/-;
9760: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9761: }
9762: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9763: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9764: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9765: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9766: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9767: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9768: -/uploaded/$1/$2/-x;
1.46 www 9769: }
1.913 albertel 9770: if ($file=~ m{^/userfiles/}) {
9771: $file =~ s{^/userfiles/}{/uploaded/};
9772: }
1.462 albertel 9773: return $file;
1.465 albertel 9774: }
9775:
9776: sub current_machine_domains {
1.853 albertel 9777: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9778: }
9779:
9780: sub machine_domains {
9781: my ($hostname) = @_;
1.465 albertel 9782: my @domains;
1.838 albertel 9783: my %hostname = &all_hostnames();
1.465 albertel 9784: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9785: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9786: if ($hostname eq $name) {
1.844 albertel 9787: push(@domains,&host_domain($id));
1.465 albertel 9788: }
9789: }
9790: return @domains;
9791: }
9792:
9793: sub current_machine_ids {
1.853 albertel 9794: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9795: }
9796:
9797: sub machine_ids {
9798: my ($hostname) = @_;
9799: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9800: my @ids;
1.888 albertel 9801: my %name_to_host = &all_names();
1.889 albertel 9802: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9803: return @{ $name_to_host{$hostname} };
9804: }
9805: return;
1.31 www 9806: }
9807:
1.824 raeburn 9808: sub additional_machine_domains {
9809: my @domains;
9810: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9811: while( my $line = <$fh>) {
9812: $line =~ s/\s//g;
9813: push(@domains,$line);
9814: }
9815: return @domains;
9816: }
9817:
9818: sub default_login_domain {
9819: my $domain = $perlvar{'lonDefDomain'};
9820: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9821: foreach my $posdom (¤t_machine_domains(),
9822: &additional_machine_domains()) {
9823: if (lc($posdom) eq lc($testdomain)) {
9824: $domain=$posdom;
9825: last;
9826: }
9827: }
9828: return $domain;
9829: }
9830:
1.31 www 9831: # ------------------------------------------------------------- Declutters URLs
9832:
9833: sub declutter {
9834: my $thisfn=shift;
1.569 albertel 9835: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9836: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9837: $thisfn=~s/^\///;
1.697 albertel 9838: $thisfn=~s|^adm/wrapper/||;
9839: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9840: $thisfn=~s/^res\///;
1.1032 raeburn 9841: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9842: $thisfn=~s/\?.+$//;
9843: }
1.268 www 9844: return $thisfn;
9845: }
9846:
9847: # ------------------------------------------------------------- Clutter up URLs
9848:
9849: sub clutter {
9850: my $thisfn='/'.&declutter(shift);
1.887 albertel 9851: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9852: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9853: $thisfn='/res'.$thisfn;
9854: }
1.1031 raeburn 9855: if ($thisfn !~m|^/adm|) {
9856: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9857: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9858: } else {
9859: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9860: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9861: if ($embstyle eq 'ssi'
9862: || ($embstyle eq 'hdn')
9863: || ($embstyle eq 'rat')
9864: || ($embstyle eq 'prv')
9865: || ($embstyle eq 'ign')) {
9866: #do nothing with these
9867: } elsif (($embstyle eq 'img')
1.695 albertel 9868: || ($embstyle eq 'emb')
9869: || ($embstyle eq 'wrp')) {
9870: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9871: } elsif ($embstyle eq 'unk'
9872: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9873: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9874: } else {
1.718 www 9875: # &logthis("Got a blank emb style");
1.695 albertel 9876: }
1.694 albertel 9877: }
9878: }
1.31 www 9879: return $thisfn;
1.12 www 9880: }
9881:
1.787 albertel 9882: sub clutter_with_no_wrapper {
9883: my $uri = &clutter(shift);
9884: if ($uri =~ m-^/adm/-) {
9885: $uri =~ s-^/adm/wrapper/-/-;
9886: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9887: }
9888: return $uri;
9889: }
9890:
1.557 albertel 9891: sub freeze_escape {
9892: my ($value)=@_;
9893: if (ref($value)) {
9894: $value=&nfreeze($value);
9895: return '__FROZEN__'.&escape($value);
9896: }
9897: return &escape($value);
9898: }
9899:
1.11 www 9900:
1.557 albertel 9901: sub thaw_unescape {
9902: my ($value)=@_;
9903: if ($value =~ /^__FROZEN__/) {
9904: substr($value,0,10,undef);
9905: $value=&unescape($value);
9906: return &thaw($value);
9907: }
9908: return &unescape($value);
9909: }
9910:
1.436 albertel 9911: sub correct_line_ends {
9912: my ($result)=@_;
9913: $$result =~s/\r\n/\n/mg;
9914: $$result =~s/\r/\n/mg;
1.415 albertel 9915: }
1.1 albertel 9916: # ================================================================ Main Program
9917:
1.184 www 9918: sub goodbye {
1.204 albertel 9919: &logthis("Starting Shut down");
1.443 albertel 9920: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9921: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9922: #converted
1.599 albertel 9923: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9924: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9925: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9926: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9927: #1.1 only
1.870 albertel 9928: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9929: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9930: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9931: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9932: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9933: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9934: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9935: &flushcourselogs();
9936: &logthis("Shutting down");
9937: }
9938:
1.852 albertel 9939: sub get_dns {
1.869 albertel 9940: my ($url,$func,$ignore_cache) = @_;
9941: if (!$ignore_cache) {
9942: my ($content,$cached)=
9943: &Apache::lonnet::is_cached_new('dns',$url);
9944: if ($cached) {
9945: &$func($content);
9946: return;
9947: }
9948: }
9949:
9950: my %alldns;
1.852 albertel 9951: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9952: foreach my $dns (<$config>) {
9953: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9954: my $line = $1;
9955: my ($host,$protocol) = split(/:/,$line);
9956: if ($protocol ne 'https') {
9957: $protocol = 'http';
9958: }
9959: $alldns{$host} = $protocol;
1.869 albertel 9960: }
9961: while (%alldns) {
9962: my ($dns) = keys(%alldns);
1.852 albertel 9963: my $ua=new LWP::UserAgent;
1.979 raeburn 9964: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9965: my $response=$ua->request($request);
1.979 raeburn 9966: delete($alldns{$dns});
1.852 albertel 9967: next if ($response->is_error());
9968: my @content = split("\n",$response->content);
1.869 albertel 9969: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9970: &$func(\@content);
1.869 albertel 9971: return;
1.852 albertel 9972: }
9973: close($config);
1.871 albertel 9974: my $which = (split('/',$url))[3];
9975: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9976: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9977: my @content = <$config>;
9978: &$func(\@content);
9979: return;
1.852 albertel 9980: }
1.327 albertel 9981: # ------------------------------------------------------------ Read domain file
9982: {
1.852 albertel 9983: my $loaded;
1.846 albertel 9984: my %domain;
9985:
1.852 albertel 9986: sub parse_domain_tab {
9987: my ($lines) = @_;
9988: foreach my $line (@$lines) {
9989: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9990:
1.846 albertel 9991: chomp($line);
1.852 albertel 9992: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9993: my %this_domain;
9994: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9995: 'lang_def', 'city', 'longi', 'lati',
9996: 'primary') {
9997: $this_domain{$field} = shift(@elements);
9998: }
9999: $domain{$name} = \%this_domain;
1.852 albertel 10000: }
10001: }
1.864 albertel 10002:
10003: sub reset_domain_info {
10004: undef($loaded);
10005: undef(%domain);
10006: }
10007:
1.852 albertel 10008: sub load_domain_tab {
1.869 albertel 10009: my ($ignore_cache) = @_;
10010: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10011: my $fh;
10012: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10013: my @lines = <$fh>;
10014: &parse_domain_tab(\@lines);
1.448 albertel 10015: }
1.852 albertel 10016: close($fh);
10017: $loaded = 1;
1.327 albertel 10018: }
1.846 albertel 10019:
10020: sub domain {
1.852 albertel 10021: &load_domain_tab() if (!$loaded);
10022:
1.846 albertel 10023: my ($name,$what) = @_;
10024: return if ( !exists($domain{$name}) );
10025:
10026: if (!$what) {
10027: return $domain{$name}{'description'};
10028: }
10029: return $domain{$name}{$what};
10030: }
1.974 raeburn 10031:
10032: sub domain_info {
10033: &load_domain_tab() if (!$loaded);
10034: return %domain;
10035: }
10036:
1.327 albertel 10037: }
10038:
10039:
1.1 albertel 10040: # ------------------------------------------------------------- Read hosts file
10041: {
1.838 albertel 10042: my %hostname;
1.844 albertel 10043: my %hostdom;
1.845 albertel 10044: my %libserv;
1.852 albertel 10045: my $loaded;
1.888 albertel 10046: my %name_to_host;
1.1056.4.6 raeburn 10047: my %internetdom;
1.852 albertel 10048:
10049: sub parse_hosts_tab {
10050: my ($file) = @_;
10051: foreach my $configline (@$file) {
10052: next if ($configline =~ /^(\#|\s*$ )/x);
10053: next if ($configline =~ /^\^/);
10054: chomp($configline);
1.1056.4.6 raeburn 10055: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10056: $name=~s/\s//g;
10057: if ($id && $domain && $role && $name) {
10058: $hostname{$id}=$name;
1.888 albertel 10059: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10060: $hostdom{$id}=$domain;
10061: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10062: if (defined($protocol)) {
10063: if ($protocol eq 'https') {
10064: $protocol{$id} = $protocol;
10065: } else {
10066: $protocol{$id} = 'http';
10067: }
1.968 raeburn 10068: } else {
1.969 raeburn 10069: $protocol{$id} = 'http';
1.968 raeburn 10070: }
1.1056.4.6 raeburn 10071: if (defined($intdom)) {
10072: $internetdom{$id} = $intdom;
10073: }
1.852 albertel 10074: }
10075: }
10076: }
1.864 albertel 10077:
10078: sub reset_hosts_info {
1.897 albertel 10079: &purge_remembered();
1.864 albertel 10080: &reset_domain_info();
10081: &reset_hosts_ip_info();
1.892 albertel 10082: undef(%name_to_host);
1.864 albertel 10083: undef(%hostname);
10084: undef(%hostdom);
10085: undef(%libserv);
10086: undef($loaded);
10087: }
1.1 albertel 10088:
1.852 albertel 10089: sub load_hosts_tab {
1.869 albertel 10090: my ($ignore_cache) = @_;
10091: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10092: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10093: my @config = <$config>;
10094: &parse_hosts_tab(\@config);
10095: close($config);
10096: $loaded=1;
1.1 albertel 10097: }
1.852 albertel 10098:
1.838 albertel 10099: sub hostname {
1.852 albertel 10100: &load_hosts_tab() if (!$loaded);
10101:
1.838 albertel 10102: my ($lonid) = @_;
10103: return $hostname{$lonid};
10104: }
1.845 albertel 10105:
1.838 albertel 10106: sub all_hostnames {
1.852 albertel 10107: &load_hosts_tab() if (!$loaded);
10108:
1.838 albertel 10109: return %hostname;
10110: }
1.845 albertel 10111:
1.888 albertel 10112: sub all_names {
10113: &load_hosts_tab() if (!$loaded);
10114:
10115: return %name_to_host;
10116: }
10117:
1.974 raeburn 10118: sub all_host_domain {
10119: &load_hosts_tab() if (!$loaded);
10120: return %hostdom;
10121: }
10122:
1.845 albertel 10123: sub is_library {
1.852 albertel 10124: &load_hosts_tab() if (!$loaded);
10125:
1.845 albertel 10126: return exists($libserv{$_[0]});
10127: }
10128:
10129: sub all_library {
1.852 albertel 10130: &load_hosts_tab() if (!$loaded);
10131:
1.845 albertel 10132: return %libserv;
10133: }
10134:
1.1056.4.2 raeburn 10135: sub unique_library {
10136: #2x reverse removes all hostnames that appear more than once
10137: my %unique = reverse &all_library();
10138: return reverse %unique;
10139: }
10140:
1.841 albertel 10141: sub get_servers {
1.852 albertel 10142: &load_hosts_tab() if (!$loaded);
10143:
1.841 albertel 10144: my ($domain,$type) = @_;
10145: my %possible_hosts = ($type eq 'library') ? %libserv
10146: : %hostname;
10147: my %result;
1.842 albertel 10148: if (ref($domain) eq 'ARRAY') {
10149: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10150: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10151: $result{$host} = $hostname;
10152: }
10153: }
10154: } else {
10155: while ( my ($host,$hostname) = each(%possible_hosts)) {
10156: if ($hostdom{$host} eq $domain) {
10157: $result{$host} = $hostname;
10158: }
1.841 albertel 10159: }
10160: }
10161: return %result;
10162: }
1.845 albertel 10163:
1.1056.4.2 raeburn 10164: sub get_unique_servers {
10165: my %unique = reverse &get_servers(@_);
10166: return reverse %unique;
10167: }
10168:
1.844 albertel 10169: sub host_domain {
1.852 albertel 10170: &load_hosts_tab() if (!$loaded);
10171:
1.844 albertel 10172: my ($lonid) = @_;
10173: return $hostdom{$lonid};
10174: }
10175:
1.841 albertel 10176: sub all_domains {
1.852 albertel 10177: &load_hosts_tab() if (!$loaded);
10178:
1.841 albertel 10179: my %seen;
10180: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10181: return @uniq;
10182: }
1.1056.4.3 raeburn 10183:
10184: sub internet_dom {
10185: &load_hosts_tab() if (!$loaded);
10186:
10187: my ($lonid) = @_;
10188: return $internetdom{$lonid};
10189: }
1.1 albertel 10190: }
10191:
1.847 albertel 10192: {
10193: my %iphost;
1.856 albertel 10194: my %name_to_ip;
10195: my %lonid_to_ip;
1.869 albertel 10196:
1.847 albertel 10197: sub get_hosts_from_ip {
10198: my ($ip) = @_;
10199: my %iphosts = &get_iphost();
10200: if (ref($iphosts{$ip})) {
10201: return @{$iphosts{$ip}};
10202: }
10203: return;
1.839 albertel 10204: }
1.864 albertel 10205:
10206: sub reset_hosts_ip_info {
10207: undef(%iphost);
10208: undef(%name_to_ip);
10209: undef(%lonid_to_ip);
10210: }
1.856 albertel 10211:
10212: sub get_host_ip {
10213: my ($lonid) = @_;
10214: if (exists($lonid_to_ip{$lonid})) {
10215: return $lonid_to_ip{$lonid};
10216: }
10217: my $name=&hostname($lonid);
10218: my $ip = gethostbyname($name);
10219: return if (!$ip || length($ip) ne 4);
10220: $ip=inet_ntoa($ip);
10221: $name_to_ip{$name} = $ip;
10222: $lonid_to_ip{$lonid} = $ip;
10223: return $ip;
10224: }
1.847 albertel 10225:
10226: sub get_iphost {
1.869 albertel 10227: my ($ignore_cache) = @_;
1.894 albertel 10228:
1.869 albertel 10229: if (!$ignore_cache) {
10230: if (%iphost) {
10231: return %iphost;
10232: }
10233: my ($ip_info,$cached)=
10234: &Apache::lonnet::is_cached_new('iphost','iphost');
10235: if ($cached) {
10236: %iphost = %{$ip_info->[0]};
10237: %name_to_ip = %{$ip_info->[1]};
10238: %lonid_to_ip = %{$ip_info->[2]};
10239: return %iphost;
10240: }
10241: }
1.894 albertel 10242:
10243: # get yesterday's info for fallback
10244: my %old_name_to_ip;
10245: my ($ip_info,$cached)=
10246: &Apache::lonnet::is_cached_new('iphost','iphost');
10247: if ($cached) {
10248: %old_name_to_ip = %{$ip_info->[1]};
10249: }
10250:
1.888 albertel 10251: my %name_to_host = &all_names();
10252: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10253: my $ip;
10254: if (!exists($name_to_ip{$name})) {
10255: $ip = gethostbyname($name);
10256: if (!$ip || length($ip) ne 4) {
1.894 albertel 10257: if (defined($old_name_to_ip{$name})) {
10258: $ip = $old_name_to_ip{$name};
10259: &logthis("Can't find $name defaulting to old $ip");
10260: } else {
10261: &logthis("Name $name no IP found");
10262: next;
10263: }
10264: } else {
10265: $ip=inet_ntoa($ip);
1.847 albertel 10266: }
10267: $name_to_ip{$name} = $ip;
10268: } else {
10269: $ip = $name_to_ip{$name};
1.653 albertel 10270: }
1.888 albertel 10271: foreach my $id (@{ $name_to_host{$name} }) {
10272: $lonid_to_ip{$id} = $ip;
10273: }
10274: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10275: }
1.869 albertel 10276: &Apache::lonnet::do_cache_new('iphost','iphost',
10277: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10278: 48*60*60);
1.869 albertel 10279:
1.847 albertel 10280: return %iphost;
1.598 albertel 10281: }
10282:
1.992 raeburn 10283: #
10284: # Given a DNS returns the loncapa host name for that DNS
10285: #
10286: sub host_from_dns {
10287: my ($dns) = @_;
10288: my @hosts;
10289: my $ip;
10290:
1.993 raeburn 10291: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10292: $ip = $name_to_ip{$dns};
10293: }
10294: if (!$ip) {
10295: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10296: if (length($ip) == 4) {
10297: $ip = &IO::Socket::inet_ntoa($ip);
10298: }
10299: }
10300: if ($ip) {
10301: @hosts = get_hosts_from_ip($ip);
10302: return $hosts[0];
10303: }
10304: return undef;
1.986 foxr 10305: }
1.992 raeburn 10306:
1.1056.4.3 raeburn 10307: sub get_internet_names {
10308: my ($lonid) = @_;
10309: return if ($lonid eq '');
10310: my ($idnref,$cached)=
10311: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10312: if ($cached) {
10313: return $idnref;
10314: }
10315: my $ip = &get_host_ip($lonid);
10316: my @hosts = &get_hosts_from_ip($ip);
10317: my %iphost = &get_iphost();
10318: my (@idns,%seen);
10319: foreach my $id (@hosts) {
10320: my $dom = &host_domain($id);
10321: my $prim_id = &domain($dom,'primary');
10322: my $prim_ip = &get_host_ip($prim_id);
10323: next if ($seen{$prim_ip});
10324: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10325: foreach my $id (@{$iphost{$prim_ip}}) {
10326: my $intdom = &internet_dom($id);
10327: unless (grep(/^\Q$intdom\E$/,@idns)) {
10328: push(@idns,$intdom);
10329: }
10330: }
10331: }
10332: $seen{$prim_ip} = 1;
10333: }
10334: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10335: }
10336:
10337: }
10338:
10339: sub all_loncaparevs {
10340: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
1.986 foxr 10341: }
10342:
1.862 albertel 10343: BEGIN {
10344:
10345: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10346: unless ($readit) {
10347: {
10348: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10349: %perlvar = (%perlvar,%{$configvars});
10350: }
10351:
10352:
1.1 albertel 10353: # ------------------------------------------------------ Read spare server file
10354: {
1.448 albertel 10355: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10356:
10357: while (my $configline=<$config>) {
10358: chomp($configline);
1.284 matthew 10359: if ($configline) {
1.784 albertel 10360: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10361: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10362: push(@{ $spareid{$type} }, $host);
1.1 albertel 10363: }
10364: }
1.448 albertel 10365: close($config);
1.1 albertel 10366: }
1.11 www 10367: # ------------------------------------------------------------ Read permissions
10368: {
1.448 albertel 10369: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10370:
10371: while (my $configline=<$config>) {
1.448 albertel 10372: chomp($configline);
10373: if ($configline) {
10374: my ($role,$perm)=split(/ /,$configline);
10375: if ($perm ne '') { $pr{$role}=$perm; }
10376: }
1.11 www 10377: }
1.448 albertel 10378: close($config);
1.11 www 10379: }
10380:
10381: # -------------------------------------------- Read plain texts for permissions
10382: {
1.448 albertel 10383: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10384:
10385: while (my $configline=<$config>) {
1.448 albertel 10386: chomp($configline);
10387: if ($configline) {
1.742 raeburn 10388: my ($short,@plain)=split(/:/,$configline);
10389: %{$prp{$short}} = ();
10390: if (@plain > 0) {
10391: $prp{$short}{'std'} = $plain[0];
10392: for (my $i=1; $i<@plain; $i++) {
10393: $prp{$short}{'alt'.$i} = $plain[$i];
10394: }
10395: }
1.448 albertel 10396: }
1.135 www 10397: }
1.448 albertel 10398: close($config);
1.135 www 10399: }
10400:
10401: # ---------------------------------------------------------- Read package table
10402: {
1.448 albertel 10403: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10404:
10405: while (my $configline=<$config>) {
1.483 albertel 10406: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10407: chomp($configline);
10408: my ($short,$plain)=split(/:/,$configline);
10409: my ($pack,$name)=split(/\&/,$short);
10410: if ($plain ne '') {
10411: $packagetab{$pack.'&'.$name.'&name'}=$name;
10412: $packagetab{$short}=$plain;
10413: }
1.11 www 10414: }
1.448 albertel 10415: close($config);
1.329 matthew 10416: }
10417:
1.1056.4.3 raeburn 10418: # ---------------------------------------------------------- Read loncaparev table
10419: {
10420: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10421: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10422: while (my $configline=<$config>) {
10423: chomp($configline);
10424: my ($hostid,$loncaparev)=split(/:/,$configline);
10425: $loncaparevs{$hostid}=$loncaparev;
10426: }
10427: close($config);
10428: }
10429: }
10430: }
10431:
10432: # ---------------------------------------------------------- Read serverhostID table
10433: {
10434: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10435: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10436: while (my $configline=<$config>) {
10437: chomp($configline);
10438: my ($name,$id)=split(/:/,$configline);
10439: $serverhomeIDs{$name}=$id;
10440: }
10441: close($config);
10442: }
10443: }
10444: }
10445:
1.1056.4.5 raeburn 10446: {
10447: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10448: if (-e $file) {
10449: my $parser = HTML::LCParser->new($file);
10450: while (my $token = $parser->get_token()) {
10451: if ($token->[0] eq 'S') {
10452: my $item = $token->[1];
10453: my $name = $token->[2]{'name'};
10454: my $value = $token->[2]{'value'};
10455: if ($item ne '' && $name ne '' && $value ne '') {
10456: my $release = $parser->get_text();
10457: $release =~ s/(^\s*|\s*$ )//gx;
10458: $needsrelease{$item.':'.$name.':'.$value} = $release;
10459: }
10460: }
10461: }
10462: }
10463: }
10464:
1.329 matthew 10465: # ------------- set up temporary directory
10466: {
10467: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10468:
1.11 www 10469: }
10470:
1.794 albertel 10471: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10472: 'compress_threshold'=> 20_000,
10473: });
1.185 www 10474:
1.281 www 10475: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10476: $dumpcount=0;
1.958 www 10477: $locknum=0;
1.22 www 10478:
1.163 harris41 10479: &logtouch();
1.672 albertel 10480: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10481: $readit=1;
1.564 albertel 10482: {
10483: use integer;
10484: my $test=(2**32)+1;
1.568 albertel 10485: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10486: &logthis(" Detected 64bit platform ($_64bit)");
10487: }
1.195 www 10488: }
1.1 albertel 10489: }
1.179 www 10490:
1.1 albertel 10491: 1;
1.191 harris41 10492: __END__
10493:
1.243 albertel 10494: =pod
10495:
1.191 harris41 10496: =head1 NAME
10497:
1.243 albertel 10498: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10499:
10500: =head1 SYNOPSIS
10501:
1.243 albertel 10502: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10503:
10504: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10505:
1.243 albertel 10506: Common parameters:
10507:
10508: =over 4
10509:
10510: =item *
10511:
10512: $uname : an internal username (if $cname expecting a course Id specifically)
10513:
10514: =item *
10515:
10516: $udom : a domain (if $cdom expecting a course's domain specifically)
10517:
10518: =item *
10519:
10520: $symb : a resource instance identifier
10521:
10522: =item *
10523:
10524: $namespace : the name of a .db file that contains the data needed or
10525: being set.
10526:
10527: =back
10528:
1.394 bowersj2 10529: =head1 OVERVIEW
1.191 harris41 10530:
1.394 bowersj2 10531: lonnet provides subroutines which interact with the
10532: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10533: about classes, users, and resources.
1.243 albertel 10534:
10535: For many of these objects you can also use this to store data about
10536: them or modify them in various ways.
1.191 harris41 10537:
1.394 bowersj2 10538: =head2 Symbs
1.191 harris41 10539:
1.394 bowersj2 10540: To identify a specific instance of a resource, LON-CAPA uses symbols
10541: or "symbs"X<symb>. These identifiers are built from the URL of the
10542: map, the resource number of the resource in the map, and the URL of
10543: the resource itself. The latter is somewhat redundant, but might help
10544: if maps change.
10545:
10546: An example is
10547:
10548: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10549:
10550: The respective map entry is
10551:
10552: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10553: title="Problem 2">
10554: </resource>
10555:
10556: Symbs are used by the random number generator, as well as to store and
10557: restore data specific to a certain instance of for example a problem.
10558:
10559: =head2 Storing And Retrieving Data
10560:
10561: X<store()>X<cstore()>X<restore()>Three of the most important functions
10562: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10563: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10564: is is the non-critical message twin of cstore. These functions are for
10565: handlers to store a perl hash to a user's permanent data space in an
10566: easy manner, and to retrieve it again on another call. It is expected
10567: that a handler would use this once at the beginning to retrieve data,
10568: and then again once at the end to send only the new data back.
10569:
10570: The data is stored in the user's data directory on the user's
10571: homeserver under the ID of the course.
10572:
10573: The hash that is returned by restore will have all of the previous
10574: value for all of the elements of the hash.
10575:
10576: Example:
10577:
10578: #creating a hash
10579: my %hash;
10580: $hash{'foo'}='bar';
10581:
10582: #storing it
10583: &Apache::lonnet::cstore(\%hash);
10584:
10585: #changing a value
10586: $hash{'foo'}='notbar';
10587:
10588: #adding a new value
10589: $hash{'bar'}='foo';
10590: &Apache::lonnet::cstore(\%hash);
10591:
10592: #retrieving the hash
10593: my %history=&Apache::lonnet::restore();
10594:
10595: #print the hash
10596: foreach my $key (sort(keys(%history))) {
10597: print("\%history{$key} = $history{$key}");
10598: }
10599:
10600: Will print out:
1.191 harris41 10601:
1.394 bowersj2 10602: %history{1:foo} = bar
10603: %history{1:keys} = foo:timestamp
10604: %history{1:timestamp} = 990455579
10605: %history{2:bar} = foo
10606: %history{2:foo} = notbar
10607: %history{2:keys} = foo:bar:timestamp
10608: %history{2:timestamp} = 990455580
10609: %history{bar} = foo
10610: %history{foo} = notbar
10611: %history{timestamp} = 990455580
10612: %history{version} = 2
10613:
10614: Note that the special hash entries C<keys>, C<version> and
10615: C<timestamp> were added to the hash. C<version> will be equal to the
10616: total number of versions of the data that have been stored. The
10617: C<timestamp> attribute will be the UNIX time the hash was
10618: stored. C<keys> is available in every historical section to list which
10619: keys were added or changed at a specific historical revision of a
10620: hash.
10621:
10622: B<Warning>: do not store the hash that restore returns directly. This
10623: will cause a mess since it will restore the historical keys as if the
10624: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10625:
1.394 bowersj2 10626: Calling convention:
1.191 harris41 10627:
1.394 bowersj2 10628: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10629: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10630:
1.394 bowersj2 10631: For more detailed information, see lonnet specific documentation.
1.191 harris41 10632:
1.394 bowersj2 10633: =head1 RETURN MESSAGES
1.191 harris41 10634:
1.394 bowersj2 10635: =over 4
1.191 harris41 10636:
1.394 bowersj2 10637: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10638:
1.394 bowersj2 10639: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10640: when the connection is brought back up
1.191 harris41 10641:
1.394 bowersj2 10642: =item * B<con_failed>: unable to contact remote host and unable to save message
10643: for later delivery
1.191 harris41 10644:
1.967 bisitz 10645: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10646:
1.394 bowersj2 10647: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10648: that was requested
1.191 harris41 10649:
1.243 albertel 10650: =back
1.191 harris41 10651:
1.243 albertel 10652: =head1 PUBLIC SUBROUTINES
1.191 harris41 10653:
1.243 albertel 10654: =head2 Session Environment Functions
1.191 harris41 10655:
1.243 albertel 10656: =over 4
1.191 harris41 10657:
1.394 bowersj2 10658: =item *
10659: X<appenv()>
1.949 raeburn 10660: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10661: the user envirnoment file, and will be restored for each access this
1.620 albertel 10662: user makes during this session, also modifies the %env for the current
1.949 raeburn 10663: process. Optional rolesarrayref - if defined contains a reference to an array
10664: of roles which are exempt from the restriction on modifying user.role entries
10665: in the user's environment.db and in %env.
1.191 harris41 10666:
10667: =item *
1.394 bowersj2 10668: X<delenv()>
1.987 raeburn 10669: B<delenv($delthis,$regexp)>: removes all items from the session
10670: environment file that begin with $delthis. If the
10671: optional second arg - $regexp - is true, $delthis is treated as a
10672: regular expression, otherwise \Q$delthis\E is used.
10673: The values are also deleted from the current processes %env.
1.191 harris41 10674:
1.795 albertel 10675: =item * get_env_multiple($name)
10676:
10677: gets $name from the %env hash, it seemlessly handles the cases where multiple
10678: values may be defined and end up as an array ref.
10679:
10680: returns an array of values
10681:
1.243 albertel 10682: =back
10683:
10684: =head2 User Information
1.191 harris41 10685:
1.243 albertel 10686: =over 4
1.191 harris41 10687:
10688: =item *
1.394 bowersj2 10689: X<queryauthenticate()>
10690: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10691: authentication scheme
10692:
10693: =item *
1.394 bowersj2 10694: X<authenticate()>
1.1056.4.3 raeburn 10695: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10696: authenticate user from domain's lib servers (first use the current
10697: one). C<$upass> should be the users password.
1.1056.4.3 raeburn 10698: $checkdefauth is optional (value is 1 if a check should be made to
10699: authenticate user using default authentication method, and allow
10700: account creation if username does not have account in the domain).
10701: $clientcancheckhost is optional (value is 1 if checking whether the
10702: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10703:
10704: =item *
1.394 bowersj2 10705: X<homeserver()>
10706: B<homeserver($uname,$udom)>: find the server which has
10707: the user's directory and files (there must be only one), this caches
10708: the answer, and also caches if there is a borken connection.
1.191 harris41 10709:
10710: =item *
1.394 bowersj2 10711: X<idget()>
10712: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10713: (IDs are a unique resource in a domain, there must be only 1 ID per
10714: username, and only 1 username per ID in a specific domain) (returns
10715: hash: id=>name,id=>name)
1.191 harris41 10716:
10717: =item *
1.394 bowersj2 10718: X<idrget()>
10719: B<idrget($udom,@unames)>: find the IDs behind a list of
10720: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10721:
10722: =item *
1.394 bowersj2 10723: X<idput()>
10724: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10725:
10726: =item *
1.394 bowersj2 10727: X<rolesinit()>
10728: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10729:
10730: =item *
1.551 albertel 10731: X<getsection()>
10732: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10733: course $cname, return section name/number or '' for "not in course"
10734: and '-1' for "no section"
10735:
10736: =item *
1.394 bowersj2 10737: X<userenvironment()>
10738: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10739: passed in @what from the requested user's environment, returns a hash
10740:
1.858 raeburn 10741: =item *
10742: X<userlog_query()>
1.859 albertel 10743: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10744: activity.log file. %filters defines filters applied when parsing the
10745: log file. These can be start or end timestamps, or the type of action
10746: - log to look for Login or Logout events, check for Checkin or
10747: Checkout, role for role selection. The response is in the form
10748: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10749: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10750:
1.243 albertel 10751: =back
10752:
10753: =head2 User Roles
10754:
10755: =over 4
10756:
10757: =item *
10758:
1.810 raeburn 10759: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10760: F: full access
10761: U,I,K: authentication modes (cxx only)
10762: '': forbidden
10763: 1: user needs to choose course
10764: 2: browse allowed
1.766 albertel 10765: A: passphrase authentication needed
1.243 albertel 10766:
10767: =item *
10768:
10769: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10770: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10771: and course level
10772:
10773: =item *
10774:
1.988 raeburn 10775: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10776: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10777: $type is Course (default) or Community.
1.988 raeburn 10778: If $forcedefault evaluates to true, text returned will be default
10779: text for $type. Otherwise, if this is a course, the text returned
10780: will be a custom name for the role (if defined in the course's
10781: environment). If no custom name is defined the default is returned.
10782:
1.832 raeburn 10783: =item *
10784:
1.935 raeburn 10785: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10786: All arguments are optional. Returns a hash of a roles, either for
10787: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10788: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10789: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10790: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10791: For each key, value is set to colon-separated start and end times for
10792: the role. If no username and domain are specified, will default to
1.934 raeburn 10793: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10794: of role statuses (active, future or previous), roles
10795: (e.g., cc,in, st etc.) and domains of the roles which can be used
10796: to restrict the list of roles reported. If no array ref is
10797: provided for types, will default to return only active roles.
1.834 albertel 10798:
1.243 albertel 10799: =back
10800:
10801: =head2 User Modification
10802:
10803: =over 4
10804:
10805: =item *
10806:
1.957 raeburn 10807: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10808: user for the level given by URL. Optional start and end dates (leave empty
10809: string or zero for "no date")
1.191 harris41 10810:
10811: =item *
10812:
1.243 albertel 10813: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10814: change a users, password, possible return values are: ok,
10815: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10816: refused
1.191 harris41 10817:
10818: =item *
10819:
1.243 albertel 10820: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10821:
10822: =item *
10823:
1.1056.4.1 raeburn 10824: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10825: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10826:
10827: will update user information (firstname,middlename,lastname,generation,
10828: permanentemail), and if forceid is true, student/employee ID also.
10829: A user's institutional affiliation(s) can also be updated.
10830: User information fields will not be overwritten with empty entries
10831: unless the field is included in the $candelete array reference.
10832: This array is included when a single user is modified via "Manage Users",
10833: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10834:
10835: =item *
10836:
1.286 matthew 10837: modifystudent
10838:
1.957 raeburn 10839: modify a student's enrollment and identification information.
1.286 matthew 10840: The course id is resolved based on the current users environment.
10841: This means the envoking user must be a course coordinator or otherwise
10842: associated with a course.
10843:
1.297 matthew 10844: This call is essentially a wrapper for lonnet::modifyuser and
10845: lonnet::modify_student_enrollment
1.286 matthew 10846:
10847: Inputs:
10848:
10849: =over 4
10850:
1.957 raeburn 10851: =item B<$udom> Student's loncapa domain
1.286 matthew 10852:
1.957 raeburn 10853: =item B<$uname> Student's loncapa login name
1.286 matthew 10854:
1.964 bisitz 10855: =item B<$uid> Student/Employee ID
1.286 matthew 10856:
1.957 raeburn 10857: =item B<$umode> Student's authentication mode
1.286 matthew 10858:
1.957 raeburn 10859: =item B<$upass> Student's password
1.286 matthew 10860:
1.957 raeburn 10861: =item B<$first> Student's first name
1.286 matthew 10862:
1.957 raeburn 10863: =item B<$middle> Student's middle name
1.286 matthew 10864:
1.957 raeburn 10865: =item B<$last> Student's last name
1.286 matthew 10866:
1.957 raeburn 10867: =item B<$gene> Student's generation
1.286 matthew 10868:
1.957 raeburn 10869: =item B<$usec> Student's section in course
1.286 matthew 10870:
10871: =item B<$end> Unix time of the roles expiration
10872:
10873: =item B<$start> Unix time of the roles start date
10874:
10875: =item B<$forceid> If defined, allow $uid to be changed
10876:
10877: =item B<$desiredhome> server to use as home server for student
10878:
1.957 raeburn 10879: =item B<$email> Student's permanent e-mail address
10880:
10881: =item B<$type> Type of enrollment (auto or manual)
10882:
1.963 raeburn 10883: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10884:
10885: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10886:
1.963 raeburn 10887: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10888:
1.963 raeburn 10889: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10890:
1.963 raeburn 10891: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10892:
1.286 matthew 10893: =back
1.297 matthew 10894:
10895: =item *
10896:
10897: modify_student_enrollment
10898:
10899: Change a students enrollment status in a class. The environment variable
10900: 'role.request.course' must be defined for this function to proceed.
10901:
10902: Inputs:
10903:
10904: =over 4
10905:
10906: =item $udom, students domain
10907:
10908: =item $uname, students name
10909:
10910: =item $uid, students user id
10911:
10912: =item $first, students first name
10913:
10914: =item $middle
10915:
10916: =item $last
10917:
10918: =item $gene
10919:
10920: =item $usec
10921:
10922: =item $end
10923:
10924: =item $start
10925:
1.957 raeburn 10926: =item $type
10927:
10928: =item $locktype
10929:
10930: =item $cid
10931:
10932: =item $selfenroll
10933:
10934: =item $context
10935:
1.297 matthew 10936: =back
10937:
1.191 harris41 10938:
10939: =item *
10940:
1.243 albertel 10941: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10942: custom role; give a custom role to a user for the level given by URL. Specify
10943: name and domain of role author, and role name
1.191 harris41 10944:
10945: =item *
10946:
1.243 albertel 10947: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10948:
10949: =item *
10950:
1.243 albertel 10951: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10952:
10953: =back
10954:
10955: =head2 Course Infomation
10956:
10957: =over 4
1.191 harris41 10958:
10959: =item *
10960:
1.631 albertel 10961: coursedescription($courseid) : returns a hash of information about the
10962: specified course id, including all environment settings for the
10963: course, the description of the course will be in the hash under the
10964: key 'description'
1.191 harris41 10965:
10966: =item *
10967:
1.624 albertel 10968: resdata($name,$domain,$type,@which) : request for current parameter
10969: setting for a specific $type, where $type is either 'course' or 'user',
10970: @what should be a list of parameters to ask about. This routine caches
10971: answers for 5 minutes.
1.243 albertel 10972:
1.877 foxr 10973: =item *
10974:
10975: get_courseresdata($courseid, $domain) : dump the entire course resource
10976: data base, returning a hash that is keyed by the resource name and has
10977: values that are the resource value. I believe that the timestamps and
10978: versions are also returned.
10979:
10980:
1.243 albertel 10981: =back
10982:
10983: =head2 Course Modification
10984:
10985: =over 4
1.191 harris41 10986:
10987: =item *
10988:
1.243 albertel 10989: writecoursepref($courseid,%prefs) : write preferences (environment
10990: database) for a course
1.191 harris41 10991:
10992: =item *
10993:
1.1011 raeburn 10994: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10995:
10996: =item *
10997:
1.1038 raeburn 10998: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10999:
11000: =back
11001:
11002: =head2 Resource Subroutines
11003:
11004: =over 4
1.191 harris41 11005:
11006: =item *
11007:
1.243 albertel 11008: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11009:
11010: =item *
11011:
1.243 albertel 11012: repcopy($filename) : subscribes to the requested file, and attempts to
11013: replicate from the owning library server, Might return
1.607 raeburn 11014: 'unavailable', 'not_found', 'forbidden', 'ok', or
11015: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11016: resource. Expects the local filesystem pathname
11017: (/home/httpd/html/res/....)
11018:
11019: =back
11020:
11021: =head2 Resource Information
11022:
11023: =over 4
1.191 harris41 11024:
11025: =item *
11026:
1.243 albertel 11027: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11028: a vairety of different possible values, $varname should be a request
11029: string, and the other parameters can be used to specify who and what
11030: one is asking about.
11031:
11032: Possible values for $varname are environment.lastname (or other item
11033: from the envirnment hash), user.name (or someother aspect about the
11034: user), resource.0.maxtries (or some other part and parameter of a
11035: resource)
1.204 albertel 11036:
11037: =item *
11038:
1.243 albertel 11039: directcondval($number) : get current value of a condition; reads from a state
11040: string
1.204 albertel 11041:
11042: =item *
11043:
1.243 albertel 11044: condval($condidx) : value of condition index based on state
1.204 albertel 11045:
11046: =item *
11047:
1.243 albertel 11048: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11049: resource's metadata, $what should be either a specific key, or either
11050: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11051: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11052:
11053: this function automatically caches all requests
1.191 harris41 11054:
11055: =item *
11056:
1.243 albertel 11057: metadata_query($query,$custom,$customshow) : make a metadata query against the
11058: network of library servers; returns file handle of where SQL and regex results
11059: will be stored for query
1.191 harris41 11060:
11061: =item *
11062:
1.243 albertel 11063: symbread($filename) : return symbolic list entry (filename argument optional);
11064: returns the data handle
1.191 harris41 11065:
11066: =item *
11067:
1.243 albertel 11068: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11069: a possible symb for the URL in $thisfn, and if is an encryypted
11070: resource that the user accessed using /enc/ returns a 1 on success, 0
11071: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11072: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11073:
1.191 harris41 11074:
11075: =item *
11076:
1.243 albertel 11077: symbclean($symb) : removes versions numbers from a symb, returns the
11078: cleaned symb
1.191 harris41 11079:
11080: =item *
11081:
1.243 albertel 11082: is_on_map($uri) : checks if the $uri is somewhere on the current
11083: course map, user must be in a course for it to work.
1.191 harris41 11084:
11085: =item *
11086:
1.243 albertel 11087: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11088:
11089: =item *
11090:
1.243 albertel 11091: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11092: a random seed, all arguments are optional, if they aren't sent it uses the
11093: environment to derive them. Note: if symb isn't sent and it can't get one
11094: from &symbread it will use the current time as its return value
1.191 harris41 11095:
11096: =item *
11097:
1.243 albertel 11098: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11099: unfakeable, receipt
1.191 harris41 11100:
11101: =item *
11102:
1.620 albertel 11103: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11104:
11105: =item *
11106:
1.243 albertel 11107: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11108:
11109: =item *
11110:
1.243 albertel 11111: 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 11112:
11113: =item *
11114:
1.243 albertel 11115: 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 11116:
11117: =item *
11118:
1.243 albertel 11119: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11120:
11121: =item *
11122:
1.243 albertel 11123: devalidate($symb) : devalidate temporary spreadsheet calculations,
11124: forcing spreadsheet to reevaluate the resource scores next time.
11125:
11126: =back
11127:
11128: =head2 Storing/Retreiving Data
11129:
11130: =over 4
1.191 harris41 11131:
11132: =item *
11133:
1.243 albertel 11134: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11135: for this url; hashref needs to be given and should be a \%hashname; the
11136: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11137: be derived from the env
1.191 harris41 11138:
11139: =item *
11140:
1.243 albertel 11141: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11142: uses critical subroutine
1.191 harris41 11143:
11144: =item *
11145:
1.243 albertel 11146: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11147: all args are optional
1.191 harris41 11148:
11149: =item *
11150:
1.717 albertel 11151: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11152: dumps the complete (or key matching regexp) namespace into a hash
11153: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11154: normally &store()ed into
11155:
11156: $range should be either an integer '100' (give me the first 100
11157: matching records)
11158: or be two integers sperated by a - with no spaces
11159: '30-50' (give me the 30th through the 50th matching
11160: records)
11161:
11162:
11163: =item *
11164:
11165: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11166: replaces a &store() version of data with a replacement set of data
11167: for a particular resource in a namespace passed in the $storehash hash
11168: reference
11169:
11170: =item *
11171:
1.243 albertel 11172: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11173: works very similar to store/cstore, but all data is stored in a
11174: temporary location and can be reset using tmpreset, $storehash should
11175: be a hash reference, returns nothing on success
1.191 harris41 11176:
11177: =item *
11178:
1.243 albertel 11179: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11180: similar to restore, but all data is stored in a temporary location and
11181: can be reset using tmpreset. Returns a hash of values on success,
11182: error string otherwise.
1.191 harris41 11183:
11184: =item *
11185:
1.243 albertel 11186: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11187: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11188:
11189: =item *
11190:
1.243 albertel 11191: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11192: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11193:
11194: =item *
11195:
1.243 albertel 11196: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11197: namesp ($udom and $uname are optional)
1.191 harris41 11198:
11199: =item *
11200:
1.702 albertel 11201: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11202: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11203: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11204:
1.702 albertel 11205: $range should be either an integer '100' (give me the first 100
11206: matching records)
11207: or be two integers sperated by a - with no spaces
11208: '30-50' (give me the 30th through the 50th matching
11209: records)
1.449 matthew 11210: =item *
11211:
11212: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11213: $store can be a scalar, an array reference, or if the amount to be
11214: incremented is > 1, a hash reference.
11215:
11216: ($udom and $uname are optional)
1.191 harris41 11217:
11218: =item *
11219:
1.243 albertel 11220: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11221: ($udom and $uname are optional)
1.191 harris41 11222:
11223: =item *
11224:
1.243 albertel 11225: cput($namespace,$storehash,$udom,$uname) : critical put
11226: ($udom and $uname are optional)
1.191 harris41 11227:
11228: =item *
11229:
1.748 albertel 11230: newput($namespace,$storehash,$udom,$uname) :
11231:
11232: Attempts to store the items in the $storehash, but only if they don't
11233: currently exist, if this succeeds you can be certain that you have
11234: successfully created a new key value pair in the $namespace db.
11235:
11236:
11237: Args:
11238: $namespace: name of database to store values to
11239: $storehash: hashref to store to the db
11240: $udom: (optional) domain of user containing the db
11241: $uname: (optional) name of user caontaining the db
11242:
11243: Returns:
11244: 'ok' -> succeeded in storing all keys of $storehash
11245: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11246: least <key> already existed in the db (other
11247: requested keys may also already exist)
1.967 bisitz 11248: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11249: 'con_lost' -> unable to contact request server
11250: 'refused' -> action was not allowed by remote machine
11251:
11252:
11253: =item *
11254:
1.243 albertel 11255: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11256: reference filled in from namesp (encrypts the return communication)
11257: ($udom and $uname are optional)
1.191 harris41 11258:
11259: =item *
11260:
1.243 albertel 11261: log($udom,$name,$home,$message) : write to permanent log for user; use
11262: critical subroutine
11263:
1.806 raeburn 11264: =item *
11265:
1.860 raeburn 11266: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11267: array reference filled in from namespace found in domain level on either
11268: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11269:
11270: =item *
11271:
1.860 raeburn 11272: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11273: domain level either on specified domain server ($uhome) or primary domain
11274: server ($udom and $uhome are optional)
1.806 raeburn 11275:
1.943 raeburn 11276: =item *
11277:
11278: get_domain_defaults($target_domain) : returns hash with defaults for
11279: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11280: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11281: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11282: Values are retrieved from cache (if current), or from domain's configuration.db
11283: (if available), or lastly from values in lonTabs/dns_domain,tab,
11284: or lonTabs/domain.tab.
11285:
11286: %domdefaults = &get_auth_defaults($target_domain);
11287:
1.243 albertel 11288: =back
11289:
11290: =head2 Network Status Functions
11291:
11292: =over 4
1.191 harris41 11293:
11294: =item *
11295:
11296: dirlist($uri) : return directory list based on URI
11297:
11298: =item *
11299:
1.243 albertel 11300: spareserver() : find server with least workload from spare.tab
11301:
1.986 foxr 11302:
11303: =item *
11304:
11305: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11306: if there is no corresponding loncapa host.
11307:
1.243 albertel 11308: =back
11309:
1.986 foxr 11310:
1.243 albertel 11311: =head2 Apache Request
11312:
11313: =over 4
1.191 harris41 11314:
11315: =item *
11316:
1.243 albertel 11317: ssi($url,%hash) : server side include, does a complete request cycle on url to
11318: localhost, posts hash
11319:
11320: =back
11321:
11322: =head2 Data to String to Data
11323:
11324: =over 4
1.191 harris41 11325:
11326: =item *
11327:
1.243 albertel 11328: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11329: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11330:
11331: =item *
11332:
1.243 albertel 11333: hashref2str($hashref) : convert a hashref into a string complete with
11334: escaping and '=' and '&' separators, supports elements that are
11335: arrayrefs and hashrefs
1.191 harris41 11336:
11337: =item *
11338:
1.243 albertel 11339: arrayref2str($arrayref) : convert an arrayref into a string complete
11340: with escaping and '&' separators, supports elements that are arrayrefs
11341: and hashrefs
1.191 harris41 11342:
11343: =item *
11344:
1.243 albertel 11345: str2hash($string) : convert string to hash using unescaping and
11346: splitting on '=' and '&', supports elements that are arrayrefs and
11347: hashrefs
1.191 harris41 11348:
11349: =item *
11350:
1.243 albertel 11351: str2array($string) : convert string to hash using unescaping and
11352: splitting on '&', supports elements that are arrayrefs and hashrefs
11353:
11354: =back
11355:
11356: =head2 Logging Routines
11357:
11358: =over 4
11359:
11360: These routines allow one to make log messages in the lonnet.log and
11361: lonnet.perm logfiles.
1.191 harris41 11362:
11363: =item *
11364:
1.243 albertel 11365: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11366:
11367: =item *
11368:
1.243 albertel 11369: logthis() : append message to the normal lonnet.log file, it gets
11370: preiodically rolled over and deleted.
1.191 harris41 11371:
11372: =item *
11373:
1.243 albertel 11374: logperm() : append a permanent message to lonnet.perm.log, this log
11375: file never gets deleted by any automated portion of the system, only
11376: messages of critical importance should go in here.
11377:
11378: =back
11379:
11380: =head2 General File Helper Routines
11381:
11382: =over 4
1.191 harris41 11383:
11384: =item *
11385:
1.481 raeburn 11386: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11387: (a) files in /uploaded
11388: (i) If a local copy of the file exists -
11389: compares modification date of local copy with last-modified date for
11390: definitive version stored on home server for course. If local copy is
11391: stale, requests a new version from the home server and stores it.
11392: If the original has been removed from the home server, then local copy
11393: is unlinked.
11394: (ii) If local copy does not exist -
11395: requests the file from the home server and stores it.
11396:
11397: If $caller is 'uploadrep':
11398: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11399: for request for files originally uploaded via DOCS.
11400: - returns 'ok' if fresh local copy now available, -1 otherwise.
11401:
11402: Otherwise:
11403: This indicates a call from the content generation phase of the request.
11404: - returns the entire contents of the file or -1.
11405:
11406: (b) files in /res
11407: - returns the entire contents of a file or -1;
11408: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11409:
1.712 albertel 11410:
11411: =item *
11412:
11413: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11414: reference
11415:
11416: returns either a stat() list of data about the file or an empty list
11417: if the file doesn't exist or couldn't find out about it (connection
11418: problems or user unknown)
11419:
1.191 harris41 11420: =item *
11421:
1.243 albertel 11422: filelocation($dir,$file) : returns file system location of a file
11423: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11424: directory that relative $file lookups are to looked in ($dir of /a/dir
11425: and a file of ../bob will become /a/bob)
1.191 harris41 11426:
11427: =item *
11428:
11429: hreflocation($dir,$file) : returns file system location or a URL; same as
11430: filelocation except for hrefs
11431:
11432: =item *
11433:
11434: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11435:
1.243 albertel 11436: =back
11437:
1.608 albertel 11438: =head2 Usererfile file routines (/uploaded*)
11439:
11440: =over 4
11441:
11442: =item *
11443:
11444: userfileupload(): main rotine for putting a file in a user or course's
11445: filespace, arguments are,
11446:
1.620 albertel 11447: formname - required - this is the name of the element in $env where the
1.608 albertel 11448: filename, and the contents of the file to create/modifed exist
1.620 albertel 11449: the filename is in $env{'form.'.$formname.'.filename'} and the
11450: contents of the file is located in $env{'form.'.$formname}
1.1056.4.13 raeburn 11451: context - if coursedoc, store the file in the course of the active role
11452: of the current user;
11453: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11454: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11455: subdir - required - subdirectory to put the file in under ../userfiles/
11456: if undefined, it will be placed in "unknown"
11457:
11458: (This routine calls clean_filename() to remove any dangerous
11459: characters from the filename, and then calls finuserfileupload() to
11460: complete the transaction)
11461:
11462: returns either the url of the uploaded file (/uploaded/....) if successful
11463: and /adm/notfound.html if unsuccessful
11464:
11465: =item *
11466:
11467: clean_filename(): routine for cleaing a filename up for storage in
11468: userfile space, argument is:
11469:
11470: filename - proposed filename
11471:
11472: returns: the new clean filename
11473:
11474: =item *
11475:
1.1056.4.13 raeburn 11476: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11477: userspace, probably shouldn't be called directly
11478:
11479: docuname: username or courseid of destination for the file
11480: docudom: domain of user/course of destination for the file
11481: formname: same as for userfileupload()
1.1056.4.13 raeburn 11482: fname: filename (including subdirectories) for the file
11483: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11484: allfiles: reference to hash used to store objects found by parser
11485: codebase: reference to hash used for codebases of java objects found by parser
11486: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11487: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11488: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11489: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11490: context: if 'overwrite', will move the uploaded file from its temporary location to
11491: userfiles to facilitate overwriting a previously uploaded file with same name.
1.608 albertel 11492:
11493: returns either the url of the uploaded file (/uploaded/....) if successful
1.1056.4.13 raeburn 11494: and /adm/notfound.html if unsuccessful (or an error message if context
11495: was 'overwrite').
11496:
1.608 albertel 11497:
11498: =item *
11499:
11500: renameuserfile(): renames an existing userfile to a new name
11501:
11502: Args:
11503: docuname: username or courseid of destination for the file
11504: docudom: domain of user/course of destination for the file
11505: old: current file name (including any subdirs under userfiles)
11506: new: desired file name (including any subdirs under userfiles)
11507:
11508: =item *
11509:
11510: mkdiruserfile(): creates a directory is a userfiles dir
11511:
11512: Args:
11513: docuname: username or courseid of destination for the file
11514: docudom: domain of user/course of destination for the file
11515: dir: dir to create (including any subdirs under userfiles)
11516:
11517: =item *
11518:
11519: removeuserfile(): removes a file that exists in userfiles
11520:
11521: Args:
11522: docuname: username or courseid of destination for the file
11523: docudom: domain of user/course of destination for the file
11524: fname: filname to delete (including any subdirs under userfiles)
11525:
11526: =item *
11527:
11528: removeuploadedurl(): convience function for removeuserfile()
11529:
11530: Args:
11531: url: a full /uploaded/... url to delete
11532:
1.747 albertel 11533: =item *
11534:
11535: get_portfile_permissions():
11536: Args:
11537: domain: domain of user or course contain the portfolio files
11538: user: name of user or num of course contain the portfolio files
11539: Returns:
11540: hashref of a dump of the proper file_permissions.db
11541:
11542:
11543: =item *
11544:
11545: get_access_controls():
11546:
11547: Args:
11548: current_permissions: the hash ref returned from get_portfile_permissions()
11549: group: (optional) the group you want the files associated with
11550: file: (optional) the file you want access info on
11551:
11552: Returns:
1.749 raeburn 11553: a hash (keys are file names) of hashes containing
11554: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11555: values are XML containing access control settings (see below)
1.747 albertel 11556:
11557: Internal notes:
11558:
1.749 raeburn 11559: access controls are stored in file_permissions.db as key=value pairs.
11560: key -> path to file/file_name\0uniqueID:scope_end_start
11561: where scope -> public,guest,course,group,domains or users.
11562: end -> UNIX time for end of access (0 -> no end date)
11563: start -> UNIX time for start of access
11564:
11565: value -> XML description of access control
11566: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11567: <start></start>
11568: <end></end>
11569:
11570: <password></password> for scope type = guest
11571:
11572: <domain></domain> for scope type = course or group
11573: <number></number>
11574: <roles id="">
11575: <role></role>
11576: <access></access>
11577: <section></section>
11578: <group></group>
11579: </roles>
11580:
11581: <dom></dom> for scope type = domains
11582:
11583: <users> for scope type = users
11584: <user>
11585: <uname></uname>
11586: <udom></udom>
11587: </user>
11588: </users>
11589: </scope>
11590:
11591: Access data is also aggregated for each file in an additional key=value pair:
11592: key -> path to file/file_name\0accesscontrol
11593: value -> reference to hash
11594: hash contains key = value pairs
11595: where key = uniqueID:scope_end_start
11596: value = UNIX time record was last updated
11597:
11598: Used to improve speed of look-ups of access controls for each file.
11599:
11600: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11601:
11602: modify_access_controls():
11603:
11604: Modifies access controls for a portfolio file
11605: Args
11606: 1. file name
11607: 2. reference to hash of required changes,
11608: 3. domain
11609: 4. username
11610: where domain,username are the domain of the portfolio owner
11611: (either a user or a course)
11612:
11613: Returns:
11614: 1. result of additions or updates ('ok' or 'error', with error message).
11615: 2. result of deletions ('ok' or 'error', with error message).
11616: 3. reference to hash of any new or updated access controls.
11617: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11618: key = integer (inbound ID)
11619: value = uniqueID
1.747 albertel 11620:
1.608 albertel 11621: =back
11622:
1.243 albertel 11623: =head2 HTTP Helper Routines
11624:
11625: =over 4
11626:
1.191 harris41 11627: =item *
11628:
11629: escape() : unpack non-word characters into CGI-compatible hex codes
11630:
11631: =item *
11632:
11633: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11634:
1.243 albertel 11635: =back
11636:
11637: =head1 PRIVATE SUBROUTINES
11638:
11639: =head2 Underlying communication routines (Shouldn't call)
11640:
11641: =over 4
11642:
11643: =item *
11644:
11645: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11646:
11647: =item *
11648:
11649: reply() : uses subreply to send a message to remote machine, logs all failures
11650:
11651: =item *
11652:
11653: critical() : passes a critical message to another server; if cannot
11654: get through then place message in connection buffer directory and
11655: returns con_delayed, if incapable of saving message, returns
11656: con_failed
11657:
11658: =item *
11659:
11660: reconlonc() : tries to reconnect lonc client processes.
11661:
11662: =back
11663:
11664: =head2 Resource Access Logging
11665:
11666: =over 4
11667:
11668: =item *
11669:
11670: flushcourselogs() : flush (save) buffer logs and access logs
11671:
11672: =item *
11673:
11674: courselog($what) : save message for course in hash
11675:
11676: =item *
11677:
11678: courseacclog($what) : save message for course using &courselog(). Perform
11679: special processing for specific resource types (problems, exams, quizzes, etc).
11680:
1.191 harris41 11681: =item *
11682:
11683: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11684: as a PerlChildExitHandler
1.243 albertel 11685:
11686: =back
11687:
11688: =head2 Other
11689:
11690: =over 4
11691:
11692: =item *
11693:
11694: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11695:
11696: =back
11697:
11698: =cut
1.877 foxr 11699:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>