Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1106
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1106 ! raeburn 4: # $Id: lonnet.pm,v 1.1105 2011/03/06 21:17:18 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.1079 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.1090 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.1106 ! raeburn 199: sub get_server_distarch {
! 200: my ($lonhost,$ignore_cache) = @_;
! 201: if (defined($lonhost)) {
! 202: if (!defined(&hostname($lonhost))) {
! 203: return;
! 204: }
! 205: my $cachetime = 12*3600;
! 206: if (!$ignore_cache) {
! 207: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
! 208: if (defined($cached)) {
! 209: return $distarch;
! 210: }
! 211: }
! 212: my $rep = &reply('serverdistarch',$lonhost);
! 213: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
! 214: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
! 215: $rep eq '') {
! 216: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
! 217: }
! 218: }
! 219: return;
! 220: }
! 221:
1.993 raeburn 222: sub get_server_loncaparev {
1.1073 raeburn 223: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 224: if (defined($lonhost)) {
225: if (!defined(&hostname($lonhost))) {
226: undef($lonhost);
227: }
228: }
229: if (!defined($lonhost)) {
230: if (defined(&domain($dom,'primary'))) {
231: $lonhost=&domain($dom,'primary');
232: if ($lonhost eq 'no_host') {
233: undef($lonhost);
234: }
235: }
236: }
237: if (defined($lonhost)) {
1.1073 raeburn 238: my $cachetime = 12*3600;
239: if (!$ignore_cache) {
240: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
241: if (defined($cached)) {
242: return $loncaparev;
243: }
244: }
245: my ($answer,$loncaparev);
246: my @ids=¤t_machine_ids();
247: if (grep(/^\Q$lonhost\E$/,@ids)) {
248: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 249: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 250: $loncaparev = $1;
251: }
252: } else {
253: $answer = &reply('serverloncaparev',$lonhost);
254: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
255: if ($caller eq 'loncron') {
256: my $ua=new LWP::UserAgent;
1.1082 raeburn 257: $ua->timeout(4);
1.1073 raeburn 258: my $protocol = $protocol{$lonhost};
259: $protocol = 'http' if ($protocol ne 'https');
260: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
261: my $request=new HTTP::Request('GET',$url);
262: my $response=$ua->request($request);
263: unless ($response->is_error()) {
264: my $content = $response->content;
1.1081 raeburn 265: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 266: $loncaparev = $1;
267: }
268: }
269: } else {
270: $loncaparev = $loncaparevs{$lonhost};
271: }
1.1081 raeburn 272: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 273: $loncaparev = $1;
274: }
1.993 raeburn 275: }
1.1073 raeburn 276: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 277: }
278: }
279:
1.1074 raeburn 280: sub get_server_homeID {
281: my ($hostname,$ignore_cache,$caller) = @_;
282: unless ($ignore_cache) {
283: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
284: if (defined($cached)) {
285: return $serverhomeID;
286: }
287: }
288: my $cachetime = 12*3600;
289: my $serverhomeID;
290: if ($caller eq 'loncron') {
291: my @machine_ids = &machine_ids($hostname);
292: foreach my $id (@machine_ids) {
293: my $response = &reply('serverhomeID',$id);
294: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
295: $serverhomeID = $response;
296: last;
297: }
298: }
299: if ($serverhomeID eq '') {
300: $serverhomeID = $machine_ids[-1];
301: }
302: } else {
303: $serverhomeID = $serverhomeIDs{$hostname};
304: }
305: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
306: }
307:
1.1 albertel 308: # -------------------------------------------------- Non-critical communication
309: sub subreply {
310: my ($cmd,$server)=@_;
1.838 albertel 311: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 312: #
313: # With loncnew process trimming, there's a timing hole between lonc server
314: # process exit and the master server picking up the listen on the AF_UNIX
315: # socket. In that time interval, a lock file will exist:
316:
317: my $lockfile=$peerfile.".lock";
318: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
319: sleep(1);
320: }
321: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 322: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 323: #
1.550 foxr 324: # We'll give the connection a few tries before abandoning it. If
325: # connection is not possible, we'll con_lost back to the client.
326: #
327: my $client;
328: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
329: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
330: Type => SOCK_STREAM,
331: Timeout => 10);
1.869 albertel 332: if ($client) {
1.550 foxr 333: last; # Connected!
1.850 albertel 334: } else {
1.853 albertel 335: &create_connection(&hostname($server),$server);
1.550 foxr 336: }
1.850 albertel 337: sleep(1); # Try again later if failed connection.
1.550 foxr 338: }
339: my $answer;
340: if ($client) {
1.704 albertel 341: print $client "sethost:$server:$cmd\n";
1.550 foxr 342: $answer=<$client>;
343: if (!$answer) { $answer="con_lost"; }
344: chomp($answer);
345: } else {
346: $answer = 'con_lost'; # Failed connection.
347: }
1.1 albertel 348: return $answer;
349: }
350:
351: sub reply {
352: my ($cmd,$server)=@_;
1.838 albertel 353: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 354: my $answer=subreply($cmd,$server);
1.65 www 355: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 356: &logthis("<font color=\"blue\">WARNING:".
1.12 www 357: " $cmd to $server returned $answer</font>");
358: }
1.1 albertel 359: return $answer;
360: }
361:
362: # ----------------------------------------------------------- Send USR1 to lonc
363:
364: sub reconlonc {
1.891 albertel 365: my ($lonid) = @_;
366: my $hostname = &hostname($lonid);
367: if ($lonid) {
368: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
369: if ($hostname && -e $peerfile) {
370: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
371: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
372: Type => SOCK_STREAM,
373: Timeout => 10);
374: if ($client) {
375: print $client ("reset_retries\n");
376: my $answer=<$client>;
377: #reset just this one.
378: }
379: }
380: return;
381: }
382:
1.836 www 383: &logthis("Trying to reconnect lonc");
1.1 albertel 384: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 385: if (open(my $fh,"<$loncfile")) {
1.1 albertel 386: my $loncpid=<$fh>;
387: chomp($loncpid);
388: if (kill 0 => $loncpid) {
389: &logthis("lonc at pid $loncpid responding, sending USR1");
390: kill USR1 => $loncpid;
391: sleep 1;
1.836 www 392: } else {
1.12 www 393: &logthis(
1.672 albertel 394: "<font color=\"blue\">WARNING:".
1.12 www 395: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 396: }
397: } else {
1.836 www 398: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 399: }
400: }
401:
402: # ------------------------------------------------------ Critical communication
1.12 www 403:
1.1 albertel 404: sub critical {
405: my ($cmd,$server)=@_;
1.838 albertel 406: unless (&hostname($server)) {
1.672 albertel 407: &logthis("<font color=\"blue\">WARNING:".
1.89 www 408: " Critical message to unknown server ($server)</font>");
409: return 'no_such_host';
410: }
1.1 albertel 411: my $answer=reply($cmd,$server);
412: if ($answer eq 'con_lost') {
413: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 414: my $answer=reply($cmd,$server);
1.1 albertel 415: if ($answer eq 'con_lost') {
416: my $now=time;
417: my $middlename=$cmd;
1.5 www 418: $middlename=substr($middlename,0,16);
1.1 albertel 419: $middlename=~s/\W//g;
420: my $dfilename=
1.305 www 421: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
422: $dumpcount++;
1.1 albertel 423: {
1.448 albertel 424: my $dfh;
425: if (open($dfh,">$dfilename")) {
426: print $dfh "$cmd\n";
427: close($dfh);
428: }
1.1 albertel 429: }
430: sleep 2;
431: my $wcmd='';
432: {
1.448 albertel 433: my $dfh;
434: if (open($dfh,"<$dfilename")) {
435: $wcmd=<$dfh>;
436: close($dfh);
437: }
1.1 albertel 438: }
439: chomp($wcmd);
1.7 www 440: if ($wcmd eq $cmd) {
1.672 albertel 441: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 442: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 443: &logperm("D:$server:$cmd");
444: return 'con_delayed';
445: } else {
1.672 albertel 446: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 447: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 448: &logperm("F:$server:$cmd");
449: return 'con_failed';
450: }
451: }
452: }
453: return $answer;
1.405 albertel 454: }
455:
1.755 albertel 456: # ------------------------------------------- check if return value is an error
457:
458: sub error {
459: my ($result) = @_;
1.756 albertel 460: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 461: if ($2 == 2) { return undef; }
462: return $1;
463: }
464: return undef;
465: }
466:
1.783 albertel 467: sub convert_and_load_session_env {
468: my ($lonidsdir,$handle)=@_;
469: my @profile;
470: {
1.917 albertel 471: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
472: if (!$opened) {
1.915 albertel 473: return 0;
474: }
1.783 albertel 475: flock($idf,LOCK_SH);
476: @profile=<$idf>;
477: close($idf);
478: }
479: my %temp_env;
480: foreach my $line (@profile) {
1.786 albertel 481: if ($line !~ m/=/) {
482: return 0;
483: }
1.783 albertel 484: chomp($line);
485: my ($envname,$envvalue)=split(/=/,$line,2);
486: $temp_env{&unescape($envname)} = &unescape($envvalue);
487: }
488: unlink("$lonidsdir/$handle.id");
489: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
490: 0640)) {
491: %disk_env = %temp_env;
492: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
493: untie(%disk_env);
494: }
1.786 albertel 495: return 1;
1.783 albertel 496: }
497:
1.374 www 498: # ------------------------------------------- Transfer profile into environment
1.780 albertel 499: my $env_loaded;
500: sub transfer_profile_to_env {
1.788 albertel 501: my ($lonidsdir,$handle,$force_transfer) = @_;
502: if (!$force_transfer && $env_loaded) { return; }
1.374 www 503:
1.720 albertel 504: if (!defined($lonidsdir)) {
505: $lonidsdir = $perlvar{'lonIDsDir'};
506: }
507: if (!defined($handle)) {
508: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
509: }
510:
1.786 albertel 511: my $convert;
512: {
1.917 albertel 513: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
514: if (!$opened) {
1.915 albertel 515: return;
516: }
1.786 albertel 517: flock($idf,LOCK_SH);
518: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
519: &GDBM_READER(),0640)) {
520: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
521: untie(%disk_env);
522: } else {
523: $convert = 1;
524: }
525: }
526: if ($convert) {
527: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
528: &logthis("Failed to load session, or convert session.");
529: }
1.374 www 530: }
1.783 albertel 531:
1.786 albertel 532: my %remove;
1.783 albertel 533: while ( my $envname = each(%env) ) {
1.433 matthew 534: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
535: if ($time < time-300) {
1.783 albertel 536: $remove{$key}++;
1.433 matthew 537: }
538: }
539: }
1.783 albertel 540:
1.619 albertel 541: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 542: $env_loaded=1;
1.783 albertel 543: foreach my $expired_key (keys(%remove)) {
1.433 matthew 544: &delenv($expired_key);
1.374 www 545: }
1.1 albertel 546: }
547:
1.916 albertel 548: # ---------------------------------------------------- Check for valid session
549: sub check_for_valid_session {
550: my ($r) = @_;
551: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
552: my $lonid=$cookies{'lonID'};
553: return undef if (!$lonid);
554:
555: my $handle=&LONCAPA::clean_handle($lonid->value);
556: my $lonidsdir=$r->dir_config('lonIDsDir');
557: return undef if (!-e "$lonidsdir/$handle.id");
558:
1.917 albertel 559: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
560: return undef if (!$opened);
1.916 albertel 561:
562: flock($idf,LOCK_SH);
563: my %disk_env;
564: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
565: &GDBM_READER(),0640)) {
566: return undef;
567: }
568:
569: if (!defined($disk_env{'user.name'})
570: || !defined($disk_env{'user.domain'})) {
571: return undef;
572: }
573: return $handle;
574: }
575:
1.830 albertel 576: sub timed_flock {
577: my ($file,$lock_type) = @_;
578: my $failed=0;
579: eval {
580: local $SIG{__DIE__}='DEFAULT';
581: local $SIG{ALRM}=sub {
582: $failed=1;
583: die("failed lock");
584: };
585: alarm(13);
586: flock($file,$lock_type);
587: alarm(0);
588: };
589: if ($failed) {
590: return undef;
591: } else {
592: return 1;
593: }
594: }
595:
1.5 www 596: # ---------------------------------------------------------- Append Environment
597:
598: sub appenv {
1.949 raeburn 599: my ($newenv,$roles) = @_;
600: if (ref($newenv) eq 'HASH') {
601: foreach my $key (keys(%{$newenv})) {
602: my $refused = 0;
603: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
604: $refused = 1;
605: if (ref($roles) eq 'ARRAY') {
606: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
607: if (grep(/^\Q$role\E$/,@{$roles})) {
608: $refused = 0;
609: }
610: }
611: }
612: if ($refused) {
613: &logthis("<font color=\"blue\">WARNING: ".
614: "Attempt to modify environment ".$key." to ".$newenv->{$key}
615: .'</font>');
616: delete($newenv->{$key});
617: } else {
618: $env{$key}=$newenv->{$key};
619: }
620: }
621: my $opened = open(my $env_file,'+<',$env{'user.environment'});
622: if ($opened
623: && &timed_flock($env_file,LOCK_EX)
624: &&
625: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
626: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
627: while (my ($key,$value) = each(%{$newenv})) {
628: $disk_env{$key} = $value;
629: }
630: untie(%disk_env);
1.35 www 631: }
1.191 harris41 632: }
1.56 www 633: return 'ok';
634: }
635: # ----------------------------------------------------- Delete from Environment
636:
637: sub delenv {
1.1104 raeburn 638: my ($delthis,$regexp,$roles) = @_;
639: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
640: my $refused = 1;
641: if (ref($roles) eq 'ARRAY') {
642: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
643: if (grep(/^\Q$role\E$/,@{$roles})) {
644: $refused = 0;
645: }
646: }
647: if ($refused) {
648: &logthis("<font color=\"blue\">WARNING: ".
649: "Attempt to delete from environment ".$delthis);
650: return 'error';
651: }
1.56 www 652: }
1.917 albertel 653: my $opened = open(my $env_file,'+<',$env{'user.environment'});
654: if ($opened
1.915 albertel 655: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 656: &&
657: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
658: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 659: foreach my $key (keys(%disk_env)) {
1.987 raeburn 660: if ($regexp) {
661: if ($key=~/^$delthis/) {
662: delete($env{$key});
663: delete($disk_env{$key});
664: }
665: } else {
666: if ($key=~/^\Q$delthis\E/) {
667: delete($env{$key});
668: delete($disk_env{$key});
669: }
670: }
1.448 albertel 671: }
1.783 albertel 672: untie(%disk_env);
1.5 www 673: }
674: return 'ok';
1.369 albertel 675: }
676:
1.790 albertel 677: sub get_env_multiple {
678: my ($name) = @_;
679: my @values;
680: if (defined($env{$name})) {
681: # exists is it an array
682: if (ref($env{$name})) {
683: @values=@{ $env{$name} };
684: } else {
685: $values[0]=$env{$name};
686: }
687: }
688: return(@values);
689: }
690:
1.958 www 691: # ------------------------------------------------------------------- Locking
692:
693: sub set_lock {
694: my ($text)=@_;
695: $locknum++;
696: my $id=$$.'-'.$locknum;
697: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
698: 'session.lock.'.$id => $text});
699: return $id;
700: }
701:
702: sub get_locks {
703: my $num=0;
704: my %texts=();
705: foreach my $lock (split(/\,/,$env{'session.locks'})) {
706: if ($lock=~/\w/) {
707: $num++;
708: $texts{$lock}=$env{'session.lock.'.$lock};
709: }
710: }
711: return ($num,%texts);
712: }
713:
714: sub remove_lock {
715: my ($id)=@_;
716: my $newlocks='';
717: foreach my $lock (split(/\,/,$env{'session.locks'})) {
718: if (($lock=~/\w/) && ($lock ne $id)) {
719: $newlocks.=','.$lock;
720: }
721: }
722: &appenv({'session.locks' => $newlocks});
723: &delenv('session.lock.'.$id);
724: }
725:
726: sub remove_all_locks {
727: my $activelocks=$env{'session.locks'};
728: foreach my $lock (split(/\,/,$env{'session.locks'})) {
729: if ($lock=~/\w/) {
730: &remove_lock($lock);
731: }
732: }
733: }
734:
735:
1.369 albertel 736: # ------------------------------------------ Find out current server userload
737: sub userload {
738: my $numusers=0;
739: {
740: opendir(LONIDS,$perlvar{'lonIDsDir'});
741: my $filename;
742: my $curtime=time;
743: while ($filename=readdir(LONIDS)) {
1.925 albertel 744: next if ($filename eq '.' || $filename eq '..');
745: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 746: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 747: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 748: }
749: closedir(LONIDS);
750: }
751: my $userloadpercent=0;
752: my $maxuserload=$perlvar{'lonUserLoadLim'};
753: if ($maxuserload) {
1.371 albertel 754: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 755: }
1.372 albertel 756: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 757: return $userloadpercent;
1.283 www 758: }
759:
1.1 albertel 760: # ------------------------------ Find server with least workload from spare.tab
1.11 www 761:
1.1 albertel 762: sub spareserver {
1.1083 raeburn 763: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 764: my $spare_server;
1.370 albertel 765: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 766: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
767: : $userloadpercent;
1.1083 raeburn 768: my ($uint_dom,$remotesessions);
769: if (($udom ne '') && (&domain($udom) ne '')) {
770: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
771: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
772: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
773: $remotesessions = $udomdefaults{'remotesessions'};
774: }
1.784 albertel 775: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083 raeburn 776: if ($uint_dom) {
777: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
778: $try_server));
779: }
1.784 albertel 780: ($spare_server, $lowest_load) =
781: &compare_server_load($try_server, $spare_server, $lowest_load);
782: }
783:
784: my $found_server = ($spare_server ne '' && $lowest_load < 100);
785:
786: if (!$found_server) {
787: foreach my $try_server (@{ $spareid{'default'} }) {
1.1083 raeburn 788: if ($uint_dom) {
789: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
790: $try_server));
791: }
1.784 albertel 792: ($spare_server, $lowest_load) =
793: &compare_server_load($try_server, $spare_server, $lowest_load);
794: }
795: }
796:
797: if (!$want_server_name) {
1.968 raeburn 798: my $protocol = 'http';
799: if ($protocol{$spare_server} eq 'https') {
800: $protocol = $protocol{$spare_server};
801: }
1.1001 raeburn 802: if (defined($spare_server)) {
803: my $hostname = &hostname($spare_server);
1.1083 raeburn 804: if (defined($hostname)) {
1.1001 raeburn 805: $spare_server = $protocol.'://'.$hostname;
806: }
807: }
1.784 albertel 808: }
809: return $spare_server;
810: }
811:
812: sub compare_server_load {
813: my ($try_server, $spare_server, $lowest_load) = @_;
814:
815: my $loadans = &reply('load', $try_server);
816: my $userloadans = &reply('userload',$try_server);
817:
818: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072 www 819: return; #didn't get a number from the server
1.784 albertel 820: }
821:
822: my $load;
823: if ($loadans =~ /\d/) {
824: if ($userloadans =~ /\d/) {
825: #both are numbers, pick the bigger one
826: $load = ($loadans > $userloadans) ? $loadans
827: : $userloadans;
1.411 albertel 828: } else {
1.784 albertel 829: $load = $loadans;
1.411 albertel 830: }
1.784 albertel 831: } else {
832: $load = $userloadans;
833: }
834:
835: if (($load =~ /\d/) && ($load < $lowest_load)) {
836: $spare_server = $try_server;
837: $lowest_load = $load;
1.370 albertel 838: }
1.784 albertel 839: return ($spare_server,$lowest_load);
1.202 matthew 840: }
1.914 albertel 841:
842: # --------------------------- ask offload servers if user already has a session
843: sub find_existing_session {
844: my ($udom,$uname) = @_;
845: foreach my $try_server (@{ $spareid{'primary'} },
846: @{ $spareid{'default'} }) {
847: return $try_server if (&has_user_session($try_server, $udom, $uname));
848: }
849: return;
850: }
851:
852: # -------------------------------- ask if server already has a session for user
853: sub has_user_session {
854: my ($lonid,$udom,$uname) = @_;
855: my $result = &reply(join(':','userhassession',
856: map {&escape($_)} ($udom,$uname)),$lonid);
857: return 1 if ($result eq 'ok');
858:
859: return 0;
860: }
861:
1.1076 raeburn 862: # --------- determine least loaded server in a user's domain which allows login
863:
864: sub choose_server {
865: my ($udom) = @_;
866: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 867: my %servers = &get_servers($udom);
1.1076 raeburn 868: my $lowest_load = 30000;
869: my ($login_host,$hostname);
870: foreach my $lonhost (keys(%servers)) {
871: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
872: if ($loginvia eq '') {
873: ($login_host, $lowest_load) =
874: &compare_server_load($lonhost, $login_host, $lowest_load);
875: }
876: }
877: if ($login_host ne '') {
878: $hostname = $servers{$login_host};
879: }
880: return ($login_host,$hostname);
881: }
882:
1.202 matthew 883: # --------------------------------------------- Try to change a user's password
884:
885: sub changepass {
1.799 raeburn 886: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 887: $currentpass = &escape($currentpass);
888: $newpass = &escape($newpass);
1.1030 raeburn 889: my $lonhost = $perlvar{'lonHostID'};
890: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 891: $server);
892: if (! $answer) {
893: &logthis("No reply on password change request to $server ".
894: "by $uname in domain $udom.");
895: } elsif ($answer =~ "^ok") {
896: &logthis("$uname in $udom successfully changed their password ".
897: "on $server.");
898: } elsif ($answer =~ "^pwchange_failure") {
899: &logthis("$uname in $udom was unable to change their password ".
900: "on $server. The action was blocked by either lcpasswd ".
901: "or pwchange");
902: } elsif ($answer =~ "^non_authorized") {
903: &logthis("$uname in $udom did not get their password correct when ".
904: "attempting to change it on $server.");
905: } elsif ($answer =~ "^auth_mode_error") {
906: &logthis("$uname in $udom attempted to change their password despite ".
907: "not being locally or internally authenticated on $server.");
908: } elsif ($answer =~ "^unknown_user") {
909: &logthis("$uname in $udom attempted to change their password ".
910: "on $server but were unable to because $server is not ".
911: "their home server.");
912: } elsif ($answer =~ "^refused") {
913: &logthis("$server refused to change $uname in $udom password because ".
914: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 915: } elsif ($answer =~ "invalid_client") {
916: &logthis("$server refused to change $uname in $udom password because ".
917: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 918: }
919: return $answer;
1.1 albertel 920: }
921:
1.169 harris41 922: # ----------------------- Try to determine user's current authentication scheme
923:
924: sub queryauthenticate {
925: my ($uname,$udom)=@_;
1.456 albertel 926: my $uhome=&homeserver($uname,$udom);
927: if (!$uhome) {
928: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
929: return 'no_host';
930: }
931: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
932: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
933: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 934: }
1.456 albertel 935: return $answer;
1.169 harris41 936: }
937:
1.1 albertel 938: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 939:
1.1 albertel 940: sub authenticate {
1.1073 raeburn 941: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 942: $upass=&escape($upass);
943: $uname= &LONCAPA::clean_username($uname);
1.836 www 944: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 945: my $newhome;
1.836 www 946: if ((!$uhome) || ($uhome eq 'no_host')) {
947: # Maybe the machine was offline and only re-appeared again recently?
948: &reconlonc();
949: # One more
1.952 raeburn 950: $uhome=&homeserver($uname,$udom,1);
951: if (($uhome eq 'no_host') && $checkdefauth) {
952: if (defined(&domain($udom,'primary'))) {
953: $newhome=&domain($udom,'primary');
954: }
955: if ($newhome ne '') {
956: $uhome = $newhome;
957: }
958: }
1.836 www 959: if ((!$uhome) || ($uhome eq 'no_host')) {
960: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 961: return 'no_host';
962: }
1.1 albertel 963: }
1.1073 raeburn 964: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 965: if ($answer eq 'authorized') {
1.952 raeburn 966: if ($newhome) {
967: &logthis("User $uname at $udom authorized by $uhome, but needs account");
968: return 'no_account_on_host';
969: } else {
970: &logthis("User $uname at $udom authorized by $uhome");
971: return $uhome;
972: }
1.471 albertel 973: }
974: if ($answer eq 'non_authorized') {
975: &logthis("User $uname at $udom rejected by $uhome");
976: return 'no_host';
1.9 www 977: }
1.471 albertel 978: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 979: return 'no_host';
980: }
981:
1.1073 raeburn 982: sub can_host_session {
1.1074 raeburn 983: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 984: my $canhost = 1;
1.1074 raeburn 985: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 986: if (ref($remotesessions) eq 'HASH') {
987: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 988: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 989: $canhost = 0;
990: } else {
991: $canhost = 1;
992: }
993: }
994: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 995: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 996: $canhost = 1;
997: } else {
998: $canhost = 0;
999: }
1000: }
1001: if ($canhost) {
1002: if ($remotesessions->{'version'} ne '') {
1003: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1004: if ($reqmajor ne '' && $reqminor ne '') {
1005: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1006: my $major = $1;
1007: my $minor = $2;
1008: if (($major < $reqmajor ) ||
1009: (($major == $reqmajor) && ($minor < $reqminor))) {
1010: $canhost = 0;
1011: }
1012: } else {
1013: $canhost = 0;
1014: }
1015: }
1016: }
1017: }
1018: }
1019: if ($canhost) {
1020: if (ref($hostedsessions) eq 'HASH') {
1021: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1022: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
1023: $canhost = 0;
1024: } else {
1025: $canhost = 1;
1026: }
1027: }
1028: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1029: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
1030: $canhost = 1;
1031: } else {
1032: $canhost = 0;
1033: }
1034: }
1035: }
1036: }
1037: return $canhost;
1038: }
1039:
1.1083 raeburn 1040: sub spare_can_host {
1041: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1042: my $canhost=1;
1043: my @intdoms;
1044: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1045: if (ref($internet_names) eq 'ARRAY') {
1046: @intdoms = @{$internet_names};
1047: }
1048: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1049: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1050: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1051: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1052: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1053: $canhost = &can_host_session($udom,$try_server,$remoterev,
1054: $remotesessions,
1055: $defdomdefaults{'hostedsessions'});
1056: }
1057: return $canhost;
1058: }
1059:
1.1 albertel 1060: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1061:
1.599 albertel 1062: my %homecache;
1.1 albertel 1063: sub homeserver {
1.230 stredwic 1064: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1065: my $index="$uname:$udom";
1.426 albertel 1066:
1.599 albertel 1067: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1068:
1069: my %servers = &get_servers($udom,'library');
1070: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1071: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1072: exists($badServerCache{$tryserver}));
1.841 albertel 1073:
1074: my $answer=reply("home:$udom:$uname",$tryserver);
1075: if ($answer eq 'found') {
1076: delete($badServerCache{$tryserver});
1077: return $homecache{$index}=$tryserver;
1078: } elsif ($answer eq 'no_host') {
1079: $badServerCache{$tryserver}=1;
1080: }
1.1 albertel 1081: }
1082: return 'no_host';
1.70 www 1083: }
1084:
1085: # ------------------------------------- Find the usernames behind a list of IDs
1086:
1087: sub idget {
1088: my ($udom,@ids)=@_;
1089: my %returnhash=();
1090:
1.841 albertel 1091: my %servers = &get_servers($udom,'library');
1092: foreach my $tryserver (keys(%servers)) {
1093: my $idlist=join('&',@ids);
1094: $idlist=~tr/A-Z/a-z/;
1095: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1096: my @answer=();
1097: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1098: @answer=split(/\&/,$reply);
1099: } ;
1100: my $i;
1101: for ($i=0;$i<=$#ids;$i++) {
1102: if ($answer[$i]) {
1103: $returnhash{$ids[$i]}=$answer[$i];
1104: }
1105: }
1106: }
1.70 www 1107: return %returnhash;
1108: }
1109:
1110: # ------------------------------------- Find the IDs behind a list of usernames
1111:
1112: sub idrget {
1113: my ($udom,@unames)=@_;
1114: my %returnhash=();
1.800 albertel 1115: foreach my $uname (@unames) {
1116: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1117: }
1.70 www 1118: return %returnhash;
1119: }
1120:
1121: # ------------------------------- Store away a list of names and associated IDs
1122:
1123: sub idput {
1124: my ($udom,%ids)=@_;
1125: my %servers=();
1.800 albertel 1126: foreach my $uname (keys(%ids)) {
1127: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1128: my $uhom=&homeserver($uname,$udom);
1.70 www 1129: if ($uhom ne 'no_host') {
1.800 albertel 1130: my $id=&escape($ids{$uname});
1.70 www 1131: $id=~tr/A-Z/a-z/;
1.800 albertel 1132: my $esc_unam=&escape($uname);
1.70 www 1133: if ($servers{$uhom}) {
1.800 albertel 1134: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1135: } else {
1.800 albertel 1136: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1137: }
1138: }
1.191 harris41 1139: }
1.800 albertel 1140: foreach my $server (keys(%servers)) {
1141: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1142: }
1.344 www 1143: }
1144:
1.1023 raeburn 1145: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1146: sub dump_dom {
1.1023 raeburn 1147: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1148: if (!$udom) {
1149: $udom=$env{'user.domain'};
1150: }
1151: my %returnhash;
1.1023 raeburn 1152: if ($udom) {
1153: my $uname = &get_domainconfiguser($udom);
1154: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1155: }
1156: return %returnhash;
1157: }
1158:
1.1023 raeburn 1159: # ------------------------------------------ get items from domain db files
1.806 raeburn 1160:
1161: sub get_dom {
1.860 raeburn 1162: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1163: my $items='';
1164: foreach my $item (@$storearr) {
1165: $items.=&escape($item).'&';
1166: }
1167: $items=~s/\&$//;
1.860 raeburn 1168: if (!$udom) {
1169: $udom=$env{'user.domain'};
1170: if (defined(&domain($udom,'primary'))) {
1171: $uhome=&domain($udom,'primary');
1172: } else {
1.874 albertel 1173: undef($uhome);
1.860 raeburn 1174: }
1175: } else {
1176: if (!$uhome) {
1177: if (defined(&domain($udom,'primary'))) {
1178: $uhome=&domain($udom,'primary');
1179: }
1180: }
1181: }
1182: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1183: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1184: my %returnhash;
1.875 albertel 1185: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1186: return %returnhash;
1187: }
1.806 raeburn 1188: my @pairs=split(/\&/,$rep);
1189: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1190: return @pairs;
1191: }
1192: my $i=0;
1193: foreach my $item (@$storearr) {
1194: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1195: $i++;
1196: }
1197: return %returnhash;
1198: } else {
1.880 banghart 1199: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1200: }
1201: }
1202:
1203: # -------------------------------------------- put items in domain db files
1204:
1205: sub put_dom {
1.860 raeburn 1206: my ($namespace,$storehash,$udom,$uhome)=@_;
1207: if (!$udom) {
1208: $udom=$env{'user.domain'};
1209: if (defined(&domain($udom,'primary'))) {
1210: $uhome=&domain($udom,'primary');
1211: } else {
1.874 albertel 1212: undef($uhome);
1.860 raeburn 1213: }
1214: } else {
1215: if (!$uhome) {
1216: if (defined(&domain($udom,'primary'))) {
1217: $uhome=&domain($udom,'primary');
1218: }
1219: }
1220: }
1221: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1222: my $items='';
1223: foreach my $item (keys(%$storehash)) {
1224: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1225: }
1226: $items=~s/\&$//;
1227: return &reply("putdom:$udom:$namespace:$items",$uhome);
1228: } else {
1.860 raeburn 1229: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1230: }
1231: }
1232:
1.1023 raeburn 1233: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1234: sub newput_dom {
1.1023 raeburn 1235: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1236: my $result;
1237: if (!$udom) {
1238: $udom=$env{'user.domain'};
1239: }
1.1023 raeburn 1240: if ($udom) {
1241: my $uname = &get_domainconfiguser($udom);
1242: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1243: }
1244: return $result;
1245: }
1246:
1.1023 raeburn 1247: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1248: sub del_dom {
1.1023 raeburn 1249: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1250: if (ref($storearr) eq 'ARRAY') {
1251: if (!$udom) {
1252: $udom=$env{'user.domain'};
1253: }
1.1023 raeburn 1254: if ($udom) {
1255: my $uname = &get_domainconfiguser($udom);
1256: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1257: }
1258: }
1259: }
1260:
1.1023 raeburn 1261: # ----------------------------------construct domainconfig user for a domain
1262: sub get_domainconfiguser {
1263: my ($udom) = @_;
1264: return $udom.'-domainconfig';
1265: }
1266:
1.837 raeburn 1267: sub retrieve_inst_usertypes {
1268: my ($udom) = @_;
1269: my (%returnhash,@order);
1.989 raeburn 1270: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1271: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1272: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1273: %returnhash = %{$domdefs{'inststatustypes'}};
1274: @order = @{$domdefs{'inststatusorder'}};
1275: } else {
1276: if (defined(&domain($udom,'primary'))) {
1277: my $uhome=&domain($udom,'primary');
1278: my $rep=&reply("inst_usertypes:$udom",$uhome);
1279: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1280: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1281: return (\%returnhash,\@order);
1282: }
1283: my ($hashitems,$orderitems) = split(/:/,$rep);
1284: my @pairs=split(/\&/,$hashitems);
1285: foreach my $item (@pairs) {
1286: my ($key,$value)=split(/=/,$item,2);
1287: $key = &unescape($key);
1288: next if ($key =~ /^error: 2 /);
1289: $returnhash{$key}=&thaw_unescape($value);
1290: }
1291: my @esc_order = split(/\&/,$orderitems);
1292: foreach my $item (@esc_order) {
1293: push(@order,&unescape($item));
1294: }
1295: } else {
1296: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1297: }
1298: }
1299: return (\%returnhash,\@order);
1300: }
1301:
1.868 raeburn 1302: sub is_domainimage {
1303: my ($url) = @_;
1304: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1305: if (&domain($1) ne '') {
1306: return '1';
1307: }
1308: }
1309: return;
1310: }
1311:
1.899 raeburn 1312: sub inst_directory_query {
1313: my ($srch) = @_;
1314: my $udom = $srch->{'srchdomain'};
1315: my %results;
1316: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1317: my $outcome;
1.899 raeburn 1318: if ($homeserver ne '') {
1.904 albertel 1319: my $queryid=&reply("querysend:instdirsearch:".
1320: &escape($srch->{'srchby'}).':'.
1321: &escape($srch->{'srchterm'}).':'.
1322: &escape($srch->{'srchtype'}),$homeserver);
1323: my $host=&hostname($homeserver);
1324: if ($queryid !~/^\Q$host\E\_/) {
1325: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1326: return;
1327: }
1328: my $response = &get_query_reply($queryid);
1329: my $maxtries = 5;
1330: my $tries = 1;
1331: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1332: $response = &get_query_reply($queryid);
1333: $tries ++;
1334: }
1335:
1336: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1337: if ($response eq 'unavailable') {
1338: $outcome = $response;
1339: } else {
1340: $outcome = 'ok';
1341: my @matches = split(/\n/,$response);
1342: foreach my $match (@matches) {
1343: my ($key,$value) = split(/=/,$match);
1344: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1345: }
1.899 raeburn 1346: }
1347: }
1348: }
1.909 raeburn 1349: return ($outcome,%results);
1.899 raeburn 1350: }
1351:
1352: sub usersearch {
1353: my ($srch) = @_;
1354: my $dom = $srch->{'srchdomain'};
1355: my %results;
1356: my %libserv = &all_library();
1357: my $query = 'usersearch';
1358: foreach my $tryserver (keys(%libserv)) {
1359: if (&host_domain($tryserver) eq $dom) {
1360: my $host=&hostname($tryserver);
1361: my $queryid=
1.911 raeburn 1362: &reply("querysend:".&escape($query).':'.
1363: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1364: &escape($srch->{'srchtype'}).':'.
1365: &escape($srch->{'srchterm'}),$tryserver);
1366: if ($queryid !~/^\Q$host\E\_/) {
1367: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1368: next;
1.899 raeburn 1369: }
1370: my $reply = &get_query_reply($queryid);
1371: my $maxtries = 1;
1372: my $tries = 1;
1373: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1374: $reply = &get_query_reply($queryid);
1375: $tries ++;
1376: }
1377: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1378: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1379: } else {
1.911 raeburn 1380: my @matches;
1381: if ($reply =~ /\n/) {
1382: @matches = split(/\n/,$reply);
1383: } else {
1384: @matches = split(/\&/,$reply);
1385: }
1.899 raeburn 1386: foreach my $match (@matches) {
1387: my ($uname,$udom,%userhash);
1.911 raeburn 1388: foreach my $entry (split(/:/,$match)) {
1389: my ($key,$value) =
1390: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1391: $userhash{$key} = $value;
1392: if ($key eq 'username') {
1393: $uname = $value;
1394: } elsif ($key eq 'domain') {
1395: $udom = $value;
1.911 raeburn 1396: }
1.899 raeburn 1397: }
1398: $results{$uname.':'.$udom} = \%userhash;
1399: }
1400: }
1401: }
1402: }
1403: return %results;
1404: }
1405:
1.912 raeburn 1406: sub get_instuser {
1407: my ($udom,$uname,$id) = @_;
1408: my $homeserver = &domain($udom,'primary');
1409: my ($outcome,%results);
1410: if ($homeserver ne '') {
1411: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1412: &escape($id).':'.&escape($udom),$homeserver);
1413: my $host=&hostname($homeserver);
1414: if ($queryid !~/^\Q$host\E\_/) {
1415: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1416: return;
1417: }
1418: my $response = &get_query_reply($queryid);
1419: my $maxtries = 5;
1420: my $tries = 1;
1421: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1422: $response = &get_query_reply($queryid);
1423: $tries ++;
1424: }
1425: if (!&error($response) && $response ne 'refused') {
1426: if ($response eq 'unavailable') {
1427: $outcome = $response;
1428: } else {
1429: $outcome = 'ok';
1430: my @matches = split(/\n/,$response);
1431: foreach my $match (@matches) {
1432: my ($key,$value) = split(/=/,$match);
1433: $results{&unescape($key)} = &thaw_unescape($value);
1434: }
1435: }
1436: }
1437: }
1438: my %userinfo;
1439: if (ref($results{$uname}) eq 'HASH') {
1440: %userinfo = %{$results{$uname}};
1441: }
1442: return ($outcome,%userinfo);
1443: }
1444:
1445: sub inst_rulecheck {
1.923 raeburn 1446: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1447: my %returnhash;
1448: if ($udom ne '') {
1449: if (ref($rules) eq 'ARRAY') {
1450: @{$rules} = map {&escape($_);} (@{$rules});
1451: my $rulestr = join(':',@{$rules});
1452: my $homeserver=&domain($udom,'primary');
1453: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1454: my $response;
1455: if ($item eq 'username') {
1456: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1457: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1458: $homeserver));
1.923 raeburn 1459: } elsif ($item eq 'id') {
1460: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1461: ':'.&escape($id).':'.$rulestr,
1462: $homeserver));
1.945 raeburn 1463: } elsif ($item eq 'selfcreate') {
1464: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1465: &escape($udom).':'.&escape($uname).
1466: ':'.$rulestr,$homeserver));
1.923 raeburn 1467: }
1.912 raeburn 1468: if ($response ne 'refused') {
1469: my @pairs=split(/\&/,$response);
1470: foreach my $item (@pairs) {
1471: my ($key,$value)=split(/=/,$item,2);
1472: $key = &unescape($key);
1473: next if ($key =~ /^error: 2 /);
1474: $returnhash{$key}=&thaw_unescape($value);
1475: }
1476: }
1477: }
1478: }
1479: }
1480: return %returnhash;
1481: }
1482:
1483: sub inst_userrules {
1.923 raeburn 1484: my ($udom,$check) = @_;
1.912 raeburn 1485: my (%ruleshash,@ruleorder);
1486: if ($udom ne '') {
1487: my $homeserver=&domain($udom,'primary');
1488: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1489: my $response;
1490: if ($check eq 'id') {
1491: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1492: $homeserver);
1.943 raeburn 1493: } elsif ($check eq 'email') {
1494: $response=&reply('instemailrules:'.&escape($udom),
1495: $homeserver);
1.923 raeburn 1496: } else {
1497: $response=&reply('instuserrules:'.&escape($udom),
1498: $homeserver);
1499: }
1.912 raeburn 1500: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1501: ($response ne 'unknown_cmd') &&
1.912 raeburn 1502: ($response ne 'no_such_host')) {
1503: my ($hashitems,$orderitems) = split(/:/,$response);
1504: my @pairs=split(/\&/,$hashitems);
1505: foreach my $item (@pairs) {
1506: my ($key,$value)=split(/=/,$item,2);
1507: $key = &unescape($key);
1508: next if ($key =~ /^error: 2 /);
1509: $ruleshash{$key}=&thaw_unescape($value);
1510: }
1511: my @esc_order = split(/\&/,$orderitems);
1512: foreach my $item (@esc_order) {
1513: push(@ruleorder,&unescape($item));
1514: }
1515: }
1516: }
1517: }
1518: return (\%ruleshash,\@ruleorder);
1519: }
1520:
1.976 raeburn 1521: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1522:
1523: sub get_domain_defaults {
1524: my ($domain) = @_;
1525: my $cachetime = 60*60*24;
1526: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1527: if (defined($cached)) {
1528: if (ref($result) eq 'HASH') {
1529: return %{$result};
1530: }
1531: }
1532: my %domdefaults;
1533: my %domconfig =
1.989 raeburn 1534: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1535: 'requestcourses','inststatus',
1.1073 raeburn 1536: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1537: if (ref($domconfig{'defaults'}) eq 'HASH') {
1538: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1539: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1540: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1541: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1542: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1543: } else {
1544: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1545: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1546: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1547: }
1.976 raeburn 1548: if (ref($domconfig{'quotas'}) eq 'HASH') {
1549: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1550: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1551: } else {
1552: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1553: }
1554: my @usertools = ('aboutme','blog','portfolio');
1555: foreach my $item (@usertools) {
1556: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1557: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1558: }
1559: }
1560: }
1.985 raeburn 1561: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1562: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1563: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1564: }
1565: }
1.989 raeburn 1566: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1567: foreach my $item ('inststatustypes','inststatusorder') {
1568: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1569: }
1570: }
1.1047 raeburn 1571: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1572: foreach my $item ('canuse_pdfforms') {
1573: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1574: }
1575: }
1.1073 raeburn 1576: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1577: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1578: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1579: }
1580: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1581: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1582: }
1583: }
1.943 raeburn 1584: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1585: $cachetime);
1586: return %domdefaults;
1587: }
1588:
1.344 www 1589: # --------------------------------------------------- Assign a key to a student
1590:
1591: sub assign_access_key {
1.364 www 1592: #
1593: # a valid key looks like uname:udom#comments
1594: # comments are being appended
1595: #
1.498 www 1596: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1597: $kdom=
1.620 albertel 1598: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1599: $knum=
1.620 albertel 1600: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1601: $cdom=
1.620 albertel 1602: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1603: $cnum=
1.620 albertel 1604: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1605: $udom=$env{'user.name'} unless (defined($udom));
1606: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1607: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1608: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1609: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1610: # assigned to this person
1611: # - this should not happen,
1.345 www 1612: # unless something went wrong
1613: # the first time around
1614: # ready to assign
1.364 www 1615: $logentry=$1.'; '.$logentry;
1.496 www 1616: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1617: $kdom,$knum) eq 'ok') {
1.345 www 1618: # key now belongs to user
1.346 www 1619: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1620: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1621: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1622: return 'ok';
1623: } else {
1624: return
1625: 'error: Count not permanently assign key, will need to be re-entered later.';
1626: }
1627: } else {
1628: return 'error: Could not assign key, try again later.';
1629: }
1.364 www 1630: } elsif (!$existing{$ckey}) {
1.345 www 1631: # the key does not exist
1632: return 'error: The key does not exist';
1633: } else {
1634: # the key is somebody else's
1635: return 'error: The key is already in use';
1636: }
1.344 www 1637: }
1638:
1.364 www 1639: # ------------------------------------------ put an additional comment on a key
1640:
1641: sub comment_access_key {
1642: #
1643: # a valid key looks like uname:udom#comments
1644: # comments are being appended
1645: #
1646: my ($ckey,$cdom,$cnum,$logentry)=@_;
1647: $cdom=
1.620 albertel 1648: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1649: $cnum=
1.620 albertel 1650: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1651: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1652: if ($existing{$ckey}) {
1653: $existing{$ckey}.='; '.$logentry;
1654: # ready to assign
1.367 www 1655: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1656: $cdom,$cnum) eq 'ok') {
1657: return 'ok';
1658: } else {
1659: return 'error: Count not store comment.';
1660: }
1661: } else {
1662: # the key does not exist
1663: return 'error: The key does not exist';
1664: }
1665: }
1666:
1.344 www 1667: # ------------------------------------------------------ Generate a set of keys
1668:
1669: sub generate_access_keys {
1.364 www 1670: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1671: $cdom=
1.620 albertel 1672: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1673: $cnum=
1.620 albertel 1674: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1675: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1676: unless (($cdom) && ($cnum)) { return 0; }
1677: if ($number>10000) { return 0; }
1678: sleep(2); # make sure don't get same seed twice
1679: srand(time()^($$+($$<<15))); # from "Programming Perl"
1680: my $total=0;
1681: for (my $i=1;$i<=$number;$i++) {
1682: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1683: sprintf("%lx",int(100000*rand)).'-'.
1684: sprintf("%lx",int(100000*rand));
1685: $newkey=~s/1/g/g; # folks mix up 1 and l
1686: $newkey=~s/0/h/g; # and also 0 and O
1687: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1688: if ($existing{$newkey}) {
1689: $i--;
1690: } else {
1.364 www 1691: if (&put('accesskeys',
1692: { $newkey => '# generated '.localtime().
1.620 albertel 1693: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1694: '; '.$logentry },
1695: $cdom,$cnum) eq 'ok') {
1.344 www 1696: $total++;
1697: }
1698: }
1699: }
1.620 albertel 1700: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1701: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1702: return $total;
1703: }
1704:
1705: # ------------------------------------------------------- Validate an accesskey
1706:
1707: sub validate_access_key {
1708: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1709: $cdom=
1.620 albertel 1710: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1711: $cnum=
1.620 albertel 1712: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1713: $udom=$env{'user.domain'} unless (defined($udom));
1714: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1715: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1716: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1717: }
1718:
1719: # ------------------------------------- Find the section of student in a course
1.652 albertel 1720: sub devalidate_getsection_cache {
1721: my ($udom,$unam,$courseid)=@_;
1722: my $hashid="$udom:$unam:$courseid";
1723: &devalidate_cache_new('getsection',$hashid);
1724: }
1.298 matthew 1725:
1.815 albertel 1726: sub courseid_to_courseurl {
1727: my ($courseid) = @_;
1728: #already url style courseid
1729: return $courseid if ($courseid =~ m{^/});
1730:
1731: if (exists($env{'course.'.$courseid.'.num'})) {
1732: my $cnum = $env{'course.'.$courseid.'.num'};
1733: my $cdom = $env{'course.'.$courseid.'.domain'};
1734: return "/$cdom/$cnum";
1735: }
1736:
1737: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1738: if (exists($courseinfo{'num'})) {
1739: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1740: }
1741:
1742: return undef;
1743: }
1744:
1.298 matthew 1745: sub getsection {
1746: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1747: my $cachetime=1800;
1.551 albertel 1748:
1749: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1750: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1751: if (defined($cached)) { return $result; }
1752:
1.298 matthew 1753: my %Pending;
1754: my %Expired;
1755: #
1756: # Each role can either have not started yet (pending), be active,
1757: # or have expired.
1758: #
1759: # If there is an active role, we are done.
1760: #
1761: # If there is more than one role which has not started yet,
1762: # choose the one which will start sooner
1763: # If there is one role which has not started yet, return it.
1764: #
1765: # If there is more than one expired role, choose the one which ended last.
1766: # If there is a role which has expired, return it.
1767: #
1.815 albertel 1768: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 1769: my $extra = &freeze_escape({'skipcheck' => 1});
1770: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1771: foreach my $key (keys(%roleshash)) {
1.479 albertel 1772: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1773: my $section=$1;
1774: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1775: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1776: my $now=time;
1.548 albertel 1777: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1778: $Expired{$end}=$section;
1779: next;
1780: }
1.548 albertel 1781: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1782: $Pending{$start}=$section;
1783: next;
1784: }
1.599 albertel 1785: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1786: }
1787: #
1788: # Presumedly there will be few matching roles from the above
1789: # loop and the sorting time will be negligible.
1790: if (scalar(keys(%Pending))) {
1791: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1792: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1793: }
1794: if (scalar(keys(%Expired))) {
1795: my @sorted = sort {$a <=> $b} keys(%Expired);
1796: my $time = pop(@sorted);
1.599 albertel 1797: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1798: }
1.599 albertel 1799: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1800: }
1.70 www 1801:
1.599 albertel 1802: sub save_cache {
1803: &purge_remembered();
1.722 albertel 1804: #&Apache::loncommon::validate_page();
1.620 albertel 1805: undef(%env);
1.780 albertel 1806: undef($env_loaded);
1.599 albertel 1807: }
1.452 albertel 1808:
1.599 albertel 1809: my $to_remember=-1;
1810: my %remembered;
1811: my %accessed;
1812: my $kicks=0;
1813: my $hits=0;
1.849 albertel 1814: sub make_key {
1815: my ($name,$id) = @_;
1.872 albertel 1816: if (length($id) > 65
1817: && length(&escape($id)) > 200) {
1818: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1819: }
1.849 albertel 1820: return &escape($name.':'.$id);
1821: }
1822:
1.599 albertel 1823: sub devalidate_cache_new {
1824: my ($name,$id,$debug) = @_;
1825: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1826: $id=&make_key($name,$id);
1.599 albertel 1827: $memcache->delete($id);
1828: delete($remembered{$id});
1829: delete($accessed{$id});
1830: }
1831:
1832: sub is_cached_new {
1833: my ($name,$id,$debug) = @_;
1.849 albertel 1834: $id=&make_key($name,$id);
1.599 albertel 1835: if (exists($remembered{$id})) {
1836: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1837: $accessed{$id}=[&gettimeofday()];
1838: $hits++;
1839: return ($remembered{$id},1);
1840: }
1841: my $value = $memcache->get($id);
1842: if (!(defined($value))) {
1843: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1844: return (undef,undef);
1.416 albertel 1845: }
1.599 albertel 1846: if ($value eq '__undef__') {
1847: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1848: $value=undef;
1849: }
1850: &make_room($id,$value,$debug);
1851: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1852: return ($value,1);
1853: }
1854:
1855: sub do_cache_new {
1856: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1857: $id=&make_key($name,$id);
1.599 albertel 1858: my $setvalue=$value;
1859: if (!defined($setvalue)) {
1860: $setvalue='__undef__';
1861: }
1.623 albertel 1862: if (!defined($time) ) {
1863: $time=600;
1864: }
1.599 albertel 1865: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1866: my $result = $memcache->set($id,$setvalue,$time);
1867: if (! $result) {
1.872 albertel 1868: &logthis("caching of id -> $id failed");
1.910 albertel 1869: $memcache->disconnect_all();
1.872 albertel 1870: }
1.600 albertel 1871: # need to make a copy of $value
1.919 albertel 1872: &make_room($id,$value,$debug);
1.599 albertel 1873: return $value;
1874: }
1875:
1876: sub make_room {
1877: my ($id,$value,$debug)=@_;
1.919 albertel 1878:
1879: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1880: : $value;
1.599 albertel 1881: if ($to_remember<0) { return; }
1882: $accessed{$id}=[&gettimeofday()];
1883: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1884: my $to_kick;
1885: my $max_time=0;
1886: foreach my $other (keys(%accessed)) {
1887: if (&tv_interval($accessed{$other}) > $max_time) {
1888: $to_kick=$other;
1889: $max_time=&tv_interval($accessed{$other});
1890: }
1891: }
1892: delete($remembered{$to_kick});
1893: delete($accessed{$to_kick});
1894: $kicks++;
1895: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1896: return;
1897: }
1898:
1.599 albertel 1899: sub purge_remembered {
1.604 albertel 1900: #&logthis("Tossing ".scalar(keys(%remembered)));
1901: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1902: undef(%remembered);
1903: undef(%accessed);
1.428 albertel 1904: }
1.70 www 1905: # ------------------------------------- Read an entry from a user's environment
1906:
1907: sub userenvironment {
1908: my ($udom,$unam,@what)=@_;
1.976 raeburn 1909: my $items;
1910: foreach my $item (@what) {
1911: $items.=&escape($item).'&';
1912: }
1913: $items=~s/\&$//;
1.70 www 1914: my %returnhash=();
1.1009 raeburn 1915: my $uhome = &homeserver($unam,$udom);
1916: unless ($uhome eq 'no_host') {
1917: my @answer=split(/\&/,
1918: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1919: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1920: return %returnhash;
1921: }
1.1009 raeburn 1922: my $i;
1923: for ($i=0;$i<=$#what;$i++) {
1924: $returnhash{$what[$i]}=&unescape($answer[$i]);
1925: }
1.70 www 1926: }
1927: return %returnhash;
1.1 albertel 1928: }
1929:
1.617 albertel 1930: # ---------------------------------------------------------- Get a studentphoto
1931: sub studentphoto {
1932: my ($udom,$unam,$ext) = @_;
1933: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1934: if (defined($env{'request.course.id'})) {
1.708 raeburn 1935: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1936: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1937: return(&retrievestudentphoto($udom,$unam,$ext));
1938: } else {
1939: my ($result,$perm_reqd)=
1.707 albertel 1940: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1941: if ($result eq 'ok') {
1942: if (!($perm_reqd eq 'yes')) {
1943: return(&retrievestudentphoto($udom,$unam,$ext));
1944: }
1945: }
1946: }
1947: }
1948: } else {
1949: my ($result,$perm_reqd) =
1.707 albertel 1950: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1951: if ($result eq 'ok') {
1952: if (!($perm_reqd eq 'yes')) {
1953: return(&retrievestudentphoto($udom,$unam,$ext));
1954: }
1955: }
1956: }
1957: return '/adm/lonKaputt/lonlogo_broken.gif';
1958: }
1959:
1960: sub retrievestudentphoto {
1961: my ($udom,$unam,$ext,$type) = @_;
1962: my $home=&Apache::lonnet::homeserver($unam,$udom);
1963: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1964: if ($ret eq 'ok') {
1965: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1966: if ($type eq 'thumbnail') {
1967: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1968: }
1969: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1970: return $tokenurl;
1971: } else {
1972: if ($type eq 'thumbnail') {
1973: return '/adm/lonKaputt/genericstudent_tn.gif';
1974: } else {
1975: return '/adm/lonKaputt/lonlogo_broken.gif';
1976: }
1.617 albertel 1977: }
1978: }
1979:
1.263 www 1980: # -------------------------------------------------------------------- New chat
1981:
1982: sub chatsend {
1.724 raeburn 1983: my ($newentry,$anon,$group)=@_;
1.620 albertel 1984: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1985: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1986: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1987: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1988: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1989: &escape($newentry)).':'.$group,$chome);
1.292 www 1990: }
1991:
1992: # ------------------------------------------ Find current version of a resource
1993:
1994: sub getversion {
1995: my $fname=&clutter(shift);
1996: unless ($fname=~/^\/res\//) { return -1; }
1997: return ¤tversion(&filelocation('',$fname));
1998: }
1999:
2000: sub currentversion {
2001: my $fname=shift;
1.599 albertel 2002: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 2003: if (defined($cached)) { return $result; }
1.292 www 2004: my $author=$fname;
2005: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2006: my ($udom,$uname)=split(/\//,$author);
2007: my $home=homeserver($uname,$udom);
2008: if ($home eq 'no_host') {
2009: return -1;
2010: }
2011: my $answer=reply("currentversion:$fname",$home);
2012: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2013: return -1;
2014: }
1.599 albertel 2015: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 2016: }
2017:
1.1 albertel 2018: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2019:
1.1 albertel 2020: sub subscribe {
2021: my $fname=shift;
1.761 raeburn 2022: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2023: $fname=~s/[\n\r]//g;
1.1 albertel 2024: my $author=$fname;
2025: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2026: my ($udom,$uname)=split(/\//,$author);
2027: my $home=homeserver($uname,$udom);
1.335 albertel 2028: if ($home eq 'no_host') {
2029: return 'not_found';
1.1 albertel 2030: }
2031: my $answer=reply("sub:$fname",$home);
1.64 www 2032: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2033: $answer.=' by '.$home;
2034: }
1.1 albertel 2035: return $answer;
2036: }
2037:
1.8 www 2038: # -------------------------------------------------------------- Replicate file
2039:
2040: sub repcopy {
2041: my $filename=shift;
1.23 www 2042: $filename=~s/\/+/\//g;
1.607 raeburn 2043: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2044: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2045: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2046: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2047: return &repcopy_userfile($filename);
2048: }
1.532 albertel 2049: $filename=~s/[\n\r]//g;
1.8 www 2050: my $transname="$filename.in.transfer";
1.828 www 2051: # FIXME: this should flock
1.607 raeburn 2052: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2053: my $remoteurl=subscribe($filename);
1.64 www 2054: if ($remoteurl =~ /^con_lost by/) {
2055: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2056: return 'unavailable';
1.8 www 2057: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2058: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2059: return 'not_found';
1.64 www 2060: } elsif ($remoteurl =~ /^rejected by/) {
2061: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2062: return 'forbidden';
1.20 www 2063: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2064: return 'ok';
1.8 www 2065: } else {
1.290 www 2066: my $author=$filename;
2067: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2068: my ($udom,$uname)=split(/\//,$author);
2069: my $home=homeserver($uname,$udom);
2070: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2071: my @parts=split(/\//,$filename);
2072: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2073: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2074: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2075: return 'bad_request';
1.8 www 2076: }
2077: my $count;
2078: for ($count=5;$count<$#parts;$count++) {
2079: $path.="/$parts[$count]";
2080: if ((-e $path)!=1) {
2081: mkdir($path,0777);
2082: }
2083: }
2084: my $ua=new LWP::UserAgent;
2085: my $request=new HTTP::Request('GET',"$remoteurl");
2086: my $response=$ua->request($request,$transname);
2087: if ($response->is_error()) {
2088: unlink($transname);
2089: my $message=$response->status_line;
1.672 albertel 2090: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2091: ." LWP get: $message: $filename</font>");
1.607 raeburn 2092: return 'unavailable';
1.8 www 2093: } else {
1.16 www 2094: if ($remoteurl!~/\.meta$/) {
2095: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2096: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2097: if ($mresponse->is_error()) {
2098: unlink($filename.'.meta');
2099: &logthis(
1.672 albertel 2100: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2101: }
2102: }
1.8 www 2103: rename($transname,$filename);
1.607 raeburn 2104: return 'ok';
1.8 www 2105: }
1.290 www 2106: }
1.8 www 2107: }
1.330 www 2108: }
2109:
2110: # ------------------------------------------------ Get server side include body
2111: sub ssi_body {
1.381 albertel 2112: my ($filelink,%form)=@_;
1.606 matthew 2113: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2114: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2115: }
1.953 www 2116: my $output='';
2117: my $response;
1.980 raeburn 2118: if ($filelink=~/^https?\:/) {
1.954 raeburn 2119: ($output,$response)=&externalssi($filelink);
1.953 www 2120: } else {
1.1004 droeschl 2121: $filelink .= $filelink=~/\?/ ? '&' : '?';
2122: $filelink .= 'inhibitmenu=yes';
1.953 www 2123: ($output,$response)=&ssi($filelink,%form);
2124: }
1.778 albertel 2125: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2126: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2127: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2128: if (wantarray) {
2129: return ($output, $response);
2130: } else {
2131: return $output;
2132: }
1.8 www 2133: }
2134:
1.15 www 2135: # --------------------------------------------------------- Server Side Include
2136:
1.782 albertel 2137: sub absolute_url {
2138: my ($host_name) = @_;
2139: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2140: if ($host_name eq '') {
2141: $host_name = $ENV{'SERVER_NAME'};
2142: }
2143: return $protocol.$host_name;
2144: }
2145:
1.942 foxr 2146: #
2147: # Server side include.
2148: # Parameters:
2149: # fn Possibly encrypted resource name/id.
2150: # form Hash that describes how the rendering should be done
2151: # and other things.
1.944 foxr 2152: # Returns:
1.950 raeburn 2153: # Scalar context: The content of the response.
2154: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2155: #
1.15 www 2156: sub ssi {
2157:
1.944 foxr 2158: my ($fn,%form)=@_;
1.15 www 2159: my $ua=new LWP::UserAgent;
1.23 www 2160: my $request;
1.711 albertel 2161:
2162: $form{'no_update_last_known'}=1;
1.895 albertel 2163: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2164: if (%form) {
1.782 albertel 2165: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2166: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2167: } else {
1.782 albertel 2168: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2169: }
2170:
1.15 www 2171: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2172: my $response=$ua->request($request);
2173:
1.944 foxr 2174: if (wantarray) {
2175: return ($response->content, $response);
2176: } else {
2177: return $response->content;
1.942 foxr 2178: }
1.324 www 2179: }
2180:
2181: sub externalssi {
2182: my ($url)=@_;
2183: my $ua=new LWP::UserAgent;
2184: my $request=new HTTP::Request('GET',$url);
2185: my $response=$ua->request($request);
1.954 raeburn 2186: if (wantarray) {
2187: return ($response->content, $response);
2188: } else {
2189: return $response->content;
2190: }
1.15 www 2191: }
1.254 www 2192:
1.492 albertel 2193: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2194:
2195: sub allowuploaded {
2196: my ($srcurl,$url)=@_;
2197: $url=&clutter(&declutter($url));
2198: my $dir=$url;
2199: $dir=~s/\/[^\/]+$//;
2200: my %httpref=();
2201: my $httpurl=&hreflocation('',$url);
2202: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2203: &Apache::lonnet::appenv(\%httpref);
1.254 www 2204: }
1.477 raeburn 2205:
1.478 albertel 2206: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2207: # input: action, courseID, current domain, intended
1.637 raeburn 2208: # path to file, source of file, instruction to parse file for objects,
2209: # ref to hash for embedded objects,
2210: # ref to hash for codebase of java objects.
1.1095 raeburn 2211: # reference to scalar to accommodate mime type determined
2212: # from File::MMagic if $parser = parse.
1.637 raeburn 2213: #
1.485 raeburn 2214: # output: url to file (if action was uploaddoc),
2215: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2216: #
1.478 albertel 2217: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2218: # course.
1.477 raeburn 2219: #
1.478 albertel 2220: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2221: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2222: # course's home server.
1.477 raeburn 2223: #
1.478 albertel 2224: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2225: # be copied from $source (current location) to
2226: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2227: # and will then be copied to
2228: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2229: # course's home server.
1.485 raeburn 2230: #
1.481 raeburn 2231: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2232: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2233: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2234: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2235: # in course's home server.
1.637 raeburn 2236: #
1.477 raeburn 2237:
2238: sub process_coursefile {
1.1095 raeburn 2239: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2240: $mimetype)=@_;
1.477 raeburn 2241: my $fetchresult;
1.638 albertel 2242: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2243: if ($action eq 'propagate') {
1.638 albertel 2244: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2245: $home);
1.481 raeburn 2246: } else {
1.477 raeburn 2247: my $fpath = '';
2248: my $fname = $file;
1.478 albertel 2249: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2250: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2251: my $filepath = &build_filepath($fpath);
1.481 raeburn 2252: if ($action eq 'copy') {
2253: if ($source eq '') {
2254: $fetchresult = 'no source file';
2255: return $fetchresult;
2256: } else {
2257: my $destination = $filepath.'/'.$fname;
2258: rename($source,$destination);
2259: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2260: $home);
1.481 raeburn 2261: }
2262: } elsif ($action eq 'uploaddoc') {
2263: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2264: print $fh $env{'form.'.$source};
1.481 raeburn 2265: close($fh);
1.637 raeburn 2266: if ($parser eq 'parse') {
1.1024 raeburn 2267: my $mm = new File::MMagic;
1.1095 raeburn 2268: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2269: if ($type eq 'text/html') {
1.1024 raeburn 2270: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2271: unless ($parse_result eq 'ok') {
2272: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2273: }
1.637 raeburn 2274: }
1.1095 raeburn 2275: if (ref($mimetype)) {
2276: $$mimetype = $type;
2277: }
1.637 raeburn 2278: }
1.477 raeburn 2279: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2280: $home);
1.481 raeburn 2281: if ($fetchresult eq 'ok') {
2282: return '/uploaded/'.$fpath.'/'.$fname;
2283: } else {
2284: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2285: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2286: return '/adm/notfound.html';
2287: }
1.477 raeburn 2288: }
2289: }
1.485 raeburn 2290: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2291: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2292: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2293: }
2294: return $fetchresult;
2295: }
2296:
1.637 raeburn 2297: sub build_filepath {
2298: my ($fpath) = @_;
2299: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2300: unless ($fpath eq '') {
2301: my @parts=split('/',$fpath);
2302: foreach my $part (@parts) {
2303: $filepath.= '/'.$part;
2304: if ((-e $filepath)!=1) {
2305: mkdir($filepath,0777);
2306: }
2307: }
2308: }
2309: return $filepath;
2310: }
2311:
2312: sub store_edited_file {
1.638 albertel 2313: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2314: my $file = $primary_url;
2315: $file =~ s#^/uploaded/$docudom/$docuname/##;
2316: my $fpath = '';
2317: my $fname = $file;
2318: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2319: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2320: my $filepath = &build_filepath($fpath);
2321: open(my $fh,'>'.$filepath.'/'.$fname);
2322: print $fh $content;
2323: close($fh);
1.638 albertel 2324: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2325: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2326: $home);
1.637 raeburn 2327: if ($$fetchresult eq 'ok') {
2328: return '/uploaded/'.$fpath.'/'.$fname;
2329: } else {
1.638 albertel 2330: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2331: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2332: return '/adm/notfound.html';
2333: }
2334: }
2335:
1.531 albertel 2336: sub clean_filename {
1.831 albertel 2337: my ($fname,$args)=@_;
1.315 www 2338: # Replace Windows backslashes by forward slashes
1.257 www 2339: $fname=~s/\\/\//g;
1.831 albertel 2340: if (!$args->{'keep_path'}) {
2341: # Get rid of everything but the actual filename
2342: $fname=~s/^.*\/([^\/]+)$/$1/;
2343: }
1.315 www 2344: # Replace spaces by underscores
2345: $fname=~s/\s+/\_/g;
2346: # Replace all other weird characters by nothing
1.831 albertel 2347: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2348: # Replace all .\d. sequences with _\d. so they no longer look like version
2349: # numbers
2350: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2351: return $fname;
2352: }
1.1051 raeburn 2353: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2354: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2355: # image with the same aspect ratio as the original, but with dimensions which do
2356: # not exceed $resizewidth and $resizeheight.
2357:
1.984 neumanie 2358: sub resizeImage {
1.1051 raeburn 2359: my ($img_path,$resizewidth,$resizeheight) = @_;
2360: my $ima = Image::Magick->new;
2361: my $resized;
2362: if (-e $img_path) {
2363: $ima->Read($img_path);
2364: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2365: my $width = $ima->Get('width');
2366: my $height = $ima->Get('height');
2367: if ($width > $resizewidth) {
2368: my $factor = $width/$resizewidth;
2369: my $newheight = $height/$factor;
2370: $ima->Scale(width=>$resizewidth,height=>$newheight);
2371: $resized = 1;
2372: }
2373: }
2374: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2375: my $width = $ima->Get('width');
2376: my $height = $ima->Get('height');
2377: if ($height > $resizeheight) {
2378: my $factor = $height/$resizeheight;
2379: my $newwidth = $width/$factor;
2380: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2381: $resized = 1;
2382: }
2383: }
2384: if ($resized) {
2385: $ima->Write($img_path);
2386: }
2387: }
2388: return;
1.977 amueller 2389: }
2390:
1.608 albertel 2391: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2392: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2393: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2394: # $context - possible values: coursedoc, existingfile, overwrite,
2395: # canceloverwrite, or ''.
2396: # if 'coursedoc': upload to the current course
2397: # if 'existingfile': write file to tmp/overwrites directory
2398: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2399: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2400: # $subdir - directory in userfile to store the file into
1.858 raeburn 2401: # $parser - instruction to parse file for objects ($parser = parse)
2402: # $allfiles - reference to hash for embedded objects
2403: # $codebase - reference to hash for codebase of java objects
2404: # $desuname - username for permanent storage of uploaded file
2405: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2406: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2407: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2408: # $resizewidth - width (pixels) to which to resize uploaded image
2409: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2410: # $mimetype - reference to scalar to accommodate mime type determined
2411: # from File::MMagic if $parser = parse.
1.858 raeburn 2412: #
1.686 albertel 2413: # output: url of file in userspace, or error: <message>
2414: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2415:
1.531 albertel 2416: sub userfileupload {
1.1090 raeburn 2417: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2418: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2419: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2420: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2421: $fname=&clean_filename($fname);
1.1090 raeburn 2422: # See if there is anything left
1.257 www 2423: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2424: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2425: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2426: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2427: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2428: my $now = time;
1.1090 raeburn 2429: my $filepath;
1.1095 raeburn 2430: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2431: $filepath = 'tmp/helprequests/'.$now;
2432: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2433: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2434: '_'.$env{'user.domain'}.'/pending';
2435: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2436: my ($docuname,$docudom);
2437: if ($destudom) {
2438: $docudom = $destudom;
2439: } else {
2440: $docudom = $env{'user.domain'};
2441: }
2442: if ($destuname) {
2443: $docuname = $destuname;
2444: } else {
2445: $docuname = $env{'user.name'};
2446: }
2447: if (exists($env{'form.group'})) {
2448: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2449: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2450: }
2451: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2452: if ($context eq 'canceloverwrite') {
2453: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2454: if (-e $tempfile) {
2455: my @info = stat($tempfile);
2456: if ($info[9] eq $env{'form.timestamp'}) {
2457: unlink($tempfile);
2458: }
2459: }
2460: return;
1.523 raeburn 2461: }
2462: }
1.1090 raeburn 2463: # Create the directory if not present
1.741 raeburn 2464: my @parts=split(/\//,$filepath);
2465: my $fullpath = $perlvar{'lonDaemons'};
2466: for (my $i=0;$i<@parts;$i++) {
2467: $fullpath .= '/'.$parts[$i];
2468: if ((-e $fullpath)!=1) {
2469: mkdir($fullpath,0777);
2470: }
2471: }
2472: open(my $fh,'>'.$fullpath.'/'.$fname);
2473: print $fh $env{'form.'.$formname};
2474: close($fh);
1.1090 raeburn 2475: if ($context eq 'existingfile') {
2476: my @info = stat($fullpath.'/'.$fname);
2477: return ($fullpath.'/'.$fname,$info[9]);
2478: } else {
2479: return $fullpath.'/'.$fname;
2480: }
1.523 raeburn 2481: }
1.995 raeburn 2482: if ($subdir eq 'scantron') {
2483: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2484: } else {
1.995 raeburn 2485: $fname="$subdir/$fname";
2486: }
1.1090 raeburn 2487: if ($context eq 'coursedoc') {
1.638 albertel 2488: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2489: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2490: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2491: return &finishuserfileupload($docuname,$docudom,
2492: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2493: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2494: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2495: } else {
1.620 albertel 2496: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2497: return &process_coursefile('uploaddoc',$docuname,$docudom,
2498: $fname,$formname,$parser,
1.1095 raeburn 2499: $allfiles,$codebase,$mimetype);
1.481 raeburn 2500: }
1.719 banghart 2501: } elsif (defined($destuname)) {
2502: my $docuname=$destuname;
2503: my $docudom=$destudom;
1.860 raeburn 2504: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2505: $parser,$allfiles,$codebase,
1.1051 raeburn 2506: $thumbwidth,$thumbheight,
1.1095 raeburn 2507: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2508: } else {
1.638 albertel 2509: my $docuname=$env{'user.name'};
2510: my $docudom=$env{'user.domain'};
1.714 raeburn 2511: if (exists($env{'form.group'})) {
2512: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2513: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2514: }
1.860 raeburn 2515: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2516: $parser,$allfiles,$codebase,
1.1051 raeburn 2517: $thumbwidth,$thumbheight,
1.1095 raeburn 2518: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2519: }
1.271 www 2520: }
2521:
2522: sub finishuserfileupload {
1.860 raeburn 2523: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2524: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2525: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2526: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2527:
1.860 raeburn 2528: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2529: $file=$fname;
2530: if ($fname=~m|/|) {
2531: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2532: $path.=$fnamepath.'/';
2533: }
1.259 www 2534: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2535: my $count;
2536: for ($count=4;$count<=$#parts;$count++) {
2537: $filepath.="/$parts[$count]";
2538: if ((-e $filepath)!=1) {
2539: mkdir($filepath,0777);
2540: }
2541: }
1.984 neumanie 2542:
1.258 www 2543: # Save the file
2544: {
1.701 albertel 2545: if (!open(FH,'>'.$filepath.'/'.$file)) {
2546: &logthis('Failed to create '.$filepath.'/'.$file);
2547: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2548: return '/adm/notfound.html';
2549: }
1.1090 raeburn 2550: if ($context eq 'overwrite') {
2551: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2552: my $target = $filepath.'/'.$file;
2553: if (-e $source) {
2554: my @info = stat($source);
2555: if ($info[9] eq $env{'form.timestamp'}) {
2556: unless (&File::Copy::move($source,$target)) {
2557: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2558: return "Moving from $source failed";
2559: }
2560: } else {
2561: return "Temporary file: $source had unexpected date/time for last modification";
2562: }
2563: } else {
2564: return "Temporary file: $source missing";
2565: }
2566: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2567: &logthis('Failed to write to '.$filepath.'/'.$file);
2568: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2569: return '/adm/notfound.html';
2570: }
1.570 albertel 2571: close(FH);
1.1051 raeburn 2572: if ($resizewidth && $resizeheight) {
2573: my $mm = new File::MMagic;
2574: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2575: if ($mime_type =~ m{^image/}) {
2576: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2577: }
1.977 amueller 2578: }
1.258 www 2579: }
1.637 raeburn 2580: if ($parser eq 'parse') {
1.1024 raeburn 2581: my $mm = new File::MMagic;
1.1095 raeburn 2582: my $type = $mm->checktype_filename($filepath.'/'.$file);
2583: if ($type eq 'text/html') {
1.1024 raeburn 2584: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2585: $allfiles,$codebase);
2586: unless ($parse_result eq 'ok') {
2587: &logthis('Failed to parse '.$filepath.$file.
2588: ' for embedded media: '.$parse_result);
2589: }
1.637 raeburn 2590: }
1.1095 raeburn 2591: if (ref($mimetype)) {
2592: $$mimetype = $type;
2593: }
1.637 raeburn 2594: }
1.860 raeburn 2595: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2596: my $input = $filepath.'/'.$file;
2597: my $output = $filepath.'/'.'tn-'.$file;
2598: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2599: system("convert -sample $thumbsize $input $output");
2600: if (-e $filepath.'/'.'tn-'.$file) {
2601: $fetchthumb = 1;
2602: }
2603: }
1.858 raeburn 2604:
1.259 www 2605: # Notify homeserver to grep it
2606: #
1.984 neumanie 2607: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2608: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2609: if ($fetchresult eq 'ok') {
1.860 raeburn 2610: if ($fetchthumb) {
2611: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2612: if ($thumbresult ne 'ok') {
2613: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2614: $docuhome.': '.$thumbresult);
2615: }
2616: }
1.259 www 2617: #
1.258 www 2618: # Return the URL to it
1.494 albertel 2619: return '/uploaded/'.$path.$file;
1.263 www 2620: } else {
1.494 albertel 2621: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2622: ': '.$fetchresult);
1.263 www 2623: return '/adm/notfound.html';
1.858 raeburn 2624: }
1.493 albertel 2625: }
2626:
1.637 raeburn 2627: sub extract_embedded_items {
1.961 raeburn 2628: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2629: my @state = ();
2630: my %javafiles = (
2631: codebase => '',
2632: code => '',
2633: archive => ''
2634: );
2635: my %mediafiles = (
2636: src => '',
2637: movie => '',
2638: );
1.648 raeburn 2639: my $p;
2640: if ($content) {
2641: $p = HTML::LCParser->new($content);
2642: } else {
1.961 raeburn 2643: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2644: }
1.641 albertel 2645: while (my $t=$p->get_token()) {
1.640 albertel 2646: if ($t->[0] eq 'S') {
2647: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2648: push(@state, $tagname);
1.648 raeburn 2649: if (lc($tagname) eq 'allow') {
2650: &add_filetype($allfiles,$attr->{'src'},'src');
2651: }
1.640 albertel 2652: if (lc($tagname) eq 'img') {
2653: &add_filetype($allfiles,$attr->{'src'},'src');
2654: }
1.886 albertel 2655: if (lc($tagname) eq 'a') {
2656: &add_filetype($allfiles,$attr->{'href'},'href');
2657: }
1.645 raeburn 2658: if (lc($tagname) eq 'script') {
2659: if ($attr->{'archive'} =~ /\.jar$/i) {
2660: &add_filetype($allfiles,$attr->{'archive'},'archive');
2661: } else {
2662: &add_filetype($allfiles,$attr->{'src'},'src');
2663: }
2664: }
2665: if (lc($tagname) eq 'link') {
2666: if (lc($attr->{'rel'}) eq 'stylesheet') {
2667: &add_filetype($allfiles,$attr->{'href'},'href');
2668: }
2669: }
1.640 albertel 2670: if (lc($tagname) eq 'object' ||
2671: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2672: foreach my $item (keys(%javafiles)) {
2673: $javafiles{$item} = '';
2674: }
2675: }
2676: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2677: my $name = lc($attr->{'name'});
2678: foreach my $item (keys(%javafiles)) {
2679: if ($name eq $item) {
2680: $javafiles{$item} = $attr->{'value'};
2681: last;
2682: }
2683: }
2684: foreach my $item (keys(%mediafiles)) {
2685: if ($name eq $item) {
2686: &add_filetype($allfiles, $attr->{'value'}, 'value');
2687: last;
2688: }
2689: }
2690: }
2691: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2692: foreach my $item (keys(%javafiles)) {
2693: if ($attr->{$item}) {
2694: $javafiles{$item} = $attr->{$item};
2695: last;
2696: }
2697: }
2698: foreach my $item (keys(%mediafiles)) {
2699: if ($attr->{$item}) {
2700: &add_filetype($allfiles,$attr->{$item},$item);
2701: last;
2702: }
2703: }
2704: }
2705: } elsif ($t->[0] eq 'E') {
2706: my ($tagname) = ($t->[1]);
2707: if ($javafiles{'codebase'} ne '') {
2708: $javafiles{'codebase'} .= '/';
2709: }
2710: if (lc($tagname) eq 'applet' ||
2711: lc($tagname) eq 'object' ||
2712: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2713: ) {
2714: foreach my $item (keys(%javafiles)) {
2715: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2716: my $file=$javafiles{'codebase'}.$javafiles{$item};
2717: &add_filetype($allfiles,$file,$item);
2718: }
2719: }
2720: }
2721: pop @state;
2722: }
2723: }
1.637 raeburn 2724: return 'ok';
2725: }
2726:
1.639 albertel 2727: sub add_filetype {
2728: my ($allfiles,$file,$type)=@_;
2729: if (exists($allfiles->{$file})) {
2730: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2731: push(@{$allfiles->{$file}}, &escape($type));
2732: }
2733: } else {
2734: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2735: }
2736: }
2737:
1.493 albertel 2738: sub removeuploadedurl {
1.984 neumanie 2739: my ($url)=@_;
2740: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2741: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2742: }
2743:
2744: sub removeuserfile {
2745: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2746: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2747: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2748: if ($result eq 'ok') {
1.798 raeburn 2749: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2750: my $metafile = $fname.'.meta';
2751: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2752: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2753: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2754: my $sqlresult =
1.823 albertel 2755: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2756: 'portfolio_metadata',$group,
2757: 'delete');
1.798 raeburn 2758: }
2759: }
2760: return $result;
1.257 www 2761: }
1.15 www 2762:
1.530 albertel 2763: sub mkdiruserfile {
2764: my ($docuname,$docudom,$dir)=@_;
2765: my $home=&homeserver($docuname,$docudom);
2766: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2767: }
2768:
1.531 albertel 2769: sub renameuserfile {
2770: my ($docuname,$docudom,$old,$new)=@_;
2771: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2772: my $result = &reply("renameuserfile:$docudom:$docuname:".
2773: &escape("$old").':'.&escape("$new"),$home);
2774: if ($result eq 'ok') {
2775: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2776: my $oldmeta = $old.'.meta';
2777: my $newmeta = $new.'.meta';
2778: my $metaresult =
2779: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2780: my $url = "/uploaded/$docudom/$docuname/$old";
2781: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2782: my $sqlresult =
1.823 albertel 2783: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2784: 'portfolio_metadata',$group,
2785: 'delete');
1.798 raeburn 2786: }
2787: }
2788: return $result;
1.531 albertel 2789: }
2790:
1.14 www 2791: # ------------------------------------------------------------------------- Log
2792:
2793: sub log {
2794: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2795: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2796: }
2797:
2798: # ------------------------------------------------------------------ Course Log
1.352 www 2799: #
2800: # This routine flushes several buffers of non-mission-critical nature
2801: #
1.157 www 2802:
2803: sub flushcourselogs {
1.352 www 2804: &logthis('Flushing log buffers');
2805: #
2806: # course logs
2807: # This is a log of all transactions in a course, which can be used
2808: # for data mining purposes
2809: #
2810: # It also collects the courseid database, which lists last transaction
2811: # times and course titles for all courseids
2812: #
2813: my %courseidbuffer=();
1.921 raeburn 2814: foreach my $crsid (keys(%courselogs)) {
1.352 www 2815: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2816: &escape($courselogs{$crsid}),
2817: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2818: delete $courselogs{$crsid};
2819: } else {
2820: &logthis('Failed to flush log buffer for '.$crsid);
2821: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2822: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2823: " exceeded maximum size, deleting.</font>");
2824: delete $courselogs{$crsid};
2825: }
1.352 www 2826: }
1.920 raeburn 2827: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2828: 'description' => $coursedescrbuf{$crsid},
2829: 'inst_code' => $courseinstcodebuf{$crsid},
2830: 'type' => $coursetypebuf{$crsid},
2831: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2832: };
1.191 harris41 2833: }
1.352 www 2834: #
2835: # Write course id database (reverse lookup) to homeserver of courses
2836: # Is used in pickcourse
2837: #
1.840 albertel 2838: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2839: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2840: $courseidbuffer{$crs_home},
2841: $crs_home,'timeonly');
1.352 www 2842: }
2843: #
2844: # File accesses
2845: # Writes to the dynamic metadata of resources to get hit counts, etc.
2846: #
1.449 matthew 2847: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2848: if ($entry =~ /___count$/) {
2849: my ($dom,$name);
1.807 albertel 2850: ($dom,$name,undef)=
1.811 albertel 2851: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2852: if (! defined($dom) || $dom eq '' ||
2853: ! defined($name) || $name eq '') {
1.620 albertel 2854: my $cid = $env{'request.course.id'};
2855: $dom = $env{'request.'.$cid.'.domain'};
2856: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2857: }
1.450 matthew 2858: my $value = $accesshash{$entry};
2859: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2860: my %temphash=($url => $value);
1.449 matthew 2861: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2862: if ($result eq 'ok') {
2863: delete $accesshash{$entry};
2864: } elsif ($result eq 'unknown_cmd') {
2865: # Target server has old code running on it.
1.450 matthew 2866: my %temphash=($entry => $value);
1.449 matthew 2867: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2868: delete $accesshash{$entry};
2869: }
2870: }
2871: } else {
1.811 albertel 2872: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2873: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2874: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2875: delete $accesshash{$entry};
2876: }
1.185 www 2877: }
1.191 harris41 2878: }
1.352 www 2879: #
2880: # Roles
2881: # Reverse lookup of user roles for course faculty/staff and co-authorship
2882: #
1.800 albertel 2883: foreach my $entry (keys(%userrolehash)) {
1.351 www 2884: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2885: split(/\:/,$entry);
2886: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2887: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2888: $rudom,$runame) eq 'ok') {
2889: delete $userrolehash{$entry};
2890: }
2891: }
1.662 raeburn 2892: #
2893: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2894: #
2895: my %domrolebuffer = ();
1.1000 raeburn 2896: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2897: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2898: if ($domrolebuffer{$rudom}) {
2899: $domrolebuffer{$rudom}.='&'.&escape($entry).
2900: '='.&escape($domainrolehash{$entry});
2901: } else {
2902: $domrolebuffer{$rudom}.=&escape($entry).
2903: '='.&escape($domainrolehash{$entry});
2904: }
2905: delete $domainrolehash{$entry};
2906: }
2907: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2908: my %servers = &get_servers($dom,'library');
2909: foreach my $tryserver (keys(%servers)) {
2910: unless (&reply('domroleput:'.$dom.':'.
2911: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2912: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2913: }
1.662 raeburn 2914: }
2915: }
1.186 www 2916: $dumpcount++;
1.157 www 2917: }
2918:
2919: sub courselog {
2920: my $what=shift;
1.158 www 2921: $what=time.':'.$what;
1.620 albertel 2922: unless ($env{'request.course.id'}) { return ''; }
2923: $coursedombuf{$env{'request.course.id'}}=
2924: $env{'course.'.$env{'request.course.id'}.'.domain'};
2925: $coursenumbuf{$env{'request.course.id'}}=
2926: $env{'course.'.$env{'request.course.id'}.'.num'};
2927: $coursehombuf{$env{'request.course.id'}}=
2928: $env{'course.'.$env{'request.course.id'}.'.home'};
2929: $coursedescrbuf{$env{'request.course.id'}}=
2930: $env{'course.'.$env{'request.course.id'}.'.description'};
2931: $courseinstcodebuf{$env{'request.course.id'}}=
2932: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2933: $courseownerbuf{$env{'request.course.id'}}=
2934: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2935: $coursetypebuf{$env{'request.course.id'}}=
2936: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2937: if (defined $courselogs{$env{'request.course.id'}}) {
2938: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2939: } else {
1.620 albertel 2940: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2941: }
1.620 albertel 2942: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2943: &flushcourselogs();
2944: }
1.158 www 2945: }
2946:
2947: sub courseacclog {
2948: my $fnsymb=shift;
1.620 albertel 2949: unless ($env{'request.course.id'}) { return ''; }
2950: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2951: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2952: $what.=':POST';
1.583 matthew 2953: # FIXME: Probably ought to escape things....
1.800 albertel 2954: foreach my $key (keys(%env)) {
2955: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2956: my $formitem = $1;
2957: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2958: $what.=':'.$formitem.'='.$env{$key};
2959: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2960: $what.=':'.$formitem.'='.$env{$key};
2961: }
1.158 www 2962: }
1.191 harris41 2963: }
1.583 matthew 2964: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2965: # FIXME: We should not be depending on a form parameter that someone
2966: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2967: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2968: $what.= ':POST';
2969: # FIXME: Probably ought to escape things....
2970: foreach my $element ('courseexp','crsfulltext','crsrelated',
2971: 'crsdiscuss') {
1.620 albertel 2972: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2973: }
2974: }
1.158 www 2975: }
2976: &courselog($what);
1.149 www 2977: }
2978:
1.185 www 2979: sub countacc {
2980: my $url=&declutter(shift);
1.458 matthew 2981: return if (! defined($url) || $url eq '');
1.620 albertel 2982: unless ($env{'request.course.id'}) { return ''; }
2983: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2984: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2985: $accesshash{$key}++;
1.185 www 2986: }
1.349 www 2987:
1.361 www 2988: sub linklog {
2989: my ($from,$to)=@_;
2990: $from=&declutter($from);
2991: $to=&declutter($to);
2992: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2993: $accesshash{$to.'___'.$from.'___goto'}=1;
2994: }
2995:
1.349 www 2996: sub userrolelog {
2997: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2998: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2999: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3000: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3001: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3002: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3003: $userrolehash
3004: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3005: =$tend.':'.$tstart;
1.662 raeburn 3006: }
1.898 albertel 3007: if (($env{'request.role'} =~ /dc\./) &&
3008: (($trole=~/^au/) || ($trole=~/^in/) ||
3009: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3010: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3011: ($trole=~/^co/))) {
1.898 albertel 3012: $userrolehash
3013: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3014: =$tend.':'.$tstart;
3015: }
1.662 raeburn 3016: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3017: ($trole=~/^li/) || ($trole=~/^li/) ||
3018: ($trole=~/^au/) || ($trole=~/^dg/) ||
3019: ($trole=~/^sc/)) {
3020: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3021: $domainrolehash
3022: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3023: = $tend.':'.$tstart;
3024: }
1.351 www 3025: }
3026:
1.957 raeburn 3027: sub courserolelog {
3028: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3029: if (($trole eq 'cc') || ($trole eq 'in') ||
3030: ($trole eq 'ep') || ($trole eq 'ad') ||
3031: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3032: ($trole=~/^cr/) || ($trole eq 'gr') ||
3033: ($trole eq 'co')) {
1.957 raeburn 3034: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3035: my $cdom = $1;
3036: my $cnum = $2;
3037: my $sec = $3;
3038: my $namespace = 'rolelog';
3039: my %storehash = (
3040: role => $trole,
3041: start => $tstart,
3042: end => $tend,
3043: selfenroll => $selfenroll,
3044: context => $context,
3045: );
3046: if ($trole eq 'gr') {
3047: $namespace = 'groupslog';
3048: $storehash{'group'} = $sec;
3049: } else {
3050: $storehash{'section'} = $sec;
3051: }
3052: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3053: if (($trole ne 'st') || ($sec ne '')) {
3054: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3055: }
1.957 raeburn 3056: }
3057: }
3058: return;
3059: }
3060:
1.351 www 3061: sub get_course_adv_roles {
1.948 raeburn 3062: my ($cid,$codes) = @_;
1.620 albertel 3063: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3064: my %coursehash=&coursedescription($cid);
1.988 raeburn 3065: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3066: my %nothide=();
1.800 albertel 3067: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3068: if ($user !~ /:/) {
3069: $nothide{join(':',split(/[\@]/,$user))}=1;
3070: } else {
3071: $nothide{$user}=1;
3072: }
1.470 www 3073: }
1.351 www 3074: my %returnhash=();
3075: my %dumphash=
3076: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3077: my $now=time;
1.997 raeburn 3078: my %privileged;
1.1000 raeburn 3079: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3080: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3081: if (($tstart) && ($tstart<0)) { next; }
3082: if (($tend) && ($tend<$now)) { next; }
3083: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3084: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3085: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3086: unless (ref($privileged{$domain}) eq 'HASH') {
3087: my %dompersonnel =
1.998 raeburn 3088: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3089: $privileged{$domain} = {};
3090: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3091: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3092: foreach my $user (keys(%{$dompersonnel{$server}})) {
3093: my ($trole,$uname,$udom) = split(/:/,$user);
3094: $privileged{$udom}{$uname} = 1;
3095: }
3096: }
3097: }
3098: }
3099: if ((exists($privileged{$domain}{$username})) &&
3100: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3101: if ($role eq 'cr') { next; }
1.948 raeburn 3102: if ($codes) {
3103: if ($section) { $role .= ':'.$section; }
3104: if ($returnhash{$role}) {
3105: $returnhash{$role}.=','.$username.':'.$domain;
3106: } else {
3107: $returnhash{$role}=$username.':'.$domain;
3108: }
1.351 www 3109: } else {
1.988 raeburn 3110: my $key=&plaintext($role,$crstype);
1.973 bisitz 3111: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3112: if ($returnhash{$key}) {
3113: $returnhash{$key}.=','.$username.':'.$domain;
3114: } else {
3115: $returnhash{$key}=$username.':'.$domain;
3116: }
1.351 www 3117: }
1.948 raeburn 3118: }
1.400 www 3119: return %returnhash;
3120: }
3121:
3122: sub get_my_roles {
1.937 raeburn 3123: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3124: unless (defined($uname)) { $uname=$env{'user.name'}; }
3125: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3126: my (%dumphash,%nothide);
1.1086 raeburn 3127: if ($context eq 'userroles') {
3128: my $extra = &freeze_escape({'skipcheck' => 1});
3129: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3130: } else {
3131: %dumphash=
1.400 www 3132: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3133: if ($hidepriv) {
3134: my %coursehash=&coursedescription($udom.'_'.$uname);
3135: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3136: if ($user !~ /:/) {
3137: $nothide{join(':',split(/[\@]/,$user))} = 1;
3138: } else {
3139: $nothide{$user} = 1;
3140: }
3141: }
3142: }
1.858 raeburn 3143: }
1.400 www 3144: my %returnhash=();
3145: my $now=time;
1.999 raeburn 3146: my %privileged;
1.800 albertel 3147: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3148: my ($role,$tend,$tstart);
3149: if ($context eq 'userroles') {
3150: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3151: } else {
3152: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3153: }
1.400 www 3154: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3155: my $status = 'active';
1.939 raeburn 3156: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3157: $status = 'previous';
3158: }
3159: if (($tstart) && ($now<$tstart)) {
3160: $status = 'future';
3161: }
3162: if (ref($types) eq 'ARRAY') {
3163: if (!grep(/^\Q$status\E$/,@{$types})) {
3164: next;
3165: }
3166: } else {
3167: if ($status ne 'active') {
3168: next;
3169: }
3170: }
1.867 raeburn 3171: my ($rolecode,$username,$domain,$section,$area);
3172: if ($context eq 'userroles') {
3173: ($area,$rolecode) = split(/_/,$entry);
3174: (undef,$domain,$username,$section) = split(/\//,$area);
3175: } else {
3176: ($role,$username,$domain,$section) = split(/\:/,$entry);
3177: }
1.832 raeburn 3178: if (ref($roledoms) eq 'ARRAY') {
3179: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3180: next;
3181: }
3182: }
3183: if (ref($roles) eq 'ARRAY') {
3184: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3185: if ($role =~ /^cr\//) {
3186: if (!grep(/^cr$/,@{$roles})) {
3187: next;
3188: }
1.1104 raeburn 3189: } elsif ($role =~ /^gr\//) {
3190: if (!grep(/^gr$/,@{$roles})) {
3191: next;
3192: }
1.922 raeburn 3193: } else {
3194: next;
3195: }
1.832 raeburn 3196: }
1.867 raeburn 3197: }
1.937 raeburn 3198: if ($hidepriv) {
1.999 raeburn 3199: if ($context eq 'userroles') {
3200: if ((&privileged($username,$domain)) &&
3201: (!$nothide{$username.':'.$domain})) {
3202: next;
3203: }
3204: } else {
3205: unless (ref($privileged{$domain}) eq 'HASH') {
3206: my %dompersonnel =
3207: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3208: $privileged{$domain} = {};
3209: if (keys(%dompersonnel)) {
3210: foreach my $server (keys(%dompersonnel)) {
3211: if (ref($dompersonnel{$server}) eq 'HASH') {
3212: foreach my $user (keys(%{$dompersonnel{$server}})) {
3213: my ($trole,$uname,$udom) = split(/:/,$user);
3214: $privileged{$udom}{$uname} = $trole;
3215: }
3216: }
3217: }
3218: }
3219: }
3220: if (exists($privileged{$domain}{$username})) {
3221: if (!$nothide{$username.':'.$domain}) {
3222: next;
3223: }
3224: }
1.937 raeburn 3225: }
3226: }
1.933 raeburn 3227: if ($withsec) {
3228: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3229: $tstart.':'.$tend;
3230: } else {
3231: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3232: }
1.832 raeburn 3233: }
1.373 www 3234: return %returnhash;
1.399 www 3235: }
3236:
3237: # ----------------------------------------------------- Frontpage Announcements
3238: #
3239: #
3240:
3241: sub postannounce {
3242: my ($server,$text)=@_;
1.844 albertel 3243: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3244: unless ($text=~/\w/) { $text=''; }
3245: return &reply('setannounce:'.&escape($text),$server);
3246: }
3247:
3248: sub getannounce {
1.448 albertel 3249:
3250: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3251: my $announcement='';
1.800 albertel 3252: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3253: close($fh);
1.399 www 3254: if ($announcement=~/\w/) {
3255: return
3256: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3257: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3258: } else {
3259: return '';
3260: }
3261: } else {
3262: return '';
3263: }
1.351 www 3264: }
1.353 www 3265:
3266: # ---------------------------------------------------------- Course ID routines
3267: # Deal with domain's nohist_courseid.db files
3268: #
3269:
3270: sub courseidput {
1.921 raeburn 3271: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3272: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3273: my $outcome;
3274: if ($caller eq 'timeonly') {
3275: my $cids = '';
3276: foreach my $item (keys(%$storehash)) {
3277: $cids.=&escape($item).'&';
3278: }
3279: $cids=~s/\&$//;
3280: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3281: $coursehome);
3282: } else {
3283: my $items = '';
3284: foreach my $item (keys(%$storehash)) {
3285: $items.= &escape($item).'='.
3286: &freeze_escape($$storehash{$item}).'&';
3287: }
3288: $items=~s/\&$//;
3289: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3290: $coursehome);
1.918 raeburn 3291: }
3292: if ($outcome eq 'unknown_cmd') {
3293: my $what;
3294: foreach my $cid (keys(%$storehash)) {
3295: $what .= &escape($cid).'=';
1.921 raeburn 3296: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3297: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3298: }
3299: $what =~ s/\:$/&/;
3300: }
3301: $what =~ s/\&$//;
3302: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3303: } else {
3304: return $outcome;
3305: }
1.353 www 3306: }
3307:
3308: sub courseiddump {
1.921 raeburn 3309: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3310: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3311: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3312: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3313: my $as_hash = 1;
3314: my %returnhash;
3315: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3316: my %libserv = &all_library();
3317: foreach my $tryserver (keys(%libserv)) {
3318: if ( ( $hostidflag == 1
3319: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3320: || (!defined($hostidflag)) ) {
3321:
1.918 raeburn 3322: if (($domfilter eq '') ||
3323: (&host_domain($tryserver) eq $domfilter)) {
3324: my $rep =
3325: &reply('courseiddump:'.&host_domain($tryserver).':'.
3326: $sincefilter.':'.&escape($descfilter).':'.
3327: &escape($instcodefilter).':'.&escape($ownerfilter).
3328: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3329: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3330: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3331: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3332: &escape($cc_clone).':'.$cloneonly.':'.
3333: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3334: &escape($creationcontext).':'.$domcloner,
3335: $tryserver);
1.918 raeburn 3336: my @pairs=split(/\&/,$rep);
3337: foreach my $item (@pairs) {
3338: my ($key,$value)=split(/\=/,$item,2);
3339: $key = &unescape($key);
3340: next if ($key =~ /^error: 2 /);
3341: my $result = &thaw_unescape($value);
3342: if (ref($result) eq 'HASH') {
3343: $returnhash{$key}=$result;
3344: } else {
1.921 raeburn 3345: my @responses = split(/:/,$value);
3346: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3347: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3348: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3349: }
1.1008 raeburn 3350: }
1.353 www 3351: }
3352: }
3353: }
3354: }
3355: return %returnhash;
3356: }
3357:
1.1055 raeburn 3358: sub courselastaccess {
3359: my ($cdom,$cnum,$hostidref) = @_;
3360: my %returnhash;
3361: if ($cdom && $cnum) {
3362: my $chome = &homeserver($cnum,$cdom);
3363: if ($chome ne 'no_host') {
3364: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3365: &extract_lastaccess(\%returnhash,$rep);
3366: }
3367: } else {
3368: if (!$cdom) { $cdom=''; }
3369: my %libserv = &all_library();
3370: foreach my $tryserver (keys(%libserv)) {
3371: if (ref($hostidref) eq 'ARRAY') {
3372: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3373: }
3374: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3375: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3376: &extract_lastaccess(\%returnhash,$rep);
3377: }
3378: }
3379: }
3380: return %returnhash;
3381: }
3382:
3383: sub extract_lastaccess {
3384: my ($returnhash,$rep) = @_;
3385: if (ref($returnhash) eq 'HASH') {
3386: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3387: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3388: $rep eq '') {
3389: my @pairs=split(/\&/,$rep);
3390: foreach my $item (@pairs) {
3391: my ($key,$value)=split(/\=/,$item,2);
3392: $key = &unescape($key);
3393: next if ($key =~ /^error: 2 /);
3394: $returnhash->{$key} = &thaw_unescape($value);
3395: }
3396: }
3397: }
3398: return;
3399: }
3400:
1.658 raeburn 3401: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3402:
3403: sub dcmailput {
1.685 raeburn 3404: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3405: my $status = &Apache::lonnet::critical(
1.740 www 3406: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3407: &escape($message),$server);
1.662 raeburn 3408: return $status;
3409: }
3410:
1.658 raeburn 3411: sub dcmaildump {
3412: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3413: my %returnhash=();
1.846 albertel 3414:
3415: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3416: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3417: &escape($enddate).':';
3418: my @esc_senders=map { &escape($_)} @$senders;
3419: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3420: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3421: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3422: if (($key) && ($value)) {
3423: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3424: }
3425: }
3426: }
3427: return %returnhash;
3428: }
1.662 raeburn 3429: # ---------------------------------------------------------- Domain roles
3430:
3431: sub get_domain_roles {
3432: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3433: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3434: $startdate = '.';
3435: }
1.1018 raeburn 3436: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3437: $enddate = '.';
3438: }
1.922 raeburn 3439: my $rolelist;
3440: if (ref($roles) eq 'ARRAY') {
3441: $rolelist = join(':',@{$roles});
3442: }
1.662 raeburn 3443: my %personnel = ();
1.841 albertel 3444:
3445: my %servers = &get_servers($dom,'library');
3446: foreach my $tryserver (keys(%servers)) {
3447: %{$personnel{$tryserver}}=();
3448: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3449: &escape($startdate).':'.
3450: &escape($enddate).':'.
3451: &escape($rolelist), $tryserver))) {
3452: my ($key,$value) = split(/\=/,$line,2);
3453: if (($key) && ($value)) {
3454: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3455: }
3456: }
1.662 raeburn 3457: }
3458: return %personnel;
3459: }
1.658 raeburn 3460:
1.1057 www 3461: # ----------------------------------------------------------- Interval timing
1.149 www 3462:
1.504 albertel 3463: sub get_first_access {
3464: my ($type,$argsymb)=@_;
1.790 albertel 3465: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3466: if ($argsymb) { $symb=$argsymb; }
3467: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3468: if ($type eq 'course') {
3469: $res='course';
3470: } elsif ($type eq 'map') {
1.588 albertel 3471: $res=&symbread($map);
3472: } else {
3473: $res=$symb;
3474: }
3475: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3476: return $times{"$courseid\0$res"};
1.504 albertel 3477: }
3478:
3479: sub set_first_access {
3480: my ($type)=@_;
1.790 albertel 3481: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3482: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3483: if ($type eq 'course') {
3484: $res='course';
3485: } elsif ($type eq 'map') {
1.588 albertel 3486: $res=&symbread($map);
3487: } else {
3488: $res=$symb;
3489: }
3490: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3491: if (!$firstaccess) {
1.588 albertel 3492: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3493: }
3494: return 'already_set';
1.504 albertel 3495: }
3496:
1.110 www 3497: # --------------------------------------------- Set Expire Date for Spreadsheet
3498:
3499: sub expirespread {
3500: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3501: my $cid=$env{'request.course.id'};
1.110 www 3502: if ($cid) {
3503: my $now=time;
3504: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3505: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3506: $env{'course.'.$cid.'.num'}.
1.110 www 3507: ':nohist_expirationdates:'.
3508: &escape($key).'='.$now,
1.620 albertel 3509: $env{'course.'.$cid.'.home'})
1.110 www 3510: }
3511: return 'ok';
1.14 www 3512: }
3513:
1.109 www 3514: # ----------------------------------------------------- Devalidate Spreadsheets
3515:
3516: sub devalidate {
1.325 www 3517: my ($symb,$uname,$udom)=@_;
1.620 albertel 3518: my $cid=$env{'request.course.id'};
1.109 www 3519: if ($cid) {
1.391 matthew 3520: # delete the stored spreadsheets for
3521: # - the student level sheet of this user in course's homespace
3522: # - the assessment level sheet for this resource
3523: # for this user in user's homespace
1.553 albertel 3524: # - current conditional state info
1.325 www 3525: my $key=$uname.':'.$udom.':';
1.109 www 3526: my $status=
1.299 matthew 3527: &del('nohist_calculatedsheets',
1.391 matthew 3528: [$key.'studentcalc:'],
1.620 albertel 3529: $env{'course.'.$cid.'.domain'},
3530: $env{'course.'.$cid.'.num'})
1.133 albertel 3531: .' '.
3532: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3533: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3534: unless ($status eq 'ok ok') {
3535: &logthis('Could not devalidate spreadsheet '.
1.325 www 3536: $uname.' at '.$udom.' for '.
1.109 www 3537: $symb.': '.$status);
1.133 albertel 3538: }
1.553 albertel 3539: &delenv('user.state.'.$cid);
1.109 www 3540: }
3541: }
3542:
1.265 albertel 3543: sub get_scalar {
3544: my ($string,$end) = @_;
3545: my $value;
3546: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3547: $value = $1;
3548: } elsif ($$string =~ s/^([^&]*?)&//) {
3549: $value = $1;
3550: }
3551: return &unescape($value);
3552: }
3553:
3554: sub array2str {
3555: my (@array) = @_;
3556: my $result=&arrayref2str(\@array);
3557: $result=~s/^__ARRAY_REF__//;
3558: $result=~s/__END_ARRAY_REF__$//;
3559: return $result;
3560: }
3561:
1.204 albertel 3562: sub arrayref2str {
3563: my ($arrayref) = @_;
1.265 albertel 3564: my $result='__ARRAY_REF__';
1.204 albertel 3565: foreach my $elem (@$arrayref) {
1.265 albertel 3566: if(ref($elem) eq 'ARRAY') {
3567: $result.=&arrayref2str($elem).'&';
3568: } elsif(ref($elem) eq 'HASH') {
3569: $result.=&hashref2str($elem).'&';
3570: } elsif(ref($elem)) {
3571: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3572: } else {
3573: $result.=&escape($elem).'&';
3574: }
3575: }
3576: $result=~s/\&$//;
1.265 albertel 3577: $result .= '__END_ARRAY_REF__';
1.204 albertel 3578: return $result;
3579: }
3580:
1.168 albertel 3581: sub hash2str {
1.204 albertel 3582: my (%hash) = @_;
3583: my $result=&hashref2str(\%hash);
1.265 albertel 3584: $result=~s/^__HASH_REF__//;
3585: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3586: return $result;
3587: }
3588:
3589: sub hashref2str {
3590: my ($hashref)=@_;
1.265 albertel 3591: my $result='__HASH_REF__';
1.800 albertel 3592: foreach my $key (sort(keys(%$hashref))) {
3593: if (ref($key) eq 'ARRAY') {
3594: $result.=&arrayref2str($key).'=';
3595: } elsif (ref($key) eq 'HASH') {
3596: $result.=&hashref2str($key).'=';
3597: } elsif (ref($key)) {
1.265 albertel 3598: $result.='=';
1.800 albertel 3599: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3600: } else {
1.800 albertel 3601: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3602: }
3603:
1.800 albertel 3604: if(ref($hashref->{$key}) eq 'ARRAY') {
3605: $result.=&arrayref2str($hashref->{$key}).'&';
3606: } elsif(ref($hashref->{$key}) eq 'HASH') {
3607: $result.=&hashref2str($hashref->{$key}).'&';
3608: } elsif(ref($hashref->{$key})) {
1.265 albertel 3609: $result.='&';
1.800 albertel 3610: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3611: } else {
1.800 albertel 3612: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3613: }
3614: }
1.168 albertel 3615: $result=~s/\&$//;
1.265 albertel 3616: $result .= '__END_HASH_REF__';
1.168 albertel 3617: return $result;
3618: }
3619:
3620: sub str2hash {
1.265 albertel 3621: my ($string)=@_;
3622: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3623: return %$hash;
3624: }
3625:
3626: sub str2hashref {
1.168 albertel 3627: my ($string) = @_;
1.265 albertel 3628:
3629: my %hash;
3630:
3631: if($string !~ /^__HASH_REF__/) {
3632: if (! ($string eq '' || !defined($string))) {
3633: $hash{'error'}='Not hash reference';
3634: }
3635: return (\%hash, $string);
3636: }
3637:
3638: $string =~ s/^__HASH_REF__//;
3639:
3640: while($string !~ /^__END_HASH_REF__/) {
3641: #key
3642: my $key='';
3643: if($string =~ /^__HASH_REF__/) {
3644: ($key, $string)=&str2hashref($string);
3645: if(defined($key->{'error'})) {
3646: $hash{'error'}='Bad data';
3647: return (\%hash, $string);
3648: }
3649: } elsif($string =~ /^__ARRAY_REF__/) {
3650: ($key, $string)=&str2arrayref($string);
3651: if($key->[0] eq 'Array reference error') {
3652: $hash{'error'}='Bad data';
3653: return (\%hash, $string);
3654: }
3655: } else {
3656: $string =~ s/^(.*?)=//;
1.267 albertel 3657: $key=&unescape($1);
1.265 albertel 3658: }
3659: $string =~ s/^=//;
3660:
3661: #value
3662: my $value='';
3663: if($string =~ /^__HASH_REF__/) {
3664: ($value, $string)=&str2hashref($string);
3665: if(defined($value->{'error'})) {
3666: $hash{'error'}='Bad data';
3667: return (\%hash, $string);
3668: }
3669: } elsif($string =~ /^__ARRAY_REF__/) {
3670: ($value, $string)=&str2arrayref($string);
3671: if($value->[0] eq 'Array reference error') {
3672: $hash{'error'}='Bad data';
3673: return (\%hash, $string);
3674: }
3675: } else {
3676: $value=&get_scalar(\$string,'__END_HASH_REF__');
3677: }
3678: $string =~ s/^&//;
3679:
3680: $hash{$key}=$value;
1.204 albertel 3681: }
1.265 albertel 3682:
3683: $string =~ s/^__END_HASH_REF__//;
3684:
3685: return (\%hash, $string);
1.204 albertel 3686: }
3687:
3688: sub str2array {
1.265 albertel 3689: my ($string)=@_;
3690: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3691: return @$array;
3692: }
3693:
3694: sub str2arrayref {
1.204 albertel 3695: my ($string) = @_;
1.265 albertel 3696: my @array;
3697:
3698: if($string !~ /^__ARRAY_REF__/) {
3699: if (! ($string eq '' || !defined($string))) {
3700: $array[0]='Array reference error';
3701: }
3702: return (\@array, $string);
3703: }
3704:
3705: $string =~ s/^__ARRAY_REF__//;
3706:
3707: while($string !~ /^__END_ARRAY_REF__/) {
3708: my $value='';
3709: if($string =~ /^__HASH_REF__/) {
3710: ($value, $string)=&str2hashref($string);
3711: if(defined($value->{'error'})) {
3712: $array[0] ='Array reference error';
3713: return (\@array, $string);
3714: }
3715: } elsif($string =~ /^__ARRAY_REF__/) {
3716: ($value, $string)=&str2arrayref($string);
3717: if($value->[0] eq 'Array reference error') {
3718: $array[0] ='Array reference error';
3719: return (\@array, $string);
3720: }
3721: } else {
3722: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3723: }
3724: $string =~ s/^&//;
3725:
3726: push(@array, $value);
1.191 harris41 3727: }
1.265 albertel 3728:
3729: $string =~ s/^__END_ARRAY_REF__//;
3730:
3731: return (\@array, $string);
1.168 albertel 3732: }
3733:
1.167 albertel 3734: # -------------------------------------------------------------------Temp Store
3735:
1.168 albertel 3736: sub tmpreset {
3737: my ($symb,$namespace,$domain,$stuname) = @_;
3738: if (!$symb) {
3739: $symb=&symbread();
1.620 albertel 3740: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3741: }
3742: $symb=escape($symb);
3743:
1.620 albertel 3744: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3745: $namespace=~s/\//\_/g;
3746: $namespace=~s/\W//g;
3747:
1.620 albertel 3748: if (!$domain) { $domain=$env{'user.domain'}; }
3749: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3750: if ($domain eq 'public' && $stuname eq 'public') {
3751: $stuname=$ENV{'REMOTE_ADDR'};
3752: }
1.168 albertel 3753: my $path=$perlvar{'lonDaemons'}.'/tmp';
3754: my %hash;
3755: if (tie(%hash,'GDBM_File',
3756: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3757: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3758: foreach my $key (keys(%hash)) {
1.180 albertel 3759: if ($key=~ /:$symb/) {
1.168 albertel 3760: delete($hash{$key});
3761: }
3762: }
3763: }
3764: }
3765:
1.167 albertel 3766: sub tmpstore {
1.168 albertel 3767: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3768:
3769: if (!$symb) {
3770: $symb=&symbread();
1.620 albertel 3771: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3772: }
3773: $symb=escape($symb);
3774:
3775: if (!$namespace) {
3776: # I don't think we would ever want to store this for a course.
3777: # it seems this will only be used if we don't have a course.
1.620 albertel 3778: #$namespace=$env{'request.course.id'};
1.168 albertel 3779: #if (!$namespace) {
1.620 albertel 3780: $namespace=$env{'request.state'};
1.168 albertel 3781: #}
3782: }
3783: $namespace=~s/\//\_/g;
3784: $namespace=~s/\W//g;
1.620 albertel 3785: if (!$domain) { $domain=$env{'user.domain'}; }
3786: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3787: if ($domain eq 'public' && $stuname eq 'public') {
3788: $stuname=$ENV{'REMOTE_ADDR'};
3789: }
1.168 albertel 3790: my $now=time;
3791: my %hash;
3792: my $path=$perlvar{'lonDaemons'}.'/tmp';
3793: if (tie(%hash,'GDBM_File',
3794: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3795: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3796: $hash{"version:$symb"}++;
3797: my $version=$hash{"version:$symb"};
3798: my $allkeys='';
3799: foreach my $key (keys(%$storehash)) {
3800: $allkeys.=$key.':';
1.591 albertel 3801: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3802: }
3803: $hash{"$version:$symb:timestamp"}=$now;
3804: $allkeys.='timestamp';
3805: $hash{"$version:keys:$symb"}=$allkeys;
3806: if (untie(%hash)) {
3807: return 'ok';
3808: } else {
3809: return "error:$!";
3810: }
3811: } else {
3812: return "error:$!";
3813: }
3814: }
1.167 albertel 3815:
1.168 albertel 3816: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3817:
1.168 albertel 3818: sub tmprestore {
3819: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3820:
1.168 albertel 3821: if (!$symb) {
3822: $symb=&symbread();
1.620 albertel 3823: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3824: }
3825: $symb=escape($symb);
3826:
1.620 albertel 3827: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3828:
1.620 albertel 3829: if (!$domain) { $domain=$env{'user.domain'}; }
3830: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3831: if ($domain eq 'public' && $stuname eq 'public') {
3832: $stuname=$ENV{'REMOTE_ADDR'};
3833: }
1.168 albertel 3834: my %returnhash;
3835: $namespace=~s/\//\_/g;
3836: $namespace=~s/\W//g;
3837: my %hash;
3838: my $path=$perlvar{'lonDaemons'}.'/tmp';
3839: if (tie(%hash,'GDBM_File',
3840: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3841: &GDBM_READER(),0640)) {
1.168 albertel 3842: my $version=$hash{"version:$symb"};
3843: $returnhash{'version'}=$version;
3844: my $scope;
3845: for ($scope=1;$scope<=$version;$scope++) {
3846: my $vkeys=$hash{"$scope:keys:$symb"};
3847: my @keys=split(/:/,$vkeys);
3848: my $key;
3849: $returnhash{"$scope:keys"}=$vkeys;
3850: foreach $key (@keys) {
1.591 albertel 3851: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3852: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3853: }
3854: }
1.168 albertel 3855: if (!(untie(%hash))) {
3856: return "error:$!";
3857: }
3858: } else {
3859: return "error:$!";
3860: }
3861: return %returnhash;
1.167 albertel 3862: }
3863:
1.9 www 3864: # ----------------------------------------------------------------------- Store
3865:
3866: sub store {
1.124 www 3867: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3868: my $home='';
3869:
1.168 albertel 3870: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3871:
1.213 www 3872: $symb=&symbclean($symb);
1.122 albertel 3873: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3874:
1.620 albertel 3875: if (!$domain) { $domain=$env{'user.domain'}; }
3876: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3877:
3878: &devalidate($symb,$stuname,$domain);
1.109 www 3879:
3880: $symb=escape($symb);
1.187 www 3881: if (!$namespace) {
1.620 albertel 3882: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3883: return '';
3884: }
3885: }
1.620 albertel 3886: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3887:
3888: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3889: $$storehash{'host'}=$perlvar{'lonHostID'};
3890:
1.12 www 3891: my $namevalue='';
1.800 albertel 3892: foreach my $key (keys(%$storehash)) {
3893: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3894: }
1.12 www 3895: $namevalue=~s/\&$//;
1.187 www 3896: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3897: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3898: }
3899:
1.47 www 3900: # -------------------------------------------------------------- Critical Store
3901:
3902: sub cstore {
1.124 www 3903: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3904: my $home='';
3905:
1.168 albertel 3906: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3907:
1.213 www 3908: $symb=&symbclean($symb);
1.122 albertel 3909: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3910:
1.620 albertel 3911: if (!$domain) { $domain=$env{'user.domain'}; }
3912: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3913:
3914: &devalidate($symb,$stuname,$domain);
1.109 www 3915:
3916: $symb=escape($symb);
1.187 www 3917: if (!$namespace) {
1.620 albertel 3918: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3919: return '';
3920: }
3921: }
1.620 albertel 3922: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3923:
3924: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3925: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3926:
1.47 www 3927: my $namevalue='';
1.800 albertel 3928: foreach my $key (keys(%$storehash)) {
3929: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3930: }
1.47 www 3931: $namevalue=~s/\&$//;
1.187 www 3932: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3933: return critical
3934: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3935: }
3936:
1.9 www 3937: # --------------------------------------------------------------------- Restore
3938:
3939: sub restore {
1.124 www 3940: my ($symb,$namespace,$domain,$stuname) = @_;
3941: my $home='';
3942:
1.168 albertel 3943: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3944:
1.122 albertel 3945: if (!$symb) {
3946: unless ($symb=escape(&symbread())) { return ''; }
3947: } else {
1.213 www 3948: $symb=&escape(&symbclean($symb));
1.122 albertel 3949: }
1.188 www 3950: if (!$namespace) {
1.620 albertel 3951: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3952: return '';
3953: }
3954: }
1.620 albertel 3955: if (!$domain) { $domain=$env{'user.domain'}; }
3956: if (!$stuname) { $stuname=$env{'user.name'}; }
3957: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3958: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3959:
1.12 www 3960: my %returnhash=();
1.800 albertel 3961: foreach my $line (split(/\&/,$answer)) {
3962: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3963: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3964: }
1.75 www 3965: my $version;
3966: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3967: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3968: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3969: }
1.75 www 3970: }
1.13 www 3971: return %returnhash;
1.34 www 3972: }
3973:
3974: # ---------------------------------------------------------- Course Description
3975:
3976: sub coursedescription {
1.731 albertel 3977: my ($courseid,$args)=@_;
1.34 www 3978: $courseid=~s/^\///;
1.49 www 3979: $courseid=~s/\_/\//g;
1.34 www 3980: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3981: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3982: my $normalid=$cdomain.'_'.$cnum;
3983: # need to always cache even if we get errors otherwise we keep
3984: # trying and trying and trying to get the course description.
3985: my %envhash=();
3986: my %returnhash=();
1.731 albertel 3987:
3988: my $expiretime=600;
3989: if ($env{'request.course.id'} eq $normalid) {
3990: $expiretime=120;
3991: }
3992:
3993: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3994: if (!$args->{'freshen_cache'}
3995: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3996: foreach my $key (keys(%env)) {
3997: next if ($key !~ /^\Q$prefix\E(.*)/);
3998: my ($setting) = $1;
3999: $returnhash{$setting} = $env{$key};
4000: }
4001: return %returnhash;
4002: }
4003:
4004: # get the data agin
4005: if (!$args->{'one_time'}) {
4006: $envhash{'course.'.$normalid.'.last_cache'}=time;
4007: }
1.811 albertel 4008:
1.34 www 4009: if ($chome ne 'no_host') {
1.302 albertel 4010: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4011: if (!exists($returnhash{'con_lost'})) {
4012: $returnhash{'home'}= $chome;
4013: $returnhash{'domain'} = $cdomain;
4014: $returnhash{'num'} = $cnum;
1.741 raeburn 4015: if (!defined($returnhash{'type'})) {
4016: $returnhash{'type'} = 'Course';
4017: }
1.130 albertel 4018: while (my ($name,$value) = each %returnhash) {
1.53 www 4019: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4020: }
1.270 www 4021: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4022: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4023: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4024: $envhash{'course.'.$normalid.'.home'}=$chome;
4025: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4026: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4027: }
4028: }
1.731 albertel 4029: if (!$args->{'one_time'}) {
1.949 raeburn 4030: &appenv(\%envhash);
1.731 albertel 4031: }
1.302 albertel 4032: return %returnhash;
1.461 www 4033: }
4034:
1.1080 raeburn 4035: sub update_released_required {
4036: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4037: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4038: $cid = $env{'request.course.id'};
4039: $cdom = $env{'course.'.$cid.'.domain'};
4040: $cnum = $env{'course.'.$cid.'.num'};
4041: $chome = $env{'course.'.$cid.'.home'};
4042: }
4043: if ($needsrelease) {
4044: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4045: my $needsupdate;
4046: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4047: $needsupdate = 1;
4048: } else {
4049: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4050: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4051: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4052: $needsupdate = 1;
4053: }
4054: }
4055: if ($needsupdate) {
4056: my %needshash = (
4057: 'internal.releaserequired' => $needsrelease,
4058: );
4059: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4060: if ($putresult eq 'ok') {
4061: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4062: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4063: if (ref($crsinfo{$cid}) eq 'HASH') {
4064: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4065: &courseidput($cdom,\%crsinfo,$chome,'notime');
4066: }
4067: }
4068: }
4069: }
4070: return;
4071: }
4072:
1.461 www 4073: # -------------------------------------------------See if a user is privileged
4074:
4075: sub privileged {
4076: my ($username,$domain)=@_;
4077: my $rolesdump=&reply("dump:$domain:$username:roles",
4078: &homeserver($username,$domain));
1.1033 raeburn 4079: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4080: ($rolesdump =~ /^error:/)) {
4081: return 0;
4082: }
1.461 www 4083: my $now=time;
4084: if ($rolesdump ne '') {
1.800 albertel 4085: foreach my $entry (split(/&/,$rolesdump)) {
4086: if ($entry!~/^rolesdef_/) {
4087: my ($area,$role)=split(/=/,$entry);
1.461 www 4088: $area=~s/\_\w\w$//;
4089: my ($trole,$tend,$tstart)=split(/_/,$role);
4090: if (($trole eq 'dc') || ($trole eq 'su')) {
4091: my $active=1;
4092: if ($tend) {
4093: if ($tend<$now) { $active=0; }
4094: }
4095: if ($tstart) {
4096: if ($tstart>$now) { $active=0; }
4097: }
4098: if ($active) { return 1; }
4099: }
4100: }
4101: }
4102: }
4103: return 0;
1.9 www 4104: }
1.1 albertel 4105:
1.103 harris41 4106: # -------------------------------------------------------- Get user privileges
1.11 www 4107:
4108: sub rolesinit {
4109: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4110: my $now=time;
4111: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4112: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4113: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4114: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4115: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4116: return \%userroles;
4117: }
1.11 www 4118: my %allroles=();
1.678 raeburn 4119: my %allgroups=();
1.11 www 4120:
4121: if ($rolesdump ne '') {
1.800 albertel 4122: foreach my $entry (split(/&/,$rolesdump)) {
4123: if ($entry!~/^rolesdef_/) {
4124: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4125: $area=~s/\_\w\w$//;
1.678 raeburn 4126: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4127: if ($role=~/^cr/) {
1.807 albertel 4128: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4129: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4130: ($tend,$tstart)=split('_',$trest);
4131: } else {
4132: $trole=$role;
4133: }
1.678 raeburn 4134: } elsif ($role =~ m|^gr/|) {
4135: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4136: next if ($tstart eq '-1');
1.678 raeburn 4137: ($trole,$group_privs) = split(/\//,$trole);
4138: $group_privs = &unescape($group_privs);
1.587 albertel 4139: } else {
4140: ($trole,$tend,$tstart)=split(/_/,$role);
4141: }
1.743 albertel 4142: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4143: $username);
4144: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4145: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4146: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4147: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4148: my $spec=$trole.'.'.$area;
4149: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4150: if ($trole =~ /^cr\//) {
1.567 raeburn 4151: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4152: } elsif ($trole eq 'gr') {
4153: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4154: } else {
1.567 raeburn 4155: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4156: }
1.12 www 4157: }
1.662 raeburn 4158: }
1.191 harris41 4159: }
1.743 albertel 4160: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4161: $userroles{'user.adv'} = $adv;
4162: $userroles{'user.author'} = $author;
1.620 albertel 4163: $env{'user.adv'}=$adv;
1.11 www 4164: }
1.743 albertel 4165: return \%userroles;
1.11 www 4166: }
4167:
1.567 raeburn 4168: sub set_arearole {
4169: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4170: # log the associated role with the area
4171: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4172: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4173: }
4174:
4175: sub custom_roleprivs {
4176: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4177: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4178: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4179: if (&hostname($homsvr) ne '') {
1.567 raeburn 4180: my ($rdummy,$roledef)=
4181: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4182: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4183: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4184: if (defined($syspriv)) {
1.1043 raeburn 4185: if ($trest =~ /^$match_community$/) {
4186: $syspriv =~ s/bre\&S//;
4187: }
1.567 raeburn 4188: $$allroles{'cm./'}.=':'.$syspriv;
4189: $$allroles{$spec.'./'}.=':'.$syspriv;
4190: }
4191: if ($tdomain ne '') {
4192: if (defined($dompriv)) {
4193: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4194: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4195: }
4196: if (($trest ne '') && (defined($coursepriv))) {
4197: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4198: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4199: }
4200: }
4201: }
4202: }
4203: }
4204:
1.678 raeburn 4205: sub group_roleprivs {
4206: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4207: my $access = 1;
4208: my $now = time;
4209: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4210: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4211: if ($access) {
1.811 albertel 4212: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4213: $$allgroups{$course}{$group} .=':'.$group_privs;
4214: }
4215: }
1.567 raeburn 4216:
4217: sub standard_roleprivs {
4218: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4219: if (defined($pr{$trole.':s'})) {
4220: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4221: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4222: }
4223: if ($tdomain ne '') {
4224: if (defined($pr{$trole.':d'})) {
4225: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4226: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4227: }
4228: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4229: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4230: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4231: }
4232: }
4233: }
4234:
4235: sub set_userprivs {
1.1064 raeburn 4236: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4237: my $author=0;
4238: my $adv=0;
1.678 raeburn 4239: my %grouproles = ();
4240: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4241: my @groupkeys;
1.1000 raeburn 4242: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4243: push(@groupkeys,$role);
4244: }
4245: if (ref($groups_roles) eq 'HASH') {
4246: foreach my $key (keys(%{$groups_roles})) {
4247: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4248: push(@groupkeys,$key);
4249: }
4250: }
4251: }
4252: if (@groupkeys > 0) {
4253: foreach my $role (@groupkeys) {
4254: my ($trole,$area,$sec,$extendedarea);
4255: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4256: $trole = $1;
4257: $area = $2;
4258: $sec = $3;
4259: $extendedarea = $area.$sec;
4260: if (exists($$allgroups{$area})) {
4261: foreach my $group (keys(%{$$allgroups{$area}})) {
4262: my $spec = $trole.'.'.$extendedarea;
4263: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4264: $$allgroups{$area}{$group};
1.1064 raeburn 4265: }
1.678 raeburn 4266: }
4267: }
4268: }
4269: }
4270: }
1.800 albertel 4271: foreach my $group (keys(%grouproles)) {
4272: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4273: }
1.800 albertel 4274: foreach my $role (keys(%{$allroles})) {
4275: my %thesepriv;
1.941 raeburn 4276: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4277: foreach my $item (split(/:/,$$allroles{$role})) {
4278: if ($item ne '') {
4279: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4280: if ($restrictions eq '') {
4281: $thesepriv{$privilege}='F';
4282: } elsif ($thesepriv{$privilege} ne 'F') {
4283: $thesepriv{$privilege}.=$restrictions;
4284: }
4285: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4286: }
4287: }
4288: my $thesestr='';
1.1104 raeburn 4289: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4290: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4291: }
4292: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4293: }
4294: return ($author,$adv);
4295: }
4296:
1.994 raeburn 4297: sub role_status {
1.1104 raeburn 4298: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4299: my @pwhere = ();
4300: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4301: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4302: unless (!defined($$role) || $$role eq '') {
4303: $$where=join('.',@pwhere);
4304: $$trolecode=$$role.'.'.$$where;
4305: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4306: $$tstatus='is';
1.1104 raeburn 4307: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4308: $$tstatus='future';
1.1034 raeburn 4309: if ($$tstart<$now) {
4310: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4311: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4312: my (%allroles,%allgroups,$group_privs,
4313: %groups_roles,@rolecodes);
1.1002 raeburn 4314: my %userroles = (
4315: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4316: );
1.1064 raeburn 4317: @rolecodes = ('cm');
1.1002 raeburn 4318: my $spec=$$role.'.'.$$where;
4319: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4320: if ($$role =~ /^cr\//) {
4321: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4322: push(@rolecodes,'cr');
1.1002 raeburn 4323: } elsif ($$role eq 'gr') {
1.1064 raeburn 4324: push(@rolecodes,$$role);
1.1002 raeburn 4325: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4326: $env{'user.name'});
1.1064 raeburn 4327: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4328: (undef,my $group_privs) = split(/\//,$trole);
4329: $group_privs = &unescape($group_privs);
4330: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4331: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104 raeburn 4332: &get_groups_roles($tdomain,$trest,
4333: \%course_roles,\@rolecodes,
4334: \%groups_roles);
1.1002 raeburn 4335: } else {
1.1064 raeburn 4336: push(@rolecodes,$$role);
1.1002 raeburn 4337: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4338: }
1.1064 raeburn 4339: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4340: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4341: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4342: }
4343: }
1.1034 raeburn 4344: $$tstatus = 'is';
1.1002 raeburn 4345: }
1.994 raeburn 4346: }
4347: if ($$tend) {
1.1104 raeburn 4348: if ($$tend<$update) {
1.994 raeburn 4349: $$tstatus='expired';
4350: } elsif ($$tend<$now) {
4351: $$tstatus='will_not';
4352: }
4353: }
4354: }
4355: }
4356: }
4357:
1.1104 raeburn 4358: sub get_groups_roles {
4359: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4360: return unless((ref($cdom_courseroles) eq 'HASH') &&
4361: (ref($rolecodes) eq 'ARRAY') &&
4362: (ref($groups_roles) eq 'HASH'));
4363: if (keys(%{$cdom_courseroles}) > 0) {
4364: my ($cnum) = ($rest =~ /^($match_courseid)/);
4365: if ($cdom ne '' && $cnum ne '') {
4366: foreach my $key (keys(%{$cdom_courseroles})) {
4367: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4368: my $crsrole = $1;
4369: my $crssec = $2;
4370: if ($crsrole =~ /^cr/) {
4371: unless (grep(/^cr$/,@{$rolecodes})) {
4372: push(@{$rolecodes},'cr');
4373: }
4374: } else {
4375: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4376: push(@{$rolecodes},$crsrole);
4377: }
4378: }
4379: my $rolekey = "$crsrole./$cdom/$cnum";
4380: if ($crssec ne '') {
4381: $rolekey .= "/$crssec";
4382: }
4383: $rolekey .= './';
4384: $groups_roles->{$rolekey} = $rolecodes;
4385: }
4386: }
4387: }
4388: }
4389: return;
4390: }
4391:
4392: sub delete_env_groupprivs {
4393: my ($where,$courseroles,$possroles) = @_;
4394: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4395: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4396: unless (ref($courseroles->{$udom}) eq 'HASH') {
4397: %{$courseroles->{$udom}} =
4398: &get_my_roles('','','userroles',['active'],
4399: $possroles,[$udom],1);
4400: }
4401: if (ref($courseroles->{$udom}) eq 'HASH') {
4402: foreach my $item (keys(%{$courseroles->{$udom}})) {
4403: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4404: my $area = '/'.$cdom.'/'.$cnum;
4405: my $privkey = "user.priv.$crsrole.$area";
4406: if ($crssec ne '') {
4407: $privkey .= '/'.$crssec;
4408: }
4409: $privkey .= ".$area/$group";
4410: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4411: }
4412: }
4413: return;
4414: }
4415:
1.994 raeburn 4416: sub check_adhoc_privs {
1.1104 raeburn 4417: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4418: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4419: if ($env{$cckey}) {
4420: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4421: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4422: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4423: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4424: }
4425: } else {
1.1088 raeburn 4426: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4427: }
4428: }
4429:
4430: sub set_adhoc_privileges {
4431: # role can be cc or ca
1.1088 raeburn 4432: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4433: my $area = '/'.$dcdom.'/'.$pickedcourse;
4434: my $spec = $role.'.'.$area;
4435: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4436: $env{'user.name'});
4437: my %ccrole = ();
4438: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4439: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4440: &appenv(\%userroles,[$role,'cm']);
4441: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4442: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4443: &appenv( {'request.role' => $spec,
4444: 'request.role.domain' => $dcdom,
4445: 'request.course.sec' => ''
4446: }
4447: );
4448: my $tadv=0;
4449: if (&allowed('adv') eq 'F') { $tadv=1; }
4450: &appenv({'request.role.adv' => $tadv});
4451: }
1.994 raeburn 4452: }
4453:
1.12 www 4454: # --------------------------------------------------------------- get interface
4455:
4456: sub get {
1.131 albertel 4457: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4458: my $items='';
1.800 albertel 4459: foreach my $item (@$storearr) {
4460: $items.=&escape($item).'&';
1.191 harris41 4461: }
1.12 www 4462: $items=~s/\&$//;
1.620 albertel 4463: if (!$udomain) { $udomain=$env{'user.domain'}; }
4464: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4465: my $uhome=&homeserver($uname,$udomain);
4466:
1.133 albertel 4467: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4468: my @pairs=split(/\&/,$rep);
1.273 albertel 4469: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4470: return @pairs;
4471: }
1.15 www 4472: my %returnhash=();
1.42 www 4473: my $i=0;
1.800 albertel 4474: foreach my $item (@$storearr) {
4475: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4476: $i++;
1.191 harris41 4477: }
1.15 www 4478: return %returnhash;
1.27 www 4479: }
4480:
4481: # --------------------------------------------------------------- del interface
4482:
4483: sub del {
1.133 albertel 4484: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4485: my $items='';
1.800 albertel 4486: foreach my $item (@$storearr) {
4487: $items.=&escape($item).'&';
1.191 harris41 4488: }
1.984 neumanie 4489:
1.27 www 4490: $items=~s/\&$//;
1.620 albertel 4491: if (!$udomain) { $udomain=$env{'user.domain'}; }
4492: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4493: my $uhome=&homeserver($uname,$udomain);
4494: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4495: }
4496:
4497: # -------------------------------------------------------------- dump interface
4498:
4499: sub dump {
1.1086 raeburn 4500: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4501: if (!$udomain) { $udomain=$env{'user.domain'}; }
4502: if (!$uname) { $uname=$env{'user.name'}; }
4503: my $uhome=&homeserver($uname,$udomain);
4504: if ($regexp) {
4505: $regexp=&escape($regexp);
4506: } else {
4507: $regexp='.';
4508: }
1.1086 raeburn 4509: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4510: my @pairs=split(/\&/,$rep);
4511: my %returnhash=();
1.1098 foxr 4512: if (!($rep =~ /^error/ )) {
4513: foreach my $item (@pairs) {
4514: my ($key,$value)=split(/=/,$item,2);
4515: $key = &unescape($key);
4516: next if ($key =~ /^error: 2 /);
4517: $returnhash{$key}=&thaw_unescape($value);
4518: }
1.755 albertel 4519: }
4520: return %returnhash;
1.407 www 4521: }
4522:
1.1098 foxr 4523:
1.717 albertel 4524: # --------------------------------------------------------- dumpstore interface
4525:
4526: sub dumpstore {
4527: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 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: }
4536: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4537: my @pairs=split(/\&/,$rep);
4538: my %returnhash=();
4539: foreach my $item (@pairs) {
4540: my ($key,$value)=split(/=/,$item,2);
4541: next if ($key =~ /^error: 2 /);
4542: $returnhash{$key}=&thaw_unescape($value);
4543: }
4544: return %returnhash;
1.717 albertel 4545: }
4546:
1.407 www 4547: # -------------------------------------------------------------- keys interface
4548:
4549: sub getkeys {
4550: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4551: if (!$udomain) { $udomain=$env{'user.domain'}; }
4552: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4553: my $uhome=&homeserver($uname,$udomain);
4554: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4555: my @keyarray=();
1.800 albertel 4556: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4557: next if ($key =~ /^error: 2 /);
1.800 albertel 4558: push(@keyarray,&unescape($key));
1.407 www 4559: }
4560: return @keyarray;
1.318 matthew 4561: }
4562:
1.319 matthew 4563: # --------------------------------------------------------------- currentdump
4564: sub currentdump {
1.328 matthew 4565: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4566: $courseid = $env{'request.course.id'} if (! defined($courseid));
4567: $sdom = $env{'user.domain'} if (! defined($sdom));
4568: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4569: my $uhome = &homeserver($sname,$sdom);
4570: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4571: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4572: #
1.318 matthew 4573: my %returnhash=();
1.319 matthew 4574: #
4575: if ($rep eq "unknown_cmd") {
4576: # an old lond will not know currentdump
4577: # Do a dump and make it look like a currentdump
1.822 albertel 4578: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4579: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4580: my %hash = @tmp;
4581: @tmp=();
1.424 matthew 4582: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4583: } else {
4584: my @pairs=split(/\&/,$rep);
1.800 albertel 4585: foreach my $pair (@pairs) {
4586: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4587: my ($symb,$param) = split(/:/,$key);
4588: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4589: &thaw_unescape($value);
1.319 matthew 4590: }
1.191 harris41 4591: }
1.12 www 4592: return %returnhash;
1.424 matthew 4593: }
4594:
4595: sub convert_dump_to_currentdump{
4596: my %hash = %{shift()};
4597: my %returnhash;
4598: # Code ripped from lond, essentially. The only difference
4599: # here is the unescaping done by lonnet::dump(). Conceivably
4600: # we might run in to problems with parameter names =~ /^v\./
4601: while (my ($key,$value) = each(%hash)) {
4602: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4603: $symb = &unescape($symb);
4604: $param = &unescape($param);
1.424 matthew 4605: next if ($v eq 'version' || $symb eq 'keys');
4606: next if (exists($returnhash{$symb}) &&
4607: exists($returnhash{$symb}->{$param}) &&
4608: $returnhash{$symb}->{'v.'.$param} > $v);
4609: $returnhash{$symb}->{$param}=$value;
4610: $returnhash{$symb}->{'v.'.$param}=$v;
4611: }
4612: #
4613: # Remove all of the keys in the hashes which keep track of
4614: # the version of the parameter.
4615: while (my ($symb,$param_hash) = each(%returnhash)) {
4616: # use a foreach because we are going to delete from the hash.
4617: foreach my $key (keys(%$param_hash)) {
4618: delete($param_hash->{$key}) if ($key =~ /^v\./);
4619: }
4620: }
4621: return \%returnhash;
1.12 www 4622: }
4623:
1.627 albertel 4624: # ------------------------------------------------------ critical inc interface
4625:
4626: sub cinc {
4627: return &inc(@_,'critical');
4628: }
4629:
1.449 matthew 4630: # --------------------------------------------------------------- inc interface
4631:
4632: sub inc {
1.627 albertel 4633: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4634: if (!$udomain) { $udomain=$env{'user.domain'}; }
4635: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4636: my $uhome=&homeserver($uname,$udomain);
4637: my $items='';
4638: if (! ref($store)) {
4639: # got a single value, so use that instead
4640: $items = &escape($store).'=&';
4641: } elsif (ref($store) eq 'SCALAR') {
4642: $items = &escape($$store).'=&';
4643: } elsif (ref($store) eq 'ARRAY') {
4644: $items = join('=&',map {&escape($_);} @{$store});
4645: } elsif (ref($store) eq 'HASH') {
4646: while (my($key,$value) = each(%{$store})) {
4647: $items.= &escape($key).'='.&escape($value).'&';
4648: }
4649: }
4650: $items=~s/\&$//;
1.627 albertel 4651: if ($critical) {
4652: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4653: } else {
4654: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4655: }
1.449 matthew 4656: }
4657:
1.12 www 4658: # --------------------------------------------------------------- put interface
4659:
4660: sub put {
1.134 albertel 4661: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4662: if (!$udomain) { $udomain=$env{'user.domain'}; }
4663: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4664: my $uhome=&homeserver($uname,$udomain);
1.12 www 4665: my $items='';
1.800 albertel 4666: foreach my $item (keys(%$storehash)) {
4667: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4668: }
1.12 www 4669: $items=~s/\&$//;
1.134 albertel 4670: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4671: }
4672:
1.631 albertel 4673: # ------------------------------------------------------------ newput interface
4674:
4675: sub newput {
4676: my ($namespace,$storehash,$udomain,$uname)=@_;
4677: if (!$udomain) { $udomain=$env{'user.domain'}; }
4678: if (!$uname) { $uname=$env{'user.name'}; }
4679: my $uhome=&homeserver($uname,$udomain);
4680: my $items='';
4681: foreach my $key (keys(%$storehash)) {
4682: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4683: }
4684: $items=~s/\&$//;
4685: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4686: }
4687:
4688: # --------------------------------------------------------- putstore interface
4689:
1.524 raeburn 4690: sub putstore {
1.715 albertel 4691: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4692: if (!$udomain) { $udomain=$env{'user.domain'}; }
4693: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4694: my $uhome=&homeserver($uname,$udomain);
4695: my $items='';
1.715 albertel 4696: foreach my $key (keys(%$storehash)) {
4697: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4698: }
1.715 albertel 4699: $items=~s/\&$//;
1.716 albertel 4700: my $esc_symb=&escape($symb);
4701: my $esc_v=&escape($version);
1.715 albertel 4702: my $reply =
1.716 albertel 4703: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4704: $uhome);
4705: if ($reply eq 'unknown_cmd') {
1.716 albertel 4706: # gfall back to way things use to be done
1.715 albertel 4707: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4708: $uname);
1.524 raeburn 4709: }
1.715 albertel 4710: return $reply;
4711: }
4712:
4713: sub old_putstore {
1.716 albertel 4714: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4715: if (!$udomain) { $udomain=$env{'user.domain'}; }
4716: if (!$uname) { $uname=$env{'user.name'}; }
4717: my $uhome=&homeserver($uname,$udomain);
4718: my %newstorehash;
1.800 albertel 4719: foreach my $item (keys(%$storehash)) {
4720: my $key = $version.':'.&escape($symb).':'.$item;
4721: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4722: }
4723: my $items='';
4724: my %allitems = ();
1.800 albertel 4725: foreach my $item (keys(%newstorehash)) {
4726: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4727: my $key = $1.':keys:'.$2;
4728: $allitems{$key} .= $3.':';
4729: }
1.800 albertel 4730: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4731: }
1.800 albertel 4732: foreach my $item (keys(%allitems)) {
4733: $allitems{$item} =~ s/\:$//;
4734: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4735: }
4736: $items=~s/\&$//;
4737: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4738: }
4739:
1.47 www 4740: # ------------------------------------------------------ critical put interface
4741:
4742: sub cput {
1.134 albertel 4743: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4744: if (!$udomain) { $udomain=$env{'user.domain'}; }
4745: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4746: my $uhome=&homeserver($uname,$udomain);
1.47 www 4747: my $items='';
1.800 albertel 4748: foreach my $item (keys(%$storehash)) {
4749: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4750: }
1.47 www 4751: $items=~s/\&$//;
1.134 albertel 4752: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4753: }
4754:
4755: # -------------------------------------------------------------- eget interface
4756:
4757: sub eget {
1.133 albertel 4758: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4759: my $items='';
1.800 albertel 4760: foreach my $item (@$storearr) {
4761: $items.=&escape($item).'&';
1.191 harris41 4762: }
1.12 www 4763: $items=~s/\&$//;
1.620 albertel 4764: if (!$udomain) { $udomain=$env{'user.domain'}; }
4765: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4766: my $uhome=&homeserver($uname,$udomain);
4767: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4768: my @pairs=split(/\&/,$rep);
4769: my %returnhash=();
1.42 www 4770: my $i=0;
1.800 albertel 4771: foreach my $item (@$storearr) {
4772: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4773: $i++;
1.191 harris41 4774: }
1.12 www 4775: return %returnhash;
4776: }
4777:
1.667 albertel 4778: # ------------------------------------------------------------ tmpput interface
4779: sub tmpput {
1.802 raeburn 4780: my ($storehash,$server,$context)=@_;
1.667 albertel 4781: my $items='';
1.800 albertel 4782: foreach my $item (keys(%$storehash)) {
4783: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4784: }
4785: $items=~s/\&$//;
1.802 raeburn 4786: if (defined($context)) {
4787: $items .= ':'.&escape($context);
4788: }
1.667 albertel 4789: return &reply("tmpput:$items",$server);
4790: }
4791:
4792: # ------------------------------------------------------------ tmpget interface
4793: sub tmpget {
1.688 albertel 4794: my ($token,$server)=@_;
4795: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4796: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4797: my %returnhash;
4798: foreach my $item (split(/\&/,$rep)) {
4799: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4800: next if ($key =~ /^error: 2 /);
1.667 albertel 4801: $returnhash{&unescape($key)}=&thaw_unescape($value);
4802: }
4803: return %returnhash;
4804: }
4805:
1.688 albertel 4806: # ------------------------------------------------------------ tmpget interface
4807: sub tmpdel {
4808: my ($token,$server)=@_;
4809: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4810: return &reply("tmpdel:$token",$server);
4811: }
4812:
1.765 albertel 4813: # -------------------------------------------------- portfolio access checking
4814:
4815: sub portfolio_access {
1.766 albertel 4816: my ($requrl) = @_;
1.765 albertel 4817: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4818: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4819: if ($result) {
4820: my %setters;
4821: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4822: my ($startblock,$endblock) =
4823: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4824: if ($startblock && $endblock) {
4825: return 'B';
4826: }
4827: } else {
4828: my ($startblock,$endblock) =
4829: &Apache::loncommon::blockcheck(\%setters,'port');
4830: if ($startblock && $endblock) {
4831: return 'B';
4832: }
4833: }
4834: }
1.765 albertel 4835: if ($result eq 'ok') {
1.766 albertel 4836: return 'F';
1.765 albertel 4837: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4838: return 'A';
1.765 albertel 4839: }
1.766 albertel 4840: return '';
1.765 albertel 4841: }
4842:
4843: sub get_portfolio_access {
1.767 albertel 4844: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4845:
4846: if (!ref($access_hash)) {
4847: my $current_perms = &get_portfile_permissions($udom,$unum);
4848: my %access_controls = &get_access_controls($current_perms,$group,
4849: $file_name);
4850: $access_hash = $access_controls{$file_name};
4851: }
4852:
1.765 albertel 4853: my ($public,$guest,@domains,@users,@courses,@groups);
4854: my $now = time;
4855: if (ref($access_hash) eq 'HASH') {
4856: foreach my $key (keys(%{$access_hash})) {
4857: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4858: if ($start > $now) {
4859: next;
4860: }
4861: if ($end && $end<$now) {
4862: next;
4863: }
4864: if ($scope eq 'public') {
4865: $public = $key;
4866: last;
4867: } elsif ($scope eq 'guest') {
4868: $guest = $key;
4869: } elsif ($scope eq 'domains') {
4870: push(@domains,$key);
4871: } elsif ($scope eq 'users') {
4872: push(@users,$key);
4873: } elsif ($scope eq 'course') {
4874: push(@courses,$key);
4875: } elsif ($scope eq 'group') {
4876: push(@groups,$key);
4877: }
4878: }
4879: if ($public) {
4880: return 'ok';
4881: }
4882: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4883: if ($guest) {
4884: return $guest;
4885: }
4886: } else {
4887: if (@domains > 0) {
4888: foreach my $domkey (@domains) {
4889: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4890: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4891: return 'ok';
4892: }
4893: }
4894: }
4895: }
4896: if (@users > 0) {
4897: foreach my $userkey (@users) {
1.865 raeburn 4898: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4899: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4900: if (ref($item) eq 'HASH') {
4901: if (($item->{'uname'} eq $env{'user.name'}) &&
4902: ($item->{'udom'} eq $env{'user.domain'})) {
4903: return 'ok';
4904: }
4905: }
4906: }
4907: }
1.765 albertel 4908: }
4909: }
4910: my %roleshash;
4911: my @courses_and_groups = @courses;
4912: push(@courses_and_groups,@groups);
4913: if (@courses_and_groups > 0) {
4914: my (%allgroups,%allroles);
4915: my ($start,$end,$role,$sec,$group);
4916: foreach my $envkey (%env) {
1.1060 raeburn 4917: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4918: my $cid = $2.'_'.$3;
4919: if ($1 eq 'gr') {
4920: $group = $4;
4921: $allgroups{$cid}{$group} = $env{$envkey};
4922: } else {
4923: if ($4 eq '') {
4924: $sec = 'none';
4925: } else {
4926: $sec = $4;
4927: }
4928: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4929: }
1.811 albertel 4930: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4931: my $cid = $2.'_'.$3;
4932: if ($4 eq '') {
4933: $sec = 'none';
4934: } else {
4935: $sec = $4;
4936: }
4937: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4938: }
4939: }
4940: if (keys(%allroles) == 0) {
4941: return;
4942: }
4943: foreach my $key (@courses_and_groups) {
4944: my %content = %{$$access_hash{$key}};
4945: my $cnum = $content{'number'};
4946: my $cdom = $content{'domain'};
4947: my $cid = $cdom.'_'.$cnum;
4948: if (!exists($allroles{$cid})) {
4949: next;
4950: }
4951: foreach my $role_id (keys(%{$content{'roles'}})) {
4952: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4953: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4954: my @status = @{$content{'roles'}{$role_id}{'access'}};
4955: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4956: foreach my $role (keys(%{$allroles{$cid}})) {
4957: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4958: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4959: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4960: if (grep/^all$/,@sections) {
4961: return 'ok';
4962: } else {
4963: if (grep/^$sec$/,@sections) {
4964: return 'ok';
4965: }
4966: }
4967: }
4968: }
4969: if (keys(%{$allgroups{$cid}}) == 0) {
4970: if (grep/^none$/,@groups) {
4971: return 'ok';
4972: }
4973: } else {
4974: if (grep/^all$/,@groups) {
4975: return 'ok';
4976: }
4977: foreach my $group (keys(%{$allgroups{$cid}})) {
4978: if (grep/^$group$/,@groups) {
4979: return 'ok';
4980: }
4981: }
4982: }
4983: }
4984: }
4985: }
4986: }
4987: }
4988: if ($guest) {
4989: return $guest;
4990: }
4991: }
4992: }
4993: return;
4994: }
4995:
4996: sub course_group_datechecker {
4997: my ($dates,$now,$status) = @_;
4998: my ($start,$end) = split(/\./,$dates);
4999: if (!$start && !$end) {
5000: return 'ok';
5001: }
5002: if (grep/^active$/,@{$status}) {
5003: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5004: return 'ok';
5005: }
5006: }
5007: if (grep/^previous$/,@{$status}) {
5008: if ($end > $now ) {
5009: return 'ok';
5010: }
5011: }
5012: if (grep/^future$/,@{$status}) {
5013: if ($start > $now) {
5014: return 'ok';
5015: }
5016: }
5017: return;
5018: }
5019:
5020: sub parse_portfolio_url {
5021: my ($url) = @_;
5022:
5023: my ($type,$udom,$unum,$group,$file_name);
5024:
1.823 albertel 5025: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5026: $type = 1;
5027: $udom = $1;
5028: $unum = $2;
5029: $file_name = $3;
1.823 albertel 5030: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5031: $type = 2;
5032: $udom = $1;
5033: $unum = $2;
5034: $group = $3;
5035: $file_name = $3.'/'.$4;
5036: }
5037: if (wantarray) {
5038: return ($type,$udom,$unum,$file_name,$group);
5039: }
5040: return $type;
5041: }
5042:
5043: sub is_portfolio_url {
5044: my ($url) = @_;
5045: return scalar(&parse_portfolio_url($url));
5046: }
5047:
1.798 raeburn 5048: sub is_portfolio_file {
5049: my ($file) = @_;
1.820 raeburn 5050: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5051: return 1;
5052: }
5053: return;
5054: }
5055:
1.976 raeburn 5056: sub usertools_access {
1.1084 raeburn 5057: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5058: my ($access,%tools);
5059: if ($context eq '') {
5060: $context = 'tools';
5061: }
5062: if ($context eq 'requestcourses') {
5063: %tools = (
5064: official => 1,
5065: unofficial => 1,
1.1006 raeburn 5066: community => 1,
1.985 raeburn 5067: );
5068: } else {
5069: %tools = (
5070: aboutme => 1,
5071: blog => 1,
5072: portfolio => 1,
5073: );
5074: }
1.976 raeburn 5075: return if (!defined($tools{$tool}));
5076:
5077: if ((!defined($udom)) || (!defined($uname))) {
5078: $udom = $env{'user.domain'};
5079: $uname = $env{'user.name'};
5080: }
5081:
1.978 raeburn 5082: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5083: if ($action ne 'reload') {
1.985 raeburn 5084: if ($context eq 'requestcourses') {
5085: return $env{'environment.canrequest.'.$tool};
5086: } else {
5087: return $env{'environment.availabletools.'.$tool};
5088: }
5089: }
1.976 raeburn 5090: }
5091:
5092: my ($toolstatus,$inststatus);
5093:
1.985 raeburn 5094: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5095: ($action ne 'reload')) {
5096: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5097: $inststatus = $env{'environment.inststatus'};
5098: } else {
1.1084 raeburn 5099: if (ref($userenvref) eq 'HASH') {
5100: $toolstatus = $userenvref->{$context.'.'.$tool};
5101: $inststatus = $userenvref->{'inststatus'};
5102: } else {
5103: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5104: $toolstatus = $userenv{$context.'.'.$tool};
5105: $inststatus = $userenv{'inststatus'};
5106: }
1.976 raeburn 5107: }
5108:
5109: if ($toolstatus ne '') {
5110: if ($toolstatus) {
5111: $access = 1;
5112: } else {
5113: $access = 0;
5114: }
5115: return $access;
5116: }
5117:
1.1084 raeburn 5118: my ($is_adv,%domdef);
5119: if (ref($is_advref) eq 'HASH') {
5120: $is_adv = $is_advref->{'is_adv'};
5121: } else {
5122: $is_adv = &is_advanced_user($udom,$uname);
5123: }
5124: if (ref($domdefref) eq 'HASH') {
5125: %domdef = %{$domdefref};
5126: } else {
5127: %domdef = &get_domain_defaults($udom);
5128: }
1.976 raeburn 5129: if (ref($domdef{$tool}) eq 'HASH') {
5130: if ($is_adv) {
5131: if ($domdef{$tool}{'_LC_adv'} ne '') {
5132: if ($domdef{$tool}{'_LC_adv'}) {
5133: $access = 1;
5134: } else {
5135: $access = 0;
5136: }
5137: return $access;
5138: }
5139: }
5140: if ($inststatus ne '') {
5141: my ($hasaccess,$hasnoaccess);
5142: foreach my $affiliation (split(/:/,$inststatus)) {
5143: if ($domdef{$tool}{$affiliation} ne '') {
5144: if ($domdef{$tool}{$affiliation}) {
5145: $hasaccess = 1;
5146: } else {
5147: $hasnoaccess = 1;
5148: }
5149: }
5150: }
5151: if ($hasaccess || $hasnoaccess) {
5152: if ($hasaccess) {
5153: $access = 1;
5154: } elsif ($hasnoaccess) {
5155: $access = 0;
5156: }
5157: return $access;
5158: }
5159: } else {
5160: if ($domdef{$tool}{'default'} ne '') {
5161: if ($domdef{$tool}{'default'}) {
5162: $access = 1;
5163: } elsif ($domdef{$tool}{'default'} == 0) {
5164: $access = 0;
5165: }
5166: return $access;
5167: }
5168: }
5169: } else {
1.985 raeburn 5170: if ($context eq 'tools') {
5171: $access = 1;
5172: } else {
5173: $access = 0;
5174: }
1.976 raeburn 5175: return $access;
5176: }
5177: }
5178:
1.1050 raeburn 5179: sub is_course_owner {
5180: my ($cdom,$cnum,$udom,$uname) = @_;
5181: if (($udom eq '') || ($uname eq '')) {
5182: $udom = $env{'user.domain'};
5183: $uname = $env{'user.name'};
5184: }
5185: unless (($udom eq '') || ($uname eq '')) {
5186: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5187: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5188: return 1;
5189: } else {
5190: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5191: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5192: return 1;
5193: }
5194: }
5195: }
5196: }
5197: return;
5198: }
5199:
1.976 raeburn 5200: sub is_advanced_user {
5201: my ($udom,$uname) = @_;
1.1085 raeburn 5202: if ($udom ne '' && $uname ne '') {
5203: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5204: return $env{'user.adv'};
5205: }
5206: }
1.976 raeburn 5207: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5208: my %allroles;
5209: my $is_adv;
5210: foreach my $role (keys(%roleshash)) {
5211: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5212: my $area = '/'.$tdomain.'/'.$trest;
5213: if ($sec ne '') {
5214: $area .= '/'.$sec;
5215: }
5216: if (($area ne '') && ($trole ne '')) {
5217: my $spec=$trole.'.'.$area;
5218: if ($trole =~ /^cr\//) {
5219: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5220: } elsif ($trole ne 'gr') {
5221: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5222: }
5223: }
5224: }
5225: foreach my $role (keys(%allroles)) {
5226: last if ($is_adv);
5227: foreach my $item (split(/:/,$allroles{$role})) {
5228: if ($item ne '') {
5229: my ($privilege,$restrictions)=split(/&/,$item);
5230: if ($privilege eq 'adv') {
5231: $is_adv = 1;
5232: last;
5233: }
5234: }
5235: }
5236: }
5237: return $is_adv;
5238: }
1.798 raeburn 5239:
1.1035 raeburn 5240: sub check_can_request {
1.1036 raeburn 5241: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5242: my $canreq = 0;
5243: my ($types,$typename) = &Apache::loncommon::course_types();
5244: my @options = ('approval','validate','autolimit');
5245: my $optregex = join('|',@options);
5246: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5247: foreach my $type (@{$types}) {
5248: if (&usertools_access($env{'user.name'},
5249: $env{'user.domain'},
5250: $type,undef,'requestcourses')) {
5251: $canreq ++;
1.1036 raeburn 5252: if (ref($request_domains) eq 'HASH') {
5253: push(@{$request_domains->{$type}},$env{'user.domain'});
5254: }
1.1035 raeburn 5255: if ($dom eq $env{'user.domain'}) {
5256: $can_request->{$type} = 1;
5257: }
5258: }
5259: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5260: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5261: if (@curr > 0) {
1.1036 raeburn 5262: foreach my $item (@curr) {
5263: if (ref($request_domains) eq 'HASH') {
5264: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5265: if ($otherdom ne '') {
5266: if (ref($request_domains->{$type}) eq 'ARRAY') {
5267: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5268: push(@{$request_domains->{$type}},$otherdom);
5269: }
5270: } else {
5271: push(@{$request_domains->{$type}},$otherdom);
5272: }
5273: }
5274: }
5275: }
5276: unless($dom eq $env{'user.domain'}) {
5277: $canreq ++;
1.1035 raeburn 5278: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5279: $can_request->{$type} = 1;
5280: }
5281: }
5282: }
5283: }
5284: }
5285: }
5286: return $canreq;
5287: }
5288:
1.341 www 5289: # ---------------------------------------------- Custom access rule evaluation
5290:
5291: sub customaccess {
5292: my ($priv,$uri)=@_;
1.807 albertel 5293: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5294: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5295: $udom = &LONCAPA::clean_domain($udom);
5296: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5297: my $access=0;
1.800 albertel 5298: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5299: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5300: if ($type eq 'user') {
5301: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5302: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5303: if ($tdom) {
5304: if ($tdom ne $env{'user.domain'}) { next; }
5305: }
1.896 albertel 5306: if ($tuname) {
5307: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5308: }
5309: $access=($effect eq 'allow');
5310: last;
5311: }
5312: } else {
5313: if ($role) {
5314: if ($role ne $urole) { next; }
5315: }
5316: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5317: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5318: if ($tdom) {
5319: if ($tdom ne $udom) { next; }
5320: }
5321: if ($tcrs) {
5322: if ($tcrs ne $ucrs) { next; }
5323: }
5324: if ($tsec) {
5325: if ($tsec ne $usec) { next; }
5326: }
5327: $access=($effect eq 'allow');
5328: last;
5329: }
5330: if ($realm eq '' && $role eq '') {
5331: $access=($effect eq 'allow');
5332: }
1.402 bowersj2 5333: }
1.341 www 5334: }
5335: return $access;
5336: }
5337:
1.103 harris41 5338: # ------------------------------------------------- Check for a user privilege
1.12 www 5339:
5340: sub allowed {
1.810 raeburn 5341: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5342: my $ver_orguri=$uri;
1.439 www 5343: $uri=&deversion($uri);
1.152 www 5344: my $orguri=$uri;
1.52 www 5345: $uri=&declutter($uri);
1.809 raeburn 5346:
1.810 raeburn 5347: if ($priv eq 'evb') {
5348: # Evade communication block restrictions for specified role in a course
5349: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5350: return $1;
5351: } else {
5352: return;
5353: }
5354: }
5355:
1.620 albertel 5356: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5357: # Free bre access to adm and meta resources
1.775 albertel 5358: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5359: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5360: && ($priv eq 'bre')) {
1.14 www 5361: return 'F';
1.159 www 5362: }
5363:
1.545 banghart 5364: # Free bre access to user's own portfolio contents
1.714 raeburn 5365: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5366: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5367: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5368: my %setters;
5369: my ($startblock,$endblock) =
5370: &Apache::loncommon::blockcheck(\%setters,'port');
5371: if ($startblock && $endblock) {
5372: return 'B';
5373: } else {
5374: return 'F';
5375: }
1.545 banghart 5376: }
5377:
1.762 raeburn 5378: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5379: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5380: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5381: if (exists($env{'request.course.id'})) {
5382: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5383: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5384: if (($domain eq $cdom) && ($name eq $cnum)) {
5385: my $courseprivid=$env{'request.course.id'};
5386: $courseprivid=~s/\_/\//;
5387: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5388: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5389: return $1;
1.762 raeburn 5390: } else {
5391: if ($env{'request.course.sec'}) {
5392: $courseprivid.='/'.$env{'request.course.sec'};
5393: }
5394: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5395: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5396: return $2;
5397: }
1.714 raeburn 5398: }
5399: }
5400: }
5401: }
5402:
1.159 www 5403: # Free bre to public access
5404:
5405: if ($priv eq 'bre') {
1.238 www 5406: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5407: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5408: return 'F';
5409: }
1.238 www 5410: if ($copyright eq 'priv') {
5411: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5412: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5413: return '';
5414: }
5415: }
5416: if ($copyright eq 'domain') {
5417: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5418: unless (($env{'user.domain'} eq $1) ||
5419: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5420: return '';
5421: }
1.262 matthew 5422: }
1.620 albertel 5423: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5424: # Library role, so allow browsing of resources in this domain.
5425: return 'F';
1.238 www 5426: }
1.341 www 5427: if ($copyright eq 'custom') {
5428: unless (&customaccess($priv,$uri)) { return ''; }
5429: }
1.14 www 5430: }
1.264 matthew 5431: # Domain coordinator is trying to create a course
1.620 albertel 5432: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5433: # uri is the requested domain in this case.
5434: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5435: # a role of dc for the domain in question.
1.620 albertel 5436: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5437: }
1.29 www 5438:
1.52 www 5439: my $thisallowed='';
5440: my $statecond=0;
5441: my $courseprivid='';
5442:
1.1039 raeburn 5443: my $ownaccess;
1.1043 raeburn 5444: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5445: if (($priv eq 'bro') && ($env{'user.author'})) {
5446: if ($uri eq '') {
5447: $ownaccess = 1;
5448: } else {
5449: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5450: my $udom = $env{'user.domain'};
5451: my $uname = $env{'user.name'};
5452: if ($uri =~ m{^\Q$udom\E/?$}) {
5453: $ownaccess = 1;
1.1040 raeburn 5454: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5455: unless ($uri =~ m{\.\./}) {
5456: $ownaccess = 1;
5457: }
5458: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5459: my $now = time;
5460: if ($uri =~ m{^([^/]+)/?$}) {
5461: my $adom = $1;
5462: foreach my $key (keys(%env)) {
1.1042 raeburn 5463: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5464: my ($start,$end) = split('.',$env{$key});
5465: if (($now >= $start) && (!$end || $end < $now)) {
5466: $ownaccess = 1;
5467: last;
5468: }
5469: }
5470: }
5471: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5472: my $adom = $1;
5473: my $aname = $2;
1.1042 raeburn 5474: foreach my $role ('ca','aa') {
5475: if ($env{"user.role.$role./$adom/$aname"}) {
5476: my ($start,$end) =
5477: split('.',$env{"user.role.$role./$adom/$aname"});
5478: if (($now >= $start) && (!$end || $end < $now)) {
5479: $ownaccess = 1;
5480: last;
5481: }
1.1039 raeburn 5482: }
5483: }
5484: }
5485: }
5486: }
5487: }
5488: }
5489:
1.52 www 5490: # Course
5491:
1.620 albertel 5492: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5493: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5494: $thisallowed.=$1;
5495: }
1.52 www 5496: }
1.29 www 5497:
1.52 www 5498: # Domain
5499:
1.620 albertel 5500: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5501: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5502: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5503: $thisallowed.=$1;
5504: }
1.12 www 5505: }
1.52 www 5506:
5507: # Course: uri itself is a course
1.66 www 5508: my $courseuri=$uri;
5509: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5510: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5511:
1.620 albertel 5512: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5513: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5514: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5515: $thisallowed.=$1;
5516: }
1.12 www 5517: }
1.29 www 5518:
1.665 albertel 5519: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5520: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5521: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5522: $thisallowed='';
1.671 raeburn 5523: my ($match)=&is_on_map($uri);
5524: if ($match) {
5525: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5526: =~/\Q$priv\E\&([^\:]*)/) {
5527: $thisallowed.=$1;
5528: }
5529: } else {
1.705 albertel 5530: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5531: if ($refuri) {
5532: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5533: $thisallowed='F';
1.671 raeburn 5534: } else {
5535: $refuri=&declutter($refuri);
5536: my ($match) = &is_on_map($refuri);
5537: if ($match) {
5538: $thisallowed='F';
5539: }
1.669 raeburn 5540: }
1.671 raeburn 5541: }
5542: }
1.314 www 5543: }
1.492 albertel 5544:
1.766 albertel 5545: if ($priv eq 'bre'
5546: && $thisallowed ne 'F'
5547: && $thisallowed ne '2'
5548: && &is_portfolio_url($uri)) {
5549: $thisallowed = &portfolio_access($uri);
5550: }
5551:
1.52 www 5552: # Full access at system, domain or course-wide level? Exit.
1.29 www 5553: if ($thisallowed=~/F/) {
5554: return 'F';
5555: }
5556:
1.52 www 5557: # If this is generating or modifying users, exit with special codes
1.29 www 5558:
1.643 www 5559: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5560: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5561: my ($audom,$auname)=split('/',$uri);
1.643 www 5562: # no author name given, so this just checks on the general right to make a co-author in this domain
5563: unless ($auname) { return $thisallowed; }
5564: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5565: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5566: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5567: ($audom ne $env{'request.role.domain'}))) { return ''; }
5568: }
1.52 www 5569: return $thisallowed;
5570: }
5571: #
1.103 harris41 5572: # Gathered so far: system, domain and course wide privileges
1.52 www 5573: #
5574: # Course: See if uri or referer is an individual resource that is part of
5575: # the course
5576:
1.620 albertel 5577: if ($env{'request.course.id'}) {
1.232 www 5578:
1.620 albertel 5579: $courseprivid=$env{'request.course.id'};
5580: if ($env{'request.course.sec'}) {
5581: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5582: }
5583: $courseprivid=~s/\_/\//;
5584: my $checkreferer=1;
1.232 www 5585: my ($match,$cond)=&is_on_map($uri);
5586: if ($match) {
5587: $statecond=$cond;
1.620 albertel 5588: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5589: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5590: $thisallowed.=$1;
5591: $checkreferer=0;
5592: }
1.29 www 5593: }
1.83 www 5594:
1.148 www 5595: if ($checkreferer) {
1.620 albertel 5596: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5597: unless ($refuri) {
1.800 albertel 5598: foreach my $key (keys(%env)) {
5599: if ($key=~/^httpref\..*\*/) {
5600: my $pattern=$key;
1.156 www 5601: $pattern=~s/^httpref\.\/res\///;
1.148 www 5602: $pattern=~s/\*/\[\^\/\]\+/g;
5603: $pattern=~s/\//\\\//g;
1.152 www 5604: if ($orguri=~/$pattern/) {
1.800 albertel 5605: $refuri=$env{$key};
1.148 www 5606: }
5607: }
1.191 harris41 5608: }
1.148 www 5609: }
1.232 www 5610:
1.148 www 5611: if ($refuri) {
1.152 www 5612: $refuri=&declutter($refuri);
1.232 www 5613: my ($match,$cond)=&is_on_map($refuri);
5614: if ($match) {
5615: my $refstatecond=$cond;
1.620 albertel 5616: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5617: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5618: $thisallowed.=$1;
1.53 www 5619: $uri=$refuri;
5620: $statecond=$refstatecond;
1.52 www 5621: }
5622: }
1.148 www 5623: }
1.29 www 5624: }
1.52 www 5625: }
1.29 www 5626:
1.52 www 5627: #
1.103 harris41 5628: # Gathered now: all privileges that could apply, and condition number
1.52 www 5629: #
5630: #
5631: # Full or no access?
5632: #
1.29 www 5633:
1.52 www 5634: if ($thisallowed=~/F/) {
5635: return 'F';
5636: }
1.29 www 5637:
1.52 www 5638: unless ($thisallowed) {
5639: return '';
5640: }
1.29 www 5641:
1.52 www 5642: # Restrictions exist, deal with them
5643: #
5644: # C:according to course preferences
5645: # R:according to resource settings
5646: # L:unless locked
5647: # X:according to user session state
5648: #
5649:
5650: # Possibly locked functionality, check all courses
1.54 www 5651: # Locks might take effect only after 10 minutes cache expiration for other
5652: # courses, and 2 minutes for current course
1.52 www 5653:
5654: my $envkey;
5655: if ($thisallowed=~/L/) {
1.1000 raeburn 5656: foreach $envkey (keys(%env)) {
1.54 www 5657: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5658: my $courseid=$2;
5659: my $roleid=$1.'.'.$2;
1.92 www 5660: $courseid=~s/^\///;
1.54 www 5661: my $expiretime=600;
1.620 albertel 5662: if ($env{'request.role'} eq $roleid) {
1.54 www 5663: $expiretime=120;
5664: }
5665: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5666: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5667: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5668: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5669: }
1.620 albertel 5670: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5671: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5672: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5673: &log($env{'user.domain'},$env{'user.name'},
5674: $env{'user.home'},
1.57 www 5675: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5676: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5677: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5678: return '';
5679: }
5680: }
1.620 albertel 5681: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5682: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5683: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5684: &log($env{'user.domain'},$env{'user.name'},
5685: $env{'user.home'},
1.57 www 5686: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5687: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5688: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5689: return '';
5690: }
5691: }
5692: }
1.29 www 5693: }
1.52 www 5694: }
5695:
5696: #
5697: # Rest of the restrictions depend on selected course
5698: #
5699:
1.620 albertel 5700: unless ($env{'request.course.id'}) {
1.766 albertel 5701: if ($thisallowed eq 'A') {
5702: return 'A';
1.814 raeburn 5703: } elsif ($thisallowed eq 'B') {
5704: return 'B';
1.766 albertel 5705: } else {
5706: return '1';
5707: }
1.52 www 5708: }
1.29 www 5709:
1.52 www 5710: #
5711: # Now user is definitely in a course
5712: #
1.53 www 5713:
5714:
5715: # Course preferences
5716:
5717: if ($thisallowed=~/C/) {
1.620 albertel 5718: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5719: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5720: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5721: =~/\Q$rolecode\E/) {
1.1103 raeburn 5722: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5723: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5724: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5725: $env{'request.course.id'});
5726: }
1.237 www 5727: return '';
5728: }
5729:
1.620 albertel 5730: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5731: =~/\Q$unamedom\E/) {
1.1103 raeburn 5732: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5733: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5734: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5735: $env{'request.course.id'});
5736: }
1.54 www 5737: return '';
5738: }
1.53 www 5739: }
5740:
5741: # Resource preferences
5742:
5743: if ($thisallowed=~/R/) {
1.620 albertel 5744: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5745: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 5746: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5747: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5748: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5749: }
5750: return '';
1.54 www 5751: }
1.53 www 5752: }
1.30 www 5753:
1.246 www 5754: # Restricted by state or randomout?
1.30 www 5755:
1.52 www 5756: if ($thisallowed=~/X/) {
1.620 albertel 5757: if ($env{'acc.randomout'}) {
1.579 albertel 5758: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5759: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5760: return '';
5761: }
1.247 www 5762: }
5763: if (&condval($statecond)) {
1.52 www 5764: return '2';
5765: } else {
5766: return '';
5767: }
5768: }
1.30 www 5769:
1.766 albertel 5770: if ($thisallowed eq 'A') {
5771: return 'A';
1.814 raeburn 5772: } elsif ($thisallowed eq 'B') {
5773: return 'B';
1.766 albertel 5774: }
1.52 www 5775: return 'F';
1.232 www 5776: }
5777:
1.710 albertel 5778: sub split_uri_for_cond {
5779: my $uri=&deversion(&declutter(shift));
5780: my @uriparts=split(/\//,$uri);
5781: my $filename=pop(@uriparts);
5782: my $pathname=join('/',@uriparts);
5783: return ($pathname,$filename);
5784: }
1.232 www 5785: # --------------------------------------------------- Is a resource on the map?
5786:
5787: sub is_on_map {
1.710 albertel 5788: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5789: #Trying to find the conditional for the file
1.620 albertel 5790: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5791: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5792: if ($match) {
1.289 bowersj2 5793: return (1,$1);
5794: } else {
1.434 www 5795: return (0,0);
1.289 bowersj2 5796: }
1.12 www 5797: }
5798:
1.427 www 5799: # --------------------------------------------------------- Get symb from alias
5800:
5801: sub get_symb_from_alias {
5802: my $symb=shift;
5803: my ($map,$resid,$url)=&decode_symb($symb);
5804: # Already is a symb
5805: if ($url) { return $symb; }
5806: # Must be an alias
5807: my $aliassymb='';
5808: my %bighash;
1.620 albertel 5809: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5810: &GDBM_READER(),0640)) {
5811: my $rid=$bighash{'mapalias_'.$symb};
5812: if ($rid) {
5813: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5814: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5815: $resid,$bighash{'src_'.$rid});
1.427 www 5816: }
5817: untie %bighash;
5818: }
5819: return $aliassymb;
5820: }
5821:
1.12 www 5822: # ----------------------------------------------------------------- Define Role
5823:
5824: sub definerole {
5825: if (allowed('mcr','/')) {
5826: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5827: foreach my $role (split(':',$sysrole)) {
5828: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5829: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5830: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5831: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5832: return "refused:s:$crole&$cqual";
5833: }
5834: }
1.191 harris41 5835: }
1.800 albertel 5836: foreach my $role (split(':',$domrole)) {
5837: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5838: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5839: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5840: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5841: return "refused:d:$crole&$cqual";
5842: }
5843: }
1.191 harris41 5844: }
1.800 albertel 5845: foreach my $role (split(':',$courole)) {
5846: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5847: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5848: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5849: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5850: return "refused:c:$crole&$cqual";
5851: }
5852: }
1.191 harris41 5853: }
1.620 albertel 5854: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5855: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5856: "rolesdef_$rolename=".
5857: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5858: return reply($command,$env{'user.home'});
1.12 www 5859: } else {
5860: return 'refused';
5861: }
1.105 harris41 5862: }
5863:
5864: # ---------------- Make a metadata query against the network of library servers
5865:
5866: sub metadata_query {
1.244 matthew 5867: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5868: my %rhash;
1.845 albertel 5869: my %libserv = &all_library();
1.244 matthew 5870: my @server_list = (defined($server_array) ? @$server_array
5871: : keys(%libserv) );
5872: for my $server (@server_list) {
1.118 harris41 5873: unless ($custom or $customshow) {
5874: my $reply=&reply("querysend:".&escape($query),$server);
5875: $rhash{$server}=$reply;
5876: }
5877: else {
5878: my $reply=&reply("querysend:".&escape($query).':'.
5879: &escape($custom).':'.&escape($customshow),
5880: $server);
5881: $rhash{$server}=$reply;
5882: }
1.112 harris41 5883: }
1.118 harris41 5884: return \%rhash;
1.240 www 5885: }
5886:
5887: # ----------------------------------------- Send log queries and wait for reply
5888:
5889: sub log_query {
5890: my ($uname,$udom,$query,%filters)=@_;
5891: my $uhome=&homeserver($uname,$udom);
5892: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5893: my $uhost=&hostname($uhome);
1.800 albertel 5894: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5895: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5896: $uhome);
1.479 albertel 5897: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5898: return get_query_reply($queryid);
5899: }
5900:
1.818 raeburn 5901: # -------------------------- Update MySQL table for portfolio file
5902:
5903: sub update_portfolio_table {
1.821 raeburn 5904: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5905: if ($group ne '') {
5906: $file_name =~s /^\Q$group\E//;
5907: }
1.818 raeburn 5908: my $homeserver = &homeserver($uname,$udom);
5909: my $queryid=
1.821 raeburn 5910: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5911: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5912: my $reply = &get_query_reply($queryid);
5913: return $reply;
5914: }
5915:
1.899 raeburn 5916: # -------------------------- Update MySQL allusers table
5917:
5918: sub update_allusers_table {
5919: my ($uname,$udom,$names) = @_;
5920: my $homeserver = &homeserver($uname,$udom);
5921: my $queryid=
5922: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5923: 'lastname='.&escape($names->{'lastname'}).'%%'.
5924: 'firstname='.&escape($names->{'firstname'}).'%%'.
5925: 'middlename='.&escape($names->{'middlename'}).'%%'.
5926: 'generation='.&escape($names->{'generation'}).'%%'.
5927: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5928: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 5929: return;
1.899 raeburn 5930: }
5931:
1.508 raeburn 5932: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5933:
5934: sub fetch_enrollment_query {
1.511 raeburn 5935: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5936: my $homeserver;
1.547 raeburn 5937: my $maxtries = 1;
1.508 raeburn 5938: if ($context eq 'automated') {
5939: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5940: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5941: } else {
5942: $homeserver = &homeserver($cnum,$dom);
5943: }
1.838 albertel 5944: my $host=&hostname($homeserver);
1.506 raeburn 5945: my $cmd = '';
1.1000 raeburn 5946: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5947: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5948: }
5949: $cmd =~ s/%%$//;
5950: $cmd = &escape($cmd);
5951: my $query = 'fetchenrollment';
1.620 albertel 5952: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5953: unless ($queryid=~/^\Q$host\E\_/) {
5954: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5955: return 'error: '.$queryid;
5956: }
1.506 raeburn 5957: my $reply = &get_query_reply($queryid);
1.547 raeburn 5958: my $tries = 1;
5959: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5960: $reply = &get_query_reply($queryid);
5961: $tries ++;
5962: }
1.526 raeburn 5963: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5964: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5965: } else {
1.901 albertel 5966: my @responses = split(/:/,$reply);
1.515 raeburn 5967: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5968: foreach my $line (@responses) {
5969: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5970: $$replyref{$key} = $value;
5971: }
5972: } else {
1.506 raeburn 5973: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5974: foreach my $line (@responses) {
5975: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5976: $$replyref{$key} = $value;
5977: if ($value > 0) {
1.800 albertel 5978: foreach my $item (@{$$affiliatesref{$key}}) {
5979: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5980: my $destname = $pathname.'/'.$filename;
5981: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5982: if ($xml_classlist =~ /^error/) {
5983: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5984: } else {
1.506 raeburn 5985: if ( open(FILE,">$destname") ) {
5986: print FILE &unescape($xml_classlist);
5987: close(FILE);
1.526 raeburn 5988: } else {
5989: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5990: }
5991: }
5992: }
5993: }
5994: }
5995: }
5996: return 'ok';
5997: }
5998: return 'error';
5999: }
6000:
1.242 www 6001: sub get_query_reply {
6002: my $queryid=shift;
1.240 www 6003: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
6004: my $reply='';
6005: for (1..100) {
6006: sleep 2;
6007: if (-e $replyfile.'.end') {
1.448 albertel 6008: if (open(my $fh,$replyfile)) {
1.904 albertel 6009: $reply = join('',<$fh>);
6010: close($fh);
1.240 www 6011: } else { return 'error: reply_file_error'; }
1.242 www 6012: return &unescape($reply);
6013: }
1.240 www 6014: }
1.242 www 6015: return 'timeout:'.$queryid;
1.240 www 6016: }
6017:
6018: sub courselog_query {
1.241 www 6019: #
6020: # possible filters:
6021: # url: url or symb
6022: # username
6023: # domain
6024: # action: view, submit, grade
6025: # start: timestamp
6026: # end: timestamp
6027: #
1.240 www 6028: my (%filters)=@_;
1.620 albertel 6029: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6030: if ($filters{'url'}) {
6031: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6032: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6033: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6034: }
1.620 albertel 6035: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6036: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6037: return &log_query($cname,$cdom,'courselog',%filters);
6038: }
6039:
6040: sub userlog_query {
1.858 raeburn 6041: #
6042: # possible filters:
6043: # action: log check role
6044: # start: timestamp
6045: # end: timestamp
6046: #
1.240 www 6047: my ($uname,$udom,%filters)=@_;
6048: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6049: }
6050:
1.506 raeburn 6051: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6052:
6053: sub auto_run {
1.508 raeburn 6054: my ($cnum,$cdom) = @_;
1.876 raeburn 6055: my $response = 0;
6056: my $settings;
6057: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6058: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6059: $settings = $domconfig{'autoenroll'};
6060: if ($settings->{'run'} eq '1') {
6061: $response = 1;
6062: }
6063: } else {
1.934 raeburn 6064: my $homeserver;
6065: if (&is_course($cdom,$cnum)) {
6066: $homeserver = &homeserver($cnum,$cdom);
6067: } else {
6068: $homeserver = &domain($cdom,'primary');
6069: }
6070: if ($homeserver ne 'no_host') {
6071: $response = &reply('autorun:'.$cdom,$homeserver);
6072: }
1.876 raeburn 6073: }
1.506 raeburn 6074: return $response;
6075: }
1.776 albertel 6076:
1.506 raeburn 6077: sub auto_get_sections {
1.508 raeburn 6078: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6079: my $homeserver;
6080: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6081: $homeserver = &homeserver($cnum,$cdom);
6082: }
6083: if (!defined($homeserver)) {
6084: if ($cdom =~ /^$match_domain$/) {
6085: $homeserver = &domain($cdom,'primary');
6086: }
6087: }
6088: my @secs;
6089: if (defined($homeserver)) {
6090: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6091: unless ($response eq 'refused') {
6092: @secs = split(/:/,$response);
6093: }
1.506 raeburn 6094: }
6095: return @secs;
6096: }
1.776 albertel 6097:
1.506 raeburn 6098: sub auto_new_course {
1.1099 raeburn 6099: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6100: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6101: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6102: return $response;
6103: }
1.776 albertel 6104:
1.506 raeburn 6105: sub auto_validate_courseID {
1.508 raeburn 6106: my ($cnum,$cdom,$inst_course_id) = @_;
6107: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6108: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6109: return $response;
6110: }
1.776 albertel 6111:
1.1007 raeburn 6112: sub auto_validate_instcode {
1.1020 raeburn 6113: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6114: my ($homeserver,$response);
6115: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6116: $homeserver = &homeserver($cnum,$cdom);
6117: }
6118: if (!defined($homeserver)) {
6119: if ($cdom =~ /^$match_domain$/) {
6120: $homeserver = &domain($cdom,'primary');
6121: }
6122: }
1.1065 raeburn 6123: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6124: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6125: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6126: return ($outcome,$description);
1.1007 raeburn 6127: }
6128:
1.506 raeburn 6129: sub auto_create_password {
1.873 raeburn 6130: my ($cnum,$cdom,$authparam,$udom) = @_;
6131: my ($homeserver,$response);
1.506 raeburn 6132: my $create_passwd = 0;
6133: my $authchk = '';
1.873 raeburn 6134: if ($udom =~ /^$match_domain$/) {
6135: $homeserver = &domain($udom,'primary');
6136: }
6137: if ($homeserver eq '') {
6138: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6139: $homeserver = &homeserver($cnum,$cdom);
6140: }
6141: }
6142: if ($homeserver eq '') {
6143: $authchk = 'nodomain';
1.506 raeburn 6144: } else {
1.873 raeburn 6145: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6146: if ($response eq 'refused') {
6147: $authchk = 'refused';
6148: } else {
1.901 albertel 6149: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6150: }
1.506 raeburn 6151: }
6152: return ($authparam,$create_passwd,$authchk);
6153: }
6154:
1.706 raeburn 6155: sub auto_photo_permission {
6156: my ($cnum,$cdom,$students) = @_;
6157: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6158: my ($outcome,$perm_reqd,$conditions) =
6159: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6160: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6161: return (undef,undef);
6162: }
1.706 raeburn 6163: return ($outcome,$perm_reqd,$conditions);
6164: }
6165:
6166: sub auto_checkphotos {
6167: my ($uname,$udom,$pid) = @_;
6168: my $homeserver = &homeserver($uname,$udom);
6169: my ($result,$resulttype);
6170: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6171: &escape($uname).':'.&escape($pid),
6172: $homeserver));
1.709 albertel 6173: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6174: return (undef,undef);
6175: }
1.706 raeburn 6176: if ($outcome) {
6177: ($result,$resulttype) = split(/:/,$outcome);
6178: }
6179: return ($result,$resulttype);
6180: }
6181:
6182: sub auto_photochoice {
6183: my ($cnum,$cdom) = @_;
6184: my $homeserver = &homeserver($cnum,$cdom);
6185: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6186: &escape($cdom),
6187: $homeserver)));
1.709 albertel 6188: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6189: return (undef,undef);
6190: }
1.706 raeburn 6191: return ($update,$comment);
6192: }
6193:
6194: sub auto_photoupdate {
6195: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6196: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6197: my $host=&hostname($homeserver);
1.706 raeburn 6198: my $cmd = '';
6199: my $maxtries = 1;
1.800 albertel 6200: foreach my $affiliate (keys(%{$affiliatesref})) {
6201: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6202: }
6203: $cmd =~ s/%%$//;
6204: $cmd = &escape($cmd);
6205: my $query = 'institutionalphotos';
6206: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6207: unless ($queryid=~/^\Q$host\E\_/) {
6208: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6209: return 'error: '.$queryid;
6210: }
6211: my $reply = &get_query_reply($queryid);
6212: my $tries = 1;
6213: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6214: $reply = &get_query_reply($queryid);
6215: $tries ++;
6216: }
6217: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6218: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6219: } else {
6220: my @responses = split(/:/,$reply);
6221: my $outcome = shift(@responses);
6222: foreach my $item (@responses) {
6223: my ($key,$value) = split(/=/,$item);
6224: $$photo{$key} = $value;
6225: }
6226: return $outcome;
6227: }
6228: return 'error';
6229: }
6230:
1.521 raeburn 6231: sub auto_instcode_format {
1.793 albertel 6232: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6233: $cat_order) = @_;
1.521 raeburn 6234: my $courses = '';
1.772 raeburn 6235: my @homeservers;
1.521 raeburn 6236: if ($caller eq 'global') {
1.841 albertel 6237: my %servers = &get_servers($codedom,'library');
6238: foreach my $tryserver (keys(%servers)) {
6239: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6240: push(@homeservers,$tryserver);
6241: }
1.584 raeburn 6242: }
1.1022 raeburn 6243: } elsif ($caller eq 'requests') {
6244: if ($codedom =~ /^$match_domain$/) {
6245: my $chome = &domain($codedom,'primary');
6246: unless ($chome eq 'no_host') {
6247: push(@homeservers,$chome);
6248: }
6249: }
1.521 raeburn 6250: } else {
1.772 raeburn 6251: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6252: }
1.793 albertel 6253: foreach my $code (keys(%{$instcodes})) {
6254: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6255: }
6256: chop($courses);
1.772 raeburn 6257: my $ok_response = 0;
6258: my $response;
6259: while (@homeservers > 0 && $ok_response == 0) {
6260: my $server = shift(@homeservers);
6261: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6262: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6263: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6264: split(/:/,$response);
1.772 raeburn 6265: %{$codes} = (%{$codes},&str2hash($codes_str));
6266: push(@{$codetitles},&str2array($codetitles_str));
6267: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6268: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6269: $ok_response = 1;
6270: }
6271: }
6272: if ($ok_response) {
1.521 raeburn 6273: return 'ok';
1.772 raeburn 6274: } else {
6275: return $response;
1.521 raeburn 6276: }
6277: }
6278:
1.792 raeburn 6279: sub auto_instcode_defaults {
6280: my ($domain,$returnhash,$code_order) = @_;
6281: my @homeservers;
1.841 albertel 6282:
6283: my %servers = &get_servers($domain,'library');
6284: foreach my $tryserver (keys(%servers)) {
6285: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6286: push(@homeservers,$tryserver);
6287: }
1.792 raeburn 6288: }
1.841 albertel 6289:
1.792 raeburn 6290: my $response;
1.841 albertel 6291: foreach my $server (@homeservers) {
1.792 raeburn 6292: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6293: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6294:
6295: foreach my $pair (split(/\&/,$response)) {
6296: my ($name,$value)=split(/\=/,$pair);
6297: if ($name eq 'code_order') {
6298: @{$code_order} = split(/\&/,&unescape($value));
6299: } else {
6300: $returnhash->{&unescape($name)}=&unescape($value);
6301: }
6302: }
6303: return 'ok';
1.792 raeburn 6304: }
1.841 albertel 6305:
6306: return $response;
1.1003 raeburn 6307: }
6308:
6309: sub auto_possible_instcodes {
1.1007 raeburn 6310: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6311: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6312: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6313: return;
6314: }
1.1003 raeburn 6315: my (@homeservers,$uhome);
6316: if (defined(&domain($domain,'primary'))) {
6317: $uhome=&domain($domain,'primary');
6318: push(@homeservers,&domain($domain,'primary'));
6319: } else {
6320: my %servers = &get_servers($domain,'library');
6321: foreach my $tryserver (keys(%servers)) {
6322: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6323: push(@homeservers,$tryserver);
6324: }
6325: }
6326: }
6327: my $response;
6328: foreach my $server (@homeservers) {
6329: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6330: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6331: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6332: split(':',$response);
6333: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6334: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6335: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6336: my ($name,$value)=split('=',$item);
6337: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6338: }
6339: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6340: my ($name,$value)=split('=',$item);
6341: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6342: }
6343: return 'ok';
6344: }
6345: return $response;
6346: }
1.792 raeburn 6347:
1.1010 raeburn 6348: sub auto_courserequest_checks {
6349: my ($dom) = @_;
1.1020 raeburn 6350: my ($homeserver,%validations);
6351: if ($dom =~ /^$match_domain$/) {
6352: $homeserver = &domain($dom,'primary');
6353: }
6354: unless ($homeserver eq 'no_host') {
6355: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6356: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6357: my @items = split(/&/,$response);
6358: foreach my $item (@items) {
6359: my ($key,$value) = split('=',$item);
6360: $validations{&unescape($key)} = &thaw_unescape($value);
6361: }
6362: }
6363: }
1.1010 raeburn 6364: return %validations;
6365: }
6366:
1.1020 raeburn 6367: sub auto_courserequest_validation {
6368: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6369: my ($homeserver,$response);
6370: if ($dom =~ /^$match_domain$/) {
6371: $homeserver = &domain($dom,'primary');
6372: }
6373: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6374:
1.1020 raeburn 6375: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6376: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6377: ':'.&escape($instcode).':'.&escape($instseclist),
6378: $homeserver));
6379: }
6380: return $response;
6381: }
6382:
1.777 albertel 6383: sub auto_validate_class_sec {
1.918 raeburn 6384: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6385: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6386: my $ownerlist;
6387: if (ref($owners) eq 'ARRAY') {
6388: $ownerlist = join(',',@{$owners});
6389: } else {
6390: $ownerlist = $owners;
6391: }
1.773 raeburn 6392: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6393: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6394: return $response;
6395: }
6396:
1.679 raeburn 6397: # ------------------------------------------------------- Course Group routines
6398:
6399: sub get_coursegroups {
1.809 raeburn 6400: my ($cdom,$cnum,$group,$namespace) = @_;
6401: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6402: }
6403:
1.679 raeburn 6404: sub modify_coursegroup {
6405: my ($cdom,$cnum,$groupsettings) = @_;
6406: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6407: }
6408:
1.809 raeburn 6409: sub toggle_coursegroup_status {
6410: my ($cdom,$cnum,$group,$action) = @_;
6411: my ($from_namespace,$to_namespace);
6412: if ($action eq 'delete') {
6413: $from_namespace = 'coursegroups';
6414: $to_namespace = 'deleted_groups';
6415: } else {
6416: $from_namespace = 'deleted_groups';
6417: $to_namespace = 'coursegroups';
6418: }
6419: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6420: if (my $tmp = &error(%curr_group)) {
6421: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6422: return ('read error',$tmp);
6423: } else {
6424: my %savedsettings = %curr_group;
1.809 raeburn 6425: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6426: my $deloutcome;
6427: if ($result eq 'ok') {
1.809 raeburn 6428: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6429: } else {
6430: return ('write error',$result);
6431: }
6432: if ($deloutcome eq 'ok') {
6433: return 'ok';
6434: } else {
6435: return ('delete error',$deloutcome);
6436: }
6437: }
6438: }
6439:
1.679 raeburn 6440: sub modify_group_roles {
1.957 raeburn 6441: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6442: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6443: my $role = 'gr/'.&escape($userprivs);
6444: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6445: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6446: if ($result eq 'ok') {
6447: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6448: }
1.679 raeburn 6449: return $result;
6450: }
6451:
6452: sub modify_coursegroup_membership {
6453: my ($cdom,$cnum,$membership) = @_;
6454: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6455: return $result;
6456: }
6457:
1.682 raeburn 6458: sub get_active_groups {
6459: my ($udom,$uname,$cdom,$cnum) = @_;
6460: my $now = time;
6461: my %groups = ();
6462: foreach my $key (keys(%env)) {
1.811 albertel 6463: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6464: my ($start,$end) = split(/\./,$env{$key});
6465: if (($end!=0) && ($end<$now)) { next; }
6466: if (($start!=0) && ($start>$now)) { next; }
6467: if ($1 eq $cdom && $2 eq $cnum) {
6468: $groups{$3} = $env{$key} ;
6469: }
6470: }
6471: }
6472: return %groups;
6473: }
6474:
1.683 raeburn 6475: sub get_group_membership {
6476: my ($cdom,$cnum,$group) = @_;
6477: return(&dump('groupmembership',$cdom,$cnum,$group));
6478: }
6479:
6480: sub get_users_groups {
6481: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6482: my @usersgroups;
1.683 raeburn 6483: my $cachetime=1800;
6484:
6485: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6486: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6487: if (defined($cached)) {
1.734 albertel 6488: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6489: } else {
6490: $grouplist = '';
1.816 raeburn 6491: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6492: my $extra = &freeze_escape({'skipcheck' => 1});
6493: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6494: my $access_end = $env{'course.'.$courseid.
6495: '.default_enrollment_end_date'};
6496: my $now = time;
6497: foreach my $key (keys(%roleshash)) {
6498: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6499: my $group = $1;
6500: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6501: my $start = $2;
6502: my $end = $1;
6503: if ($start == -1) { next; } # deleted from group
6504: if (($start!=0) && ($start>$now)) { next; }
6505: if (($end!=0) && ($end<$now)) {
6506: if ($access_end && $access_end < $now) {
6507: if ($access_end - $end < 86400) {
6508: push(@usersgroups,$group);
1.733 raeburn 6509: }
6510: }
1.817 raeburn 6511: next;
1.733 raeburn 6512: }
1.817 raeburn 6513: push(@usersgroups,$group);
1.683 raeburn 6514: }
6515: }
6516: }
1.817 raeburn 6517: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6518: $grouplist = join(':',@usersgroups);
6519: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6520: }
1.733 raeburn 6521: return @usersgroups;
1.683 raeburn 6522: }
6523:
6524: sub devalidate_getgroups_cache {
6525: my ($udom,$uname,$cdom,$cnum)=@_;
6526: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6527:
1.683 raeburn 6528: my $hashid="$udom:$uname:$courseid";
6529: &devalidate_cache_new('getgroups',$hashid);
6530: }
6531:
1.12 www 6532: # ------------------------------------------------------------------ Plain Text
6533:
6534: sub plaintext {
1.988 raeburn 6535: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6536: if ($short =~ m{^cr/}) {
1.758 albertel 6537: return (split('/',$short))[-1];
6538: }
1.742 raeburn 6539: if (!defined($cid)) {
6540: $cid = $env{'request.course.id'};
6541: }
6542: my %rolenames = (
1.1008 raeburn 6543: Course => 'std',
6544: Community => 'alt1',
1.742 raeburn 6545: );
1.1037 raeburn 6546: if ($cid ne '') {
6547: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6548: unless ($forcedefault) {
6549: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6550: &Apache::lonlocal::mt_escape(\$roletext);
6551: return &Apache::lonlocal::mt($roletext);
6552: }
6553: }
6554: }
6555: if ((defined($type)) && (defined($rolenames{$type})) &&
6556: (defined($rolenames{$type})) &&
6557: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6558: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6559: } elsif ($cid ne '') {
6560: my $crstype = $env{'course.'.$cid.'.type'};
6561: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6562: (defined($prp{$short}{$rolenames{$crstype}}))) {
6563: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6564: }
1.742 raeburn 6565: }
1.1037 raeburn 6566: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6567: }
6568:
6569: # ----------------------------------------------------------------- Assign Role
6570:
6571: sub assignrole {
1.957 raeburn 6572: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6573: $context)=@_;
1.21 www 6574: my $mrole;
6575: if ($role =~ /^cr\//) {
1.393 www 6576: my $cwosec=$url;
1.811 albertel 6577: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6578: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6579: my $refused = 1;
6580: if ($context eq 'requestcourses') {
6581: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6582: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6583: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6584: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6585: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6586: if ($crsenv{'internal.courseowner'} eq
6587: $env{'user.name'}.':'.$env{'user.domain'}) {
6588: $refused = '';
6589: }
6590: }
6591: }
6592: }
6593: }
6594: if ($refused) {
6595: &logthis('Refused custom assignrole: '.
6596: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6597: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6598: return 'refused';
6599: }
1.104 www 6600: }
1.21 www 6601: $mrole='cr';
1.678 raeburn 6602: } elsif ($role =~ /^gr\//) {
6603: my $cwogrp=$url;
1.811 albertel 6604: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6605: unless (&allowed('mdg',$cwogrp)) {
6606: &logthis('Refused group assignrole: '.
6607: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6608: $env{'user.name'}.' at '.$env{'user.domain'});
6609: return 'refused';
6610: }
6611: $mrole='gr';
1.21 www 6612: } else {
1.82 www 6613: my $cwosec=$url;
1.811 albertel 6614: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6615: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6616: my $refused;
6617: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6618: if (!(&allowed('c'.$role,$url))) {
6619: $refused = 1;
6620: }
6621: } else {
6622: $refused = 1;
6623: }
1.947 raeburn 6624: if ($refused) {
1.1045 raeburn 6625: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6626: if (!$selfenroll && $context eq 'course') {
6627: my %crsenv;
6628: if ($role eq 'cc' || $role eq 'co') {
6629: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6630: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6631: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6632: if ($crsenv{'internal.courseowner'} eq
6633: $env{'user.name'}.':'.$env{'user.domain'}) {
6634: $refused = '';
6635: }
6636: }
6637: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6638: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6639: if ($crsenv{'internal.courseowner'} eq
6640: $env{'user.name'}.':'.$env{'user.domain'}) {
6641: $refused = '';
6642: }
6643: }
6644: }
6645: }
6646: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6647: $refused = '';
1.1017 raeburn 6648: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6649: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6650: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6651: my $wrongcc;
6652: if ($cnum =~ /^$match_community$/) {
6653: $wrongcc = 1 if ($role eq 'cc');
6654: } else {
6655: $wrongcc = 1 if ($role eq 'co');
6656: }
6657: unless ($wrongcc) {
6658: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6659: if ($crsenv{'internal.courseowner'} eq
6660: $env{'user.name'}.':'.$env{'user.domain'}) {
6661: $refused = '';
6662: }
1.1017 raeburn 6663: }
6664: }
6665: }
6666: if ($refused) {
1.947 raeburn 6667: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6668: ' '.$role.' '.$end.' '.$start.' by '.
6669: $env{'user.name'}.' at '.$env{'user.domain'});
6670: return 'refused';
6671: }
1.932 raeburn 6672: }
1.104 www 6673: }
1.21 www 6674: $mrole=$role;
6675: }
1.620 albertel 6676: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6677: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6678: if ($end) { $command.='_'.$end; }
1.21 www 6679: if ($start) {
6680: if ($end) {
1.81 www 6681: $command.='_'.$start;
1.21 www 6682: } else {
1.81 www 6683: $command.='_0_'.$start;
1.21 www 6684: }
6685: }
1.739 raeburn 6686: my $origstart = $start;
6687: my $origend = $end;
1.957 raeburn 6688: my $delflag;
1.357 www 6689: # actually delete
6690: if ($deleteflag) {
1.373 www 6691: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6692: # modify command to delete the role
1.620 albertel 6693: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6694: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6695: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6696: # set start and finish to negative values for userrolelog
6697: $start=-1;
6698: $end=-1;
1.957 raeburn 6699: $delflag = 1;
1.357 www 6700: }
6701: }
6702: # send command
1.349 www 6703: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6704: # log new user role if status is ok
1.349 www 6705: if ($answer eq 'ok') {
1.663 raeburn 6706: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6707: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6708: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6709: unless ($role =~ /^gr/) {
6710: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6711: $origstart,$selfenroll,$context);
1.739 raeburn 6712: }
1.1053 raeburn 6713: if ($role eq 'cc') {
6714: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6715: }
1.349 www 6716: }
6717: return $answer;
1.169 harris41 6718: }
6719:
1.1053 raeburn 6720: sub autoupdate_coowners {
6721: my ($url,$end,$start,$uname,$udom) = @_;
6722: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6723: if (($cdom ne '') && ($cnum ne '')) {
6724: my $now = time;
6725: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6726: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6727: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6728: my $instcode = $coursehash{'internal.coursecode'};
6729: if ($instcode ne '') {
1.1056 raeburn 6730: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6731: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6732: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6733: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6734: if ($result eq 'valid') {
6735: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6736: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6737: push(@newcoowners,$coowner);
6738: }
6739: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6740: push(@newcoowners,$uname.':'.$udom);
6741: }
6742: @newcoowners = sort(@newcoowners);
6743: } else {
6744: push(@newcoowners,$uname.':'.$udom);
6745: }
6746: } else {
6747: if ($coursehash{'internal.co-owners'}) {
6748: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6749: unless ($coowner eq $uname.':'.$udom) {
6750: push(@newcoowners,$coowner);
6751: }
6752: }
6753: unless (@newcoowners > 0) {
6754: $delcoowners = 1;
6755: $coowners = '';
6756: }
6757: }
6758: }
6759: if (@newcoowners || $delcoowners) {
6760: &store_coowners($cdom,$cnum,$coursehash{'home'},
6761: $delcoowners,@newcoowners);
6762: }
6763: }
6764: }
6765: }
6766: }
6767: }
6768: }
6769:
6770: sub store_coowners {
6771: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6772: my $cid = $cdom.'_'.$cnum;
6773: my ($coowners,$delresult,$putresult);
6774: if (@newcoowners) {
6775: $coowners = join(',',@newcoowners);
6776: my %coownershash = (
6777: 'internal.co-owners' => $coowners,
6778: );
6779: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6780: if ($putresult eq 'ok') {
6781: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6782: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6783: }
6784: }
6785: }
6786: if ($delcoowners) {
6787: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6788: if ($delresult eq 'ok') {
6789: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6790: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6791: }
6792: }
6793: }
6794: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6795: my %crsinfo =
6796: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6797: if (ref($crsinfo{$cid}) eq 'HASH') {
6798: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6799: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6800: }
6801: }
6802: }
6803:
1.169 harris41 6804: # -------------------------------------------------- Modify user authentication
1.197 www 6805: # Overrides without validation
6806:
1.169 harris41 6807: sub modifyuserauth {
6808: my ($udom,$uname,$umode,$upass)=@_;
6809: my $uhome=&homeserver($uname,$udom);
1.197 www 6810: unless (&allowed('mau',$udom)) { return 'refused'; }
6811: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6812: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6813: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6814: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6815: &escape($upass),$uhome);
1.620 albertel 6816: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6817: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6818: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6819: &log($udom,,$uname,$uhome,
1.620 albertel 6820: 'Authentication changed by '.$env{'user.domain'}.', '.
6821: $env{'user.name'}.', '.$umode.
1.197 www 6822: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6823: unless ($reply eq 'ok') {
1.197 www 6824: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6825: return 'error: '.$reply;
6826: }
1.170 harris41 6827: return 'ok';
1.80 www 6828: }
6829:
1.81 www 6830: # --------------------------------------------------------------- Modify a user
1.80 www 6831:
1.81 www 6832: sub modifyuser {
1.206 matthew 6833: my ($udom, $uname, $uid,
6834: $umode, $upass, $first,
6835: $middle, $last, $gene,
1.1058 raeburn 6836: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6837: $udom= &LONCAPA::clean_domain($udom);
6838: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6839: my $showcandelete = 'none';
6840: if (ref($candelete) eq 'ARRAY') {
6841: if (@{$candelete} > 0) {
6842: $showcandelete = join(', ',@{$candelete});
6843: }
6844: }
1.81 www 6845: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6846: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6847: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6848: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6849: ' desiredhome not specified').
1.620 albertel 6850: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6851: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6852: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 6853: my $newuser;
6854: if ($uhome eq 'no_host') {
6855: $newuser = 1;
6856: }
1.80 www 6857: # ----------------------------------------------------------------- Create User
1.406 albertel 6858: if (($uhome eq 'no_host') &&
6859: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6860: my $unhome='';
1.844 albertel 6861: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6862: $unhome = $desiredhome;
1.620 albertel 6863: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6864: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6865: } else { # load balancing routine for determining $unhome
1.81 www 6866: my $loadm=10000000;
1.841 albertel 6867: my %servers = &get_servers($udom,'library');
6868: foreach my $tryserver (keys(%servers)) {
6869: my $answer=reply('load',$tryserver);
6870: if (($answer=~/\d+/) && ($answer<$loadm)) {
6871: $loadm=$answer;
6872: $unhome=$tryserver;
6873: }
1.80 www 6874: }
6875: }
6876: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6877: return 'error: unable to find a home server for '.$uname.
6878: ' in domain '.$udom;
1.80 www 6879: }
6880: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6881: &escape($upass),$unhome);
6882: unless ($reply eq 'ok') {
6883: return 'error: '.$reply;
6884: }
1.230 stredwic 6885: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6886: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6887: return 'error: unable verify users home machine.';
1.80 www 6888: }
1.209 matthew 6889: } # End of creation of new user
1.80 www 6890: # ---------------------------------------------------------------------- Add ID
6891: if ($uid) {
6892: $uid=~tr/A-Z/a-z/;
6893: my %uidhash=&idrget($udom,$uname);
1.196 www 6894: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6895: && (!$forceid)) {
1.80 www 6896: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6897: return 'error: user id "'.$uid.'" does not match '.
6898: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6899: }
6900: } else {
6901: &idput($udom,($uname => $uid));
6902: }
6903: }
6904: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6905: my @tmp=&get('environment',
1.899 raeburn 6906: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6907: 'permanentemail','inststatus'],
1.134 albertel 6908: $udom,$uname);
1.1075 raeburn 6909: my (%names,%oldnames);
1.313 matthew 6910: if ($tmp[0] =~ m/^error:.*/) {
6911: %names=();
6912: } else {
6913: %names = @tmp;
1.1075 raeburn 6914: %oldnames = %names;
1.313 matthew 6915: }
1.388 www 6916: #
1.1058 raeburn 6917: # If name, email and/or uid are blank (e.g., because an uploaded file
6918: # of users did not contain them), do not overwrite existing values
6919: # unless field is in $candelete array ref.
6920: #
6921:
6922: my @fields = ('firstname','middlename','lastname','generation',
6923: 'permanentemail','id');
6924: my %newvalues;
6925: if (ref($candelete) eq 'ARRAY') {
6926: foreach my $field (@fields) {
6927: if (grep(/^\Q$field\E$/,@{$candelete})) {
6928: if ($field eq 'firstname') {
6929: $names{$field} = $first;
6930: } elsif ($field eq 'middlename') {
6931: $names{$field} = $middle;
6932: } elsif ($field eq 'lastname') {
6933: $names{$field} = $last;
6934: } elsif ($field eq 'generation') {
6935: $names{$field} = $gene;
6936: } elsif ($field eq 'permanentemail') {
6937: $names{$field} = $email;
6938: } elsif ($field eq 'id') {
6939: $names{$field} = $uid;
6940: }
6941: }
6942: }
6943: }
1.388 www 6944: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6945: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6946: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6947: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6948: if ($email) {
6949: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6950: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6951: }
1.899 raeburn 6952: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6953: if (defined($inststatus)) {
6954: $names{'inststatus'} = '';
6955: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6956: if (ref($usertypes) eq 'HASH') {
6957: my @okstatuses;
6958: foreach my $item (split(/:/,$inststatus)) {
6959: if (defined($usertypes->{$item})) {
6960: push(@okstatuses,$item);
6961: }
6962: }
6963: if (@okstatuses) {
6964: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6965: }
6966: }
6967: }
1.1075 raeburn 6968: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6969: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 6970: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6971: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6972: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6973: } else {
6974: $logmsg .= ' during self creation';
6975: }
1.1075 raeburn 6976: my $changed;
6977: if ($newuser) {
6978: $changed = 1;
6979: } else {
6980: foreach my $field (@fields) {
6981: if ($names{$field} ne $oldnames{$field}) {
6982: $changed = 1;
6983: last;
6984: }
6985: }
6986: }
6987: unless ($changed) {
6988: $logmsg = 'No changes in user information needed for: '.$logmsg;
6989: &logthis($logmsg);
6990: return 'ok';
6991: }
6992: my $reply = &put('environment', \%names, $udom,$uname);
6993: if ($reply ne 'ok') {
6994: return 'error: '.$reply;
6995: }
1.1087 raeburn 6996: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
6997: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
6998: }
1.1075 raeburn 6999: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7000: &devalidate_cache_new('namescache',$uname.':'.$udom);
7001: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7002: &logthis($logmsg);
1.134 albertel 7003: return 'ok';
1.80 www 7004: }
7005:
1.81 www 7006: # -------------------------------------------------------------- Modify student
1.80 www 7007:
1.81 www 7008: sub modifystudent {
7009: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7010: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7011: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7012: if (!$cid) {
1.620 albertel 7013: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7014: return 'not_in_class';
7015: }
1.80 www 7016: }
7017: # --------------------------------------------------------------- Make the user
1.81 www 7018: my $reply=&modifyuser
1.209 matthew 7019: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7020: $desiredhome,$email,$inststatus);
1.80 www 7021: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7022: # This will cause &modify_student_enrollment to get the uid from the
7023: # students environment
7024: $uid = undef if (!$forceid);
1.455 albertel 7025: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7026: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7027: return $reply;
7028: }
7029:
7030: sub modify_student_enrollment {
1.957 raeburn 7031: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7032: my ($cdom,$cnum,$chome);
7033: if (!$cid) {
1.620 albertel 7034: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7035: return 'not_in_class';
7036: }
1.620 albertel 7037: $cdom=$env{'course.'.$cid.'.domain'};
7038: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7039: } else {
7040: ($cdom,$cnum)=split(/_/,$cid);
7041: }
1.620 albertel 7042: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7043: if (!$chome) {
1.457 raeburn 7044: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7045: }
1.455 albertel 7046: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7047: # Make sure the user exists
1.81 www 7048: my $uhome=&homeserver($uname,$udom);
7049: if (($uhome eq '') || ($uhome eq 'no_host')) {
7050: return 'error: no such user';
7051: }
1.297 matthew 7052: # Get student data if we were not given enough information
7053: if (!defined($first) || $first eq '' ||
7054: !defined($last) || $last eq '' ||
7055: !defined($uid) || $uid eq '' ||
7056: !defined($middle) || $middle eq '' ||
7057: !defined($gene) || $gene eq '') {
1.294 matthew 7058: # They did not supply us with enough data to enroll the student, so
7059: # we need to pick up more information.
1.297 matthew 7060: my %tmp = &get('environment',
1.294 matthew 7061: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7062: ,$udom,$uname);
7063:
1.800 albertel 7064: #foreach my $key (keys(%tmp)) {
7065: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7066: #}
1.294 matthew 7067: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7068: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7069: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7070: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7071: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7072: }
1.556 albertel 7073: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7074: my $reply=cput('classlist',
7075: {"$uname:$udom" =>
1.515 raeburn 7076: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7077: $cdom,$cnum);
1.81 www 7078: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7079: return 'error: '.$reply;
1.652 albertel 7080: } else {
7081: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7082: }
1.297 matthew 7083: # Add student role to user
1.83 www 7084: my $uurl='/'.$cid;
1.81 www 7085: $uurl=~s/\_/\//g;
7086: if ($usec) {
7087: $uurl.='/'.$usec;
7088: }
1.957 raeburn 7089: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7090: }
7091:
1.556 albertel 7092: sub format_name {
7093: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7094: my $name;
7095: if ($first ne 'lastname') {
7096: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7097: } else {
7098: if ($lastname=~/\S/) {
7099: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7100: $name=~s/\s+,/,/;
7101: } else {
7102: $name.= $firstname.' '.$middlename.' '.$generation;
7103: }
7104: }
7105: $name=~s/^\s+//;
7106: $name=~s/\s+$//;
7107: $name=~s/\s+/ /g;
7108: return $name;
7109: }
7110:
1.84 www 7111: # ------------------------------------------------- Write to course preferences
7112:
7113: sub writecoursepref {
7114: my ($courseid,%prefs)=@_;
7115: $courseid=~s/^\///;
7116: $courseid=~s/\_/\//g;
7117: my ($cdomain,$cnum)=split(/\//,$courseid);
7118: my $chome=homeserver($cnum,$cdomain);
7119: if (($chome eq '') || ($chome eq 'no_host')) {
7120: return 'error: no such course';
7121: }
7122: my $cstring='';
1.800 albertel 7123: foreach my $pref (keys(%prefs)) {
7124: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7125: }
1.84 www 7126: $cstring=~s/\&$//;
7127: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7128: }
7129:
7130: # ---------------------------------------------------------- Make/modify course
7131:
7132: sub createcourse {
1.741 raeburn 7133: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7134: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7135: $url=&declutter($url);
7136: my $cid='';
1.1028 raeburn 7137: if ($context eq 'requestcourses') {
7138: my $can_create = 0;
7139: my ($ownername,$ownerdom) = split(':',$course_owner);
7140: if ($udom eq $ownerdom) {
7141: if (&usertools_access($ownername,$ownerdom,$category,undef,
7142: $context)) {
7143: $can_create = 1;
7144: }
7145: } else {
7146: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7147: $category);
7148: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7149: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7150: if (@curr > 0) {
7151: my @options = qw(approval validate autolimit);
7152: my $optregex = join('|',@options);
7153: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7154: $can_create = 1;
7155: }
7156: }
7157: }
7158: }
7159: if ($can_create) {
7160: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7161: unless (&allowed('ccc',$udom)) {
7162: return 'refused';
7163: }
1.1017 raeburn 7164: }
7165: } else {
7166: return 'refused';
7167: }
1.1028 raeburn 7168: } elsif (!&allowed('ccc',$udom)) {
7169: return 'refused';
1.84 www 7170: }
1.1011 raeburn 7171: # --------------------------------------------------------------- Get Unique ID
7172: my $uname;
7173: if ($cnum =~ /^$match_courseid$/) {
7174: my $chome=&homeserver($cnum,$udom,'true');
7175: if (($chome eq '') || ($chome eq 'no_host')) {
7176: $uname = $cnum;
7177: } else {
1.1038 raeburn 7178: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7179: }
7180: } else {
1.1038 raeburn 7181: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7182: }
7183: return $uname if ($uname =~ /^error/);
7184: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7185: if (!defined($course_server)) {
7186: if (defined(&domain($udom,'primary'))) {
7187: $course_server = &domain($udom,'primary');
7188: } else {
7189: $course_server = $env{'user.home'};
7190: }
7191: }
7192: my %host_servers =
7193: &Apache::lonnet::get_servers($udom,'library');
7194: unless ($host_servers{$course_server}) {
7195: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7196: }
1.84 www 7197: # ------------------------------------------------------------- Make the course
7198: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7199: $course_server);
1.84 www 7200: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7201: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7202: if (($uhome eq '') || ($uhome eq 'no_host')) {
7203: return 'error: no such course';
7204: }
1.271 www 7205: # ----------------------------------------------------------------- Course made
1.516 raeburn 7206: # log existence
1.1029 raeburn 7207: my $now = time;
1.918 raeburn 7208: my $newcourse = {
7209: $udom.'_'.$uname => {
1.921 raeburn 7210: description => $description,
7211: inst_code => $inst_code,
7212: owner => $course_owner,
7213: type => $crstype,
1.1029 raeburn 7214: creator => $env{'user.name'}.':'.
7215: $env{'user.domain'},
7216: created => $now,
7217: context => $context,
1.918 raeburn 7218: },
7219: };
1.921 raeburn 7220: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7221: # set toplevel url
1.271 www 7222: my $topurl=$url;
7223: unless ($nonstandard) {
7224: # ------------------------------------------ For standard courses, make top url
7225: my $mapurl=&clutter($url);
1.278 www 7226: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7227: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7228: <map>
7229: <resource id="1" type="start"></resource>
7230: <resource id="2" src="$mapurl"></resource>
7231: <resource id="3" type="finish"></resource>
7232: <link index="1" from="1" to="2"></link>
7233: <link index="2" from="2" to="3"></link>
7234: </map>
7235: ENDINITMAP
7236: $topurl=&declutter(
1.638 albertel 7237: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7238: );
7239: }
7240: # ----------------------------------------------------------- Write preferences
1.84 www 7241: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7242: ('description' => $description,
7243: 'url' => $topurl,
7244: 'internal.creator' => $env{'user.name'}.':'.
7245: $env{'user.domain'},
7246: 'internal.created' => $now,
7247: 'internal.creationcontext' => $context)
7248: );
1.84 www 7249: return '/'.$udom.'/'.$uname;
7250: }
7251:
1.1011 raeburn 7252: # ------------------------------------------------------------------- Create ID
7253: sub generate_coursenum {
1.1038 raeburn 7254: my ($udom,$crstype) = @_;
1.1011 raeburn 7255: my $domdesc = &domain($udom);
7256: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7257: my $first;
7258: if ($crstype eq 'Community') {
7259: $first = '0';
7260: } else {
7261: $first = int(1+rand(9));
7262: }
7263: my $uname=$first.
1.1011 raeburn 7264: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7265: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7266: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7267: # ----------------------------------------------- Make sure that does not exist
7268: my $uhome=&homeserver($uname,$udom,'true');
7269: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7270: if ($crstype eq 'Community') {
7271: $first = '0';
7272: } else {
7273: $first = int(1+rand(9));
7274: }
7275: $uname=$first.
1.1011 raeburn 7276: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7277: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7278: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7279: $uhome=&homeserver($uname,$udom,'true');
7280: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7281: return 'error: unable to generate unique course-ID';
7282: }
7283: }
7284: return $uname;
7285: }
7286:
1.813 albertel 7287: sub is_course {
7288: my ($cdom,$cnum) = @_;
7289: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7290: undef,'.');
1.813 albertel 7291: if (exists($courses{$cdom.'_'.$cnum})) {
7292: return 1;
7293: }
7294: return 0;
7295: }
7296:
1.1015 raeburn 7297: sub store_userdata {
7298: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7299: my $result;
1.1016 raeburn 7300: if ($datakey ne '') {
1.1013 raeburn 7301: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7302: if ($udom eq '' || $uname eq '') {
7303: $udom = $env{'user.domain'};
7304: $uname = $env{'user.name'};
7305: }
7306: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7307: if (($uhome eq '') || ($uhome eq 'no_host')) {
7308: $result = 'error: no_host';
7309: } else {
7310: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7311: $storehash->{'host'} = $perlvar{'lonHostID'};
7312:
7313: my $namevalue='';
7314: foreach my $key (keys(%{$storehash})) {
7315: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7316: }
7317: $namevalue=~s/\&$//;
1.1105 raeburn 7318: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7319: $namevalue,$uhome);
1.1013 raeburn 7320: }
7321: } else {
7322: $result = 'error: data to store was not a hash reference';
7323: }
7324: } else {
7325: $result= 'error: invalid requestkey';
7326: }
7327: return $result;
7328: }
7329:
1.21 www 7330: # ---------------------------------------------------------- Assign Custom Role
7331:
7332: sub assigncustomrole {
1.957 raeburn 7333: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7334: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7335: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7336: }
7337:
7338: # ----------------------------------------------------------------- Revoke Role
7339:
7340: sub revokerole {
1.957 raeburn 7341: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7342: my $now=time;
1.965 raeburn 7343: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7344: }
7345:
7346: # ---------------------------------------------------------- Revoke Custom Role
7347:
7348: sub revokecustomrole {
1.957 raeburn 7349: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7350: my $now=time;
1.357 www 7351: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7352: $deleteflag,$selfenroll,$context);
1.17 www 7353: }
7354:
1.533 banghart 7355: # ------------------------------------------------------------ Disk usage
1.535 albertel 7356: sub diskusage {
1.955 raeburn 7357: my ($udom,$uname,$directorypath,$getpropath)=@_;
7358: $directorypath =~ s/\/$//;
7359: my $listing=&reply('du2:'.&escape($directorypath).':'
7360: .&escape($getpropath).':'.&escape($uname).':'
7361: .&escape($udom),homeserver($uname,$udom));
7362: if ($listing eq 'unknown_cmd') {
7363: if ($getpropath) {
7364: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7365: }
7366: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7367: }
1.514 albertel 7368: return $listing;
1.512 banghart 7369: }
7370:
1.566 banghart 7371: sub is_locked {
1.1096 raeburn 7372: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7373: my @check;
7374: my $is_locked;
1.1093 raeburn 7375: push (@check,$file_name);
1.613 albertel 7376: my %locked = &get('file_permissions',\@check,
1.620 albertel 7377: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7378: my ($tmp)=keys(%locked);
7379: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7380:
1.566 banghart 7381: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7382: $is_locked = 'false';
7383: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 7384: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7385: $is_locked = 'true';
1.1096 raeburn 7386: if (ref($which) eq 'ARRAY') {
7387: push(@{$which},$entry);
7388: } else {
7389: last;
7390: }
1.745 raeburn 7391: }
7392: }
1.566 banghart 7393: } else {
7394: $is_locked = 'false';
7395: }
1.1093 raeburn 7396: return $is_locked;
1.566 banghart 7397: }
7398:
1.759 albertel 7399: sub declutter_portfile {
7400: my ($file) = @_;
1.833 albertel 7401: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7402: return $file;
7403: }
7404:
1.559 banghart 7405: # ------------------------------------------------------------- Mark as Read Only
7406:
7407: sub mark_as_readonly {
7408: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7409: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7410: my ($tmp)=keys(%current_permissions);
7411: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7412: foreach my $file (@{$files}) {
1.759 albertel 7413: $file = &declutter_portfile($file);
1.561 banghart 7414: push(@{$current_permissions{$file}},$what);
1.559 banghart 7415: }
1.613 albertel 7416: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7417: return;
7418: }
7419:
1.572 banghart 7420: # ------------------------------------------------------------Save Selected Files
7421:
7422: sub save_selected_files {
7423: my ($user, $path, @files) = @_;
7424: my $filename = $user."savedfiles";
1.573 banghart 7425: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7426: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7427: foreach my $file (@files) {
1.620 albertel 7428: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7429: }
7430: foreach my $file (@other_files) {
1.574 banghart 7431: print (OUT $file."\n");
1.572 banghart 7432: }
1.574 banghart 7433: close (OUT);
1.572 banghart 7434: return 'ok';
7435: }
7436:
1.574 banghart 7437: sub clear_selected_files {
7438: my ($user) = @_;
7439: my $filename = $user."savedfiles";
7440: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7441: print (OUT undef);
7442: close (OUT);
7443: return ("ok");
7444: }
7445:
1.572 banghart 7446: sub files_in_path {
7447: my ($user, $path) = @_;
7448: my $filename = $user."savedfiles";
7449: my %return_files;
1.574 banghart 7450: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7451: while (my $line_in = <IN>) {
1.574 banghart 7452: chomp ($line_in);
7453: my @paths_and_file = split (m!/!, $line_in);
7454: my $file_part = pop (@paths_and_file);
7455: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7456: $path_part.='/';
7457: my $path_and_file = $path_part.$file_part;
7458: if ($path_part eq $path) {
7459: $return_files{$file_part}= 'selected';
7460: }
7461: }
1.574 banghart 7462: close (IN);
7463: return (\%return_files);
1.572 banghart 7464: }
7465:
7466: # called in portfolio select mode, to show files selected NOT in current directory
7467: sub files_not_in_path {
7468: my ($user, $path) = @_;
7469: my $filename = $user."savedfiles";
7470: my @return_files;
7471: my $path_part;
1.800 albertel 7472: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7473: while (my $line = <IN>) {
1.572 banghart 7474: #ok, I know it's clunky, but I want it to work
1.800 albertel 7475: my @paths_and_file = split(m|/|, $line);
7476: my $file_part = pop(@paths_and_file);
7477: chomp($file_part);
7478: my $path_part = join('/', @paths_and_file);
1.572 banghart 7479: $path_part .= '/';
7480: my $path_and_file = $path_part.$file_part;
7481: if ($path_part ne $path) {
1.800 albertel 7482: push(@return_files, ($path_and_file));
1.572 banghart 7483: }
7484: }
1.800 albertel 7485: close(OUT);
1.574 banghart 7486: return (@return_files);
1.572 banghart 7487: }
7488:
1.745 raeburn 7489: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7490:
1.745 raeburn 7491: sub get_portfile_permissions {
7492: my ($domain,$user) = @_;
1.613 albertel 7493: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7494: my ($tmp)=keys(%current_permissions);
7495: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7496: return \%current_permissions;
7497: }
7498:
7499: #---------------------------------------------Get portfolio file access controls
7500:
1.749 raeburn 7501: sub get_access_controls {
1.745 raeburn 7502: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7503: my %access;
7504: my $real_file = $file;
7505: $file =~ s/\.meta$//;
1.745 raeburn 7506: if (defined($file)) {
1.749 raeburn 7507: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7508: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7509: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7510: }
7511: }
1.745 raeburn 7512: } else {
1.749 raeburn 7513: foreach my $key (keys(%{$current_permissions})) {
7514: if ($key =~ /\0accesscontrol$/) {
7515: if (defined($group)) {
7516: if ($key !~ m-^\Q$group\E/-) {
7517: next;
7518: }
7519: }
7520: my ($fullpath) = split(/\0/,$key);
7521: if (ref($$current_permissions{$key}) eq 'HASH') {
7522: foreach my $control (keys(%{$$current_permissions{$key}})) {
7523: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7524: }
7525: }
7526: }
7527: }
7528: }
7529: return %access;
7530: }
7531:
7532: sub modify_access_controls {
7533: my ($file_name,$changes,$domain,$user)=@_;
7534: my ($outcome,$deloutcome);
7535: my %store_permissions;
7536: my %new_values;
7537: my %new_control;
7538: my %translation;
7539: my @deletions = ();
7540: my $now = time;
7541: if (exists($$changes{'activate'})) {
7542: if (ref($$changes{'activate'}) eq 'HASH') {
7543: my @newitems = sort(keys(%{$$changes{'activate'}}));
7544: my $numnew = scalar(@newitems);
7545: for (my $i=0; $i<$numnew; $i++) {
7546: my $newkey = $newitems[$i];
7547: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7548: if ($newkey =~ /^\d+:/) {
7549: $newkey =~ s/^(\d+)/$newid/;
7550: $translation{$1} = $newid;
7551: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7552: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7553: $translation{$1} = $newid;
7554: }
1.749 raeburn 7555: $new_values{$file_name."\0".$newkey} =
7556: $$changes{'activate'}{$newitems[$i]};
7557: $new_control{$newkey} = $now;
7558: }
7559: }
7560: }
7561: my %todelete;
7562: my %changed_items;
7563: foreach my $action ('delete','update') {
7564: if (exists($$changes{$action})) {
7565: if (ref($$changes{$action}) eq 'HASH') {
7566: foreach my $key (keys(%{$$changes{$action}})) {
7567: my ($itemnum) = ($key =~ /^([^:]+):/);
7568: if ($action eq 'delete') {
7569: $todelete{$itemnum} = 1;
7570: } else {
7571: $changed_items{$itemnum} = $key;
7572: }
7573: }
1.745 raeburn 7574: }
7575: }
1.749 raeburn 7576: }
7577: # get lock on access controls for file.
7578: my $lockhash = {
7579: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7580: ':'.$env{'user.domain'},
7581: };
7582: my $tries = 0;
7583: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7584:
7585: while (($gotlock ne 'ok') && $tries <3) {
7586: $tries ++;
7587: sleep 1;
7588: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7589: }
7590: if ($gotlock eq 'ok') {
7591: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7592: my ($tmp)=keys(%curr_permissions);
7593: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7594: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7595: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7596: if (ref($curr_controls) eq 'HASH') {
7597: foreach my $control_item (keys(%{$curr_controls})) {
7598: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7599: if (defined($todelete{$itemnum})) {
7600: push(@deletions,$file_name."\0".$control_item);
7601: } else {
7602: if (defined($changed_items{$itemnum})) {
7603: $new_control{$changed_items{$itemnum}} = $now;
7604: push(@deletions,$file_name."\0".$control_item);
7605: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7606: } else {
7607: $new_control{$control_item} = $$curr_controls{$control_item};
7608: }
7609: }
1.745 raeburn 7610: }
7611: }
7612: }
1.970 raeburn 7613: my ($group);
7614: if (&is_course($domain,$user)) {
7615: ($group,my $file) = split(/\//,$file_name,2);
7616: }
1.749 raeburn 7617: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7618: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7619: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7620: # remove lock
7621: my @del_lock = ($file_name."\0".'locked_access_records');
7622: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7623: my $sqlresult =
1.970 raeburn 7624: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7625: $group);
1.749 raeburn 7626: } else {
7627: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7628: }
1.749 raeburn 7629: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7630: }
7631:
1.827 raeburn 7632: sub make_public_indefinitely {
7633: my ($requrl) = @_;
7634: my $now = time;
7635: my $action = 'activate';
7636: my $aclnum = 0;
7637: if (&is_portfolio_url($requrl)) {
7638: my (undef,$udom,$unum,$file_name,$group) =
7639: &parse_portfolio_url($requrl);
7640: my $current_perms = &get_portfile_permissions($udom,$unum);
7641: my %access_controls = &get_access_controls($current_perms,
7642: $group,$file_name);
7643: foreach my $key (keys(%{$access_controls{$file_name}})) {
7644: my ($num,$scope,$end,$start) =
7645: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7646: if ($scope eq 'public') {
7647: if ($start <= $now && $end == 0) {
7648: $action = 'none';
7649: } else {
7650: $action = 'update';
7651: $aclnum = $num;
7652: }
7653: last;
7654: }
7655: }
7656: if ($action eq 'none') {
7657: return 'ok';
7658: } else {
7659: my %changes;
7660: my $newend = 0;
7661: my $newstart = $now;
7662: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7663: $changes{$action}{$newkey} = {
7664: type => 'public',
7665: time => {
7666: start => $newstart,
7667: end => $newend,
7668: },
7669: };
7670: my ($outcome,$deloutcome,$new_values,$translation) =
7671: &modify_access_controls($file_name,\%changes,$udom,$unum);
7672: return $outcome;
7673: }
7674: } else {
7675: return 'invalid';
7676: }
7677: }
7678:
1.745 raeburn 7679: #------------------------------------------------------Get Marked as Read Only
7680:
7681: sub get_marked_as_readonly {
7682: my ($domain,$user,$what,$group) = @_;
7683: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7684: my @readonly_files;
1.629 banghart 7685: my $cmp1=$what;
7686: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7687: while (my ($file_name,$value) = each(%{$current_permissions})) {
7688: if (defined($group)) {
7689: if ($file_name !~ m-^\Q$group\E/-) {
7690: next;
7691: }
7692: }
1.561 banghart 7693: if (ref($value) eq "ARRAY"){
7694: foreach my $stored_what (@{$value}) {
1.629 banghart 7695: my $cmp2=$stored_what;
1.759 albertel 7696: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7697: $cmp2=join('',@{$stored_what});
1.745 raeburn 7698: }
1.629 banghart 7699: if ($cmp1 eq $cmp2) {
1.561 banghart 7700: push(@readonly_files, $file_name);
1.745 raeburn 7701: last;
1.563 banghart 7702: } elsif (!defined($what)) {
7703: push(@readonly_files, $file_name);
1.745 raeburn 7704: last;
1.561 banghart 7705: }
7706: }
1.745 raeburn 7707: }
1.561 banghart 7708: }
7709: return @readonly_files;
7710: }
1.577 banghart 7711: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7712:
1.577 banghart 7713: sub get_marked_as_readonly_hash {
1.745 raeburn 7714: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7715: my %readonly_files;
1.745 raeburn 7716: while (my ($file_name,$value) = each(%{$current_permissions})) {
7717: if (defined($group)) {
7718: if ($file_name !~ m-^\Q$group\E/-) {
7719: next;
7720: }
7721: }
1.577 banghart 7722: if (ref($value) eq "ARRAY"){
7723: foreach my $stored_what (@{$value}) {
1.745 raeburn 7724: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7725: foreach my $lock_descriptor(@{$stored_what}) {
7726: if ($lock_descriptor eq 'graded') {
7727: $readonly_files{$file_name} = 'graded';
7728: } elsif ($lock_descriptor eq 'handback') {
7729: $readonly_files{$file_name} = 'handback';
7730: } else {
7731: if (!exists($readonly_files{$file_name})) {
7732: $readonly_files{$file_name} = 'locked';
7733: }
7734: }
1.745 raeburn 7735: }
1.750 banghart 7736: }
1.577 banghart 7737: }
7738: }
7739: }
7740: return %readonly_files;
7741: }
1.559 banghart 7742: # ------------------------------------------------------------ Unmark as Read Only
7743:
7744: sub unmark_as_readonly {
1.629 banghart 7745: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7746: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7747: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7748: $file_name = &declutter_portfile($file_name);
1.634 albertel 7749: my $symb_crs = $what;
7750: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7751: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7752: my ($tmp)=keys(%current_permissions);
7753: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7754: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7755: foreach my $file (@readonly_files) {
1.759 albertel 7756: my $clean_file = &declutter_portfile($file);
7757: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7758: my $current_locks = $current_permissions{$file};
1.563 banghart 7759: my @new_locks;
7760: my @del_keys;
7761: if (ref($current_locks) eq "ARRAY"){
7762: foreach my $locker (@{$current_locks}) {
1.632 albertel 7763: my $compare=$locker;
1.749 raeburn 7764: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7765: $compare=join('',@{$locker});
1.746 raeburn 7766: if ($compare ne $symb_crs) {
7767: push(@new_locks, $locker);
7768: }
1.563 banghart 7769: }
7770: }
1.650 albertel 7771: if (scalar(@new_locks) > 0) {
1.563 banghart 7772: $current_permissions{$file} = \@new_locks;
7773: } else {
7774: push(@del_keys, $file);
1.613 albertel 7775: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7776: delete($current_permissions{$file});
1.563 banghart 7777: }
7778: }
1.561 banghart 7779: }
1.613 albertel 7780: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7781: return;
7782: }
1.512 banghart 7783:
1.17 www 7784: # ------------------------------------------------------------ Directory lister
7785:
7786: sub dirlist {
1.955 raeburn 7787: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7788: $uri=~s/^\///;
7789: $uri=~s/\/$//;
1.253 stredwic 7790: my ($udom, $uname);
1.955 raeburn 7791: if ($getuserdir) {
1.253 stredwic 7792: $udom = $userdomain;
7793: $uname = $username;
1.955 raeburn 7794: } else {
7795: (undef,$udom,$uname)=split(/\//,$uri);
7796: if(defined($userdomain)) {
7797: $udom = $userdomain;
7798: }
7799: if(defined($username)) {
7800: $uname = $username;
7801: }
1.253 stredwic 7802: }
1.955 raeburn 7803: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7804:
1.955 raeburn 7805: $dirRoot = $perlvar{'lonDocRoot'};
7806: if (defined($getpropath)) {
7807: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7808: $dirRoot =~ s/\/$//;
1.955 raeburn 7809: } elsif (defined($getuserdir)) {
7810: my $subdir=$uname.'__';
7811: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7812: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7813: ."/$udom/$subdir/$uname";
7814: } elsif (defined($alternateRoot)) {
7815: $dirRoot = $alternateRoot;
1.751 banghart 7816: }
1.253 stredwic 7817:
7818: if($udom) {
7819: if($uname) {
1.955 raeburn 7820: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7821: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7822: .':'.&escape($uname).':'.&escape($udom),
7823: &homeserver($uname,$udom));
7824: if ($listing eq 'unknown_cmd') {
7825: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7826: &homeserver($uname,$udom));
7827: } else {
7828: @listing_results = map { &unescape($_); } split(/:/,$listing);
7829: }
1.605 matthew 7830: if ($listing eq 'unknown_cmd') {
1.800 albertel 7831: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7832: &homeserver($uname,$udom));
1.605 matthew 7833: @listing_results = split(/:/,$listing);
7834: } else {
7835: @listing_results = map { &unescape($_); } split(/:/,$listing);
7836: }
7837: return @listing_results;
1.955 raeburn 7838: } elsif(!$alternateRoot) {
1.800 albertel 7839: my %allusers;
1.841 albertel 7840: my %servers = &get_servers($udom,'library');
1.955 raeburn 7841: foreach my $tryserver (keys(%servers)) {
7842: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7843: &escape($udom),$tryserver);
7844: if ($listing eq 'unknown_cmd') {
7845: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7846: $udom, $tryserver);
7847: } else {
7848: @listing_results = map { &unescape($_); } split(/:/,$listing);
7849: }
1.841 albertel 7850: if ($listing eq 'unknown_cmd') {
7851: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7852: $udom, $tryserver);
7853: @listing_results = split(/:/,$listing);
7854: } else {
7855: @listing_results =
7856: map { &unescape($_); } split(/:/,$listing);
7857: }
7858: if ($listing_results[0] ne 'no_such_dir' &&
7859: $listing_results[0] ne 'empty' &&
7860: $listing_results[0] ne 'con_lost') {
7861: foreach my $line (@listing_results) {
7862: my ($entry) = split(/&/,$line,2);
7863: $allusers{$entry} = 1;
7864: }
7865: }
1.253 stredwic 7866: }
7867: my $alluserstr='';
1.800 albertel 7868: foreach my $user (sort(keys(%allusers))) {
7869: $alluserstr.=$user.'&user:';
1.253 stredwic 7870: }
7871: $alluserstr=~s/:$//;
7872: return split(/:/,$alluserstr);
7873: } else {
1.800 albertel 7874: return ('missing user name');
1.253 stredwic 7875: }
1.955 raeburn 7876: } elsif(!defined($getpropath)) {
1.841 albertel 7877: my @all_domains = sort(&all_domains());
1.955 raeburn 7878: foreach my $domain (@all_domains) {
7879: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7880: }
7881: return @all_domains;
7882: } else {
1.800 albertel 7883: return ('missing domain');
1.275 stredwic 7884: }
7885: }
7886:
7887: # --------------------------------------------- GetFileTimestamp
7888: # This function utilizes dirlist and returns the date stamp for
7889: # when it was last modified. It will also return an error of -1
7890: # if an error occurs
7891:
7892: sub GetFileTimestamp {
1.955 raeburn 7893: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7894: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7895: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7896: my ($fileStat) =
7897: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7898: undef,$getuserdir);
1.275 stredwic 7899: my @stats = split('&', $fileStat);
7900: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7901: # @stats contains first the filename, then the stat output
7902: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7903: } else {
7904: return -1;
1.253 stredwic 7905: }
1.26 www 7906: }
7907:
1.712 albertel 7908: sub stat_file {
7909: my ($uri) = @_;
1.787 albertel 7910: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7911:
1.955 raeburn 7912: my ($udom,$uname,$file);
1.712 albertel 7913: if ($uri =~ m-^/(uploaded|editupload)/-) {
7914: ($udom,$uname,$file) =
1.811 albertel 7915: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7916: $file = 'userfiles/'.$file;
7917: }
7918: if ($uri =~ m-^/res/-) {
7919: ($udom,$uname) =
1.807 albertel 7920: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7921: $file = $uri;
7922: }
7923:
7924: if (!$udom || !$uname || !$file) {
7925: # unable to handle the uri
7926: return ();
7927: }
1.956 raeburn 7928: my $getpropath;
7929: if ($file =~ /^userfiles\//) {
7930: $getpropath = 1;
7931: }
1.955 raeburn 7932: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7933: my @stats = split('&', $result);
1.721 banghart 7934:
1.712 albertel 7935: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7936: shift(@stats); #filename is first
7937: return @stats;
7938: }
7939: return ();
7940: }
7941:
1.26 www 7942: # -------------------------------------------------------- Value of a Condition
7943:
1.713 albertel 7944: # gets the value of a specific preevaluated condition
7945: # stored in the string $env{user.state.<cid>}
7946: # or looks up a condition reference in the bighash and if if hasn't
7947: # already been evaluated recurses into docondval to get the value of
7948: # the condition, then memoizing it to
7949: # $env{user.state.<cid>.<condition>}
1.40 www 7950: sub directcondval {
7951: my $number=shift;
1.620 albertel 7952: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7953: &Apache::lonuserstate::evalstate();
7954: }
1.713 albertel 7955: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7956: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7957: } elsif ($number =~ /^_/) {
7958: my $sub_condition;
7959: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7960: &GDBM_READER(),0640)) {
7961: $sub_condition=$bighash{'conditions'.$number};
7962: untie(%bighash);
7963: }
7964: my $value = &docondval($sub_condition);
1.949 raeburn 7965: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7966: return $value;
7967: }
1.620 albertel 7968: if ($env{'user.state.'.$env{'request.course.id'}}) {
7969: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7970: } else {
7971: return 2;
7972: }
7973: }
7974:
1.713 albertel 7975: # get the collection of conditions for this resource
1.26 www 7976: sub condval {
7977: my $condidx=shift;
1.54 www 7978: my $allpathcond='';
1.713 albertel 7979: foreach my $cond (split(/\|/,$condidx)) {
7980: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7981: $allpathcond.=
7982: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7983: }
1.191 harris41 7984: }
1.54 www 7985: $allpathcond=~s/\|$//;
1.713 albertel 7986: return &docondval($allpathcond);
7987: }
7988:
7989: #evaluates an expression of conditions
7990: sub docondval {
7991: my ($allpathcond) = @_;
7992: my $result=0;
7993: if ($env{'request.course.id'}
7994: && defined($allpathcond)) {
7995: my $operand='|';
7996: my @stack;
7997: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7998: if ($chunk eq '(') {
7999: push @stack,($operand,$result);
8000: } elsif ($chunk eq ')') {
8001: my $before=pop @stack;
8002: if (pop @stack eq '&') {
8003: $result=$result>$before?$before:$result;
8004: } else {
8005: $result=$result>$before?$result:$before;
8006: }
8007: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8008: $operand=$chunk;
8009: } else {
8010: my $new=directcondval($chunk);
8011: if ($operand eq '&') {
8012: $result=$result>$new?$new:$result;
8013: } else {
8014: $result=$result>$new?$result:$new;
8015: }
8016: }
8017: }
1.26 www 8018: }
8019: return $result;
1.421 albertel 8020: }
8021:
8022: # ---------------------------------------------------- Devalidate courseresdata
8023:
8024: sub devalidatecourseresdata {
8025: my ($coursenum,$coursedomain)=@_;
8026: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8027: &devalidate_cache_new('courseres',$hashid);
1.28 www 8028: }
8029:
1.763 www 8030:
1.200 www 8031: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8032: #
8033: # Parameters:
8034: # $coursenum - Number of the course.
8035: # $coursedomain - Domain at which the course was created.
8036: # Returns:
8037: # A hash of the course parameters along (I think) with timestamps
8038: # and version info.
1.877 foxr 8039:
1.624 albertel 8040: sub get_courseresdata {
8041: my ($coursenum,$coursedomain)=@_;
1.200 www 8042: my $coursehom=&homeserver($coursenum,$coursedomain);
8043: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8044: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8045: my %dumpreply;
1.417 albertel 8046: unless (defined($cached)) {
1.624 albertel 8047: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8048: $result=\%dumpreply;
1.251 albertel 8049: my ($tmp) = keys(%dumpreply);
8050: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8051: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8052: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8053: return $tmp;
1.416 albertel 8054: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8055: $result=undef;
1.599 albertel 8056: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8057: }
8058: }
1.624 albertel 8059: return $result;
8060: }
8061:
1.633 albertel 8062: sub devalidateuserresdata {
8063: my ($uname,$udom)=@_;
8064: my $hashid="$udom:$uname";
8065: &devalidate_cache_new('userres',$hashid);
8066: }
8067:
1.624 albertel 8068: sub get_userresdata {
8069: my ($uname,$udom)=@_;
8070: #most student don\'t have any data set, check if there is some data
8071: if (&EXT_cache_status($udom,$uname)) { return undef; }
8072:
8073: my $hashid="$udom:$uname";
8074: my ($result,$cached)=&is_cached_new('userres',$hashid);
8075: if (!defined($cached)) {
8076: my %resourcedata=&dump('resourcedata',$udom,$uname);
8077: $result=\%resourcedata;
8078: &do_cache_new('userres',$hashid,$result,600);
8079: }
8080: my ($tmp)=keys(%$result);
8081: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8082: return $result;
8083: }
8084: #error 2 occurs when the .db doesn't exist
8085: if ($tmp!~/error: 2 /) {
1.672 albertel 8086: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8087: " Trying to get resource data for ".
8088: $uname." at ".$udom.": ".
8089: $tmp."</font>");
8090: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8091: #&EXT_cache_set($udom,$uname);
8092: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8093: undef($tmp); # not really an error so don't send it back
1.624 albertel 8094: }
8095: return $tmp;
8096: }
1.879 foxr 8097: #----------------------------------------------- resdata - return resource data
8098: # Purpose:
8099: # Return resource data for either users or for a course.
8100: # Parameters:
8101: # $name - Course/user name.
8102: # $domain - Name of the domain the user/course is registered on.
8103: # $type - Type of thing $name is (must be 'course' or 'user'
8104: # @which - Array of names of resources desired.
8105: # Returns:
8106: # The value of the first reasource in @which that is found in the
8107: # resource hash.
8108: # Exceptional Conditions:
8109: # If the $type passed in is not valid (not the string 'course' or
8110: # 'user', an undefined reference is returned.
8111: # If none of the resources are found, an undef is returned
1.624 albertel 8112: sub resdata {
8113: my ($name,$domain,$type,@which)=@_;
8114: my $result;
8115: if ($type eq 'course') {
8116: $result=&get_courseresdata($name,$domain);
8117: } elsif ($type eq 'user') {
8118: $result=&get_userresdata($name,$domain);
8119: }
8120: if (!ref($result)) { return $result; }
1.251 albertel 8121: foreach my $item (@which) {
1.927 albertel 8122: if (defined($result->{$item->[0]})) {
8123: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8124: }
1.250 albertel 8125: }
1.291 albertel 8126: return undef;
1.200 www 8127: }
8128:
1.379 matthew 8129: #
8130: # EXT resource caching routines
8131: #
8132:
8133: sub clear_EXT_cache_status {
1.383 albertel 8134: &delenv('cache.EXT.');
1.379 matthew 8135: }
8136:
8137: sub EXT_cache_status {
8138: my ($target_domain,$target_user) = @_;
1.383 albertel 8139: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8140: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8141: # We know already the user has no data
8142: return 1;
8143: } else {
8144: return 0;
8145: }
8146: }
8147:
8148: sub EXT_cache_set {
8149: my ($target_domain,$target_user) = @_;
1.383 albertel 8150: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8151: #&appenv({$cachename => time});
1.379 matthew 8152: }
8153:
1.28 www 8154: # --------------------------------------------------------- Value of a Variable
1.58 www 8155: sub EXT {
1.715 albertel 8156:
1.395 albertel 8157: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8158: unless ($varname) { return ''; }
1.218 albertel 8159: #get real user name/domain, courseid and symb
8160: my $courseid;
1.359 albertel 8161: my $publicuser;
1.427 www 8162: if ($symbparm) {
8163: $symbparm=&get_symb_from_alias($symbparm);
8164: }
1.218 albertel 8165: if (!($uname && $udom)) {
1.790 albertel 8166: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8167: if (!$symbparm) { $symbparm=$cursymb; }
8168: } else {
1.620 albertel 8169: $courseid=$env{'request.course.id'};
1.218 albertel 8170: }
1.48 www 8171: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8172: my $rest;
1.320 albertel 8173: if (defined($therest[0])) {
1.48 www 8174: $rest=join('.',@therest);
8175: } else {
8176: $rest='';
8177: }
1.320 albertel 8178:
1.57 www 8179: my $qualifierrest=$qualifier;
8180: if ($rest) { $qualifierrest.='.'.$rest; }
8181: my $spacequalifierrest=$space;
8182: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8183: if ($realm eq 'user') {
1.48 www 8184: # --------------------------------------------------------------- user.resource
8185: if ($space eq 'resource') {
1.651 albertel 8186: if ( (defined($Apache::lonhomework::parsing_a_problem)
8187: || defined($Apache::lonhomework::parsing_a_task))
8188: &&
1.744 albertel 8189: ($symbparm eq &symbread()) ) {
8190: # if we are in the middle of processing the resource the
8191: # get the value we are planning on committing
8192: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8193: return $Apache::lonhomework::results{$qualifierrest};
8194: } else {
8195: return $Apache::lonhomework::history{$qualifierrest};
8196: }
1.335 albertel 8197: } else {
1.359 albertel 8198: my %restored;
1.620 albertel 8199: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8200: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8201: } else {
8202: %restored=&restore($symbparm,$courseid,$udom,$uname);
8203: }
1.335 albertel 8204: return $restored{$qualifierrest};
8205: }
1.48 www 8206: # ----------------------------------------------------------------- user.access
8207: } elsif ($space eq 'access') {
1.218 albertel 8208: # FIXME - not supporting calls for a specific user
1.48 www 8209: return &allowed($qualifier,$rest);
8210: # ------------------------------------------ user.preferences, user.environment
8211: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8212: if (($uname eq $env{'user.name'}) &&
8213: ($udom eq $env{'user.domain'})) {
8214: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8215: } else {
1.359 albertel 8216: my %returnhash;
8217: if (!$publicuser) {
8218: %returnhash=&userenvironment($udom,$uname,
8219: $qualifierrest);
8220: }
1.218 albertel 8221: return $returnhash{$qualifierrest};
8222: }
1.48 www 8223: # ----------------------------------------------------------------- user.course
8224: } elsif ($space eq 'course') {
1.218 albertel 8225: # FIXME - not supporting calls for a specific user
1.620 albertel 8226: return $env{join('.',('request.course',$qualifier))};
1.48 www 8227: # ------------------------------------------------------------------- user.role
8228: } elsif ($space eq 'role') {
1.218 albertel 8229: # FIXME - not supporting calls for a specific user
1.620 albertel 8230: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8231: if ($qualifier eq 'value') {
8232: return $role;
8233: } elsif ($qualifier eq 'extent') {
8234: return $where;
8235: }
8236: # ----------------------------------------------------------------- user.domain
8237: } elsif ($space eq 'domain') {
1.218 albertel 8238: return $udom;
1.48 www 8239: # ------------------------------------------------------------------- user.name
8240: } elsif ($space eq 'name') {
1.218 albertel 8241: return $uname;
1.48 www 8242: # ---------------------------------------------------- Any other user namespace
1.29 www 8243: } else {
1.359 albertel 8244: my %reply;
8245: if (!$publicuser) {
8246: %reply=&get($space,[$qualifierrest],$udom,$uname);
8247: }
8248: return $reply{$qualifierrest};
1.48 www 8249: }
1.236 www 8250: } elsif ($realm eq 'query') {
8251: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8252: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8253: [$spacequalifierrest]);
1.620 albertel 8254: return $env{'form.'.$spacequalifierrest};
1.236 www 8255: } elsif ($realm eq 'request') {
1.48 www 8256: # ------------------------------------------------------------- request.browser
8257: if ($space eq 'browser') {
1.430 www 8258: if ($qualifier eq 'textremote') {
1.676 albertel 8259: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8260: return 1;
8261: } else {
8262: return 0;
8263: }
8264: } else {
1.620 albertel 8265: return $env{'browser.'.$qualifier};
1.430 www 8266: }
1.57 www 8267: # ------------------------------------------------------------ request.filename
8268: } else {
1.620 albertel 8269: return $env{'request.'.$spacequalifierrest};
1.29 www 8270: }
1.28 www 8271: } elsif ($realm eq 'course') {
1.48 www 8272: # ---------------------------------------------------------- course.description
1.620 albertel 8273: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8274: } elsif ($realm eq 'resource') {
1.165 www 8275:
1.620 albertel 8276: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8277: if (!$symbparm) { $symbparm=&symbread(); }
8278: }
1.693 albertel 8279:
8280: if ($space eq 'title') {
8281: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8282: return &gettitle($symbparm);
8283: }
8284:
8285: if ($space eq 'map') {
8286: my ($map) = &decode_symb($symbparm);
8287: return &symbread($map);
8288: }
1.905 albertel 8289: if ($space eq 'filename') {
8290: if ($symbparm) {
8291: return &clutter((&decode_symb($symbparm))[2]);
8292: }
8293: return &hreflocation('',$env{'request.filename'});
8294: }
1.693 albertel 8295:
8296: my ($section, $group, @groups);
1.593 albertel 8297: my ($courselevelm,$courselevel);
1.539 albertel 8298: if ($symbparm && defined($courseid) &&
1.620 albertel 8299: $courseid eq $env{'request.course.id'}) {
1.165 www 8300:
1.218 albertel 8301: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8302:
1.60 www 8303: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8304: my $symbp=$symbparm;
1.735 albertel 8305: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8306:
8307: my $symbparm=$symbp.'.'.$spacequalifierrest;
8308: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8309:
1.620 albertel 8310: if (($env{'user.name'} eq $uname) &&
8311: ($env{'user.domain'} eq $udom)) {
8312: $section=$env{'request.course.sec'};
1.733 raeburn 8313: @groups = split(/:/,$env{'request.course.groups'});
8314: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8315: } else {
1.539 albertel 8316: if (! defined($usection)) {
1.551 albertel 8317: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8318: } else {
8319: $section = $usection;
8320: }
1.733 raeburn 8321: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8322: }
8323:
8324: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8325: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8326: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8327:
1.593 albertel 8328: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8329: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8330: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8331:
1.60 www 8332: # ----------------------------------------------------------- first, check user
1.624 albertel 8333:
8334: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8335: ([$courselevelr,'resource'],
8336: [$courselevelm,'map' ],
8337: [$courselevel, 'course' ]));
1.931 albertel 8338: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8339:
1.594 albertel 8340: # ------------------------------------------------ second, check some of course
1.684 raeburn 8341: my $coursereply;
1.691 raeburn 8342: if (@groups > 0) {
8343: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8344: $mapparm,$spacequalifierrest);
1.927 albertel 8345: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8346: }
1.96 www 8347:
1.684 raeburn 8348: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8349: $env{'course.'.$courseid.'.domain'},
8350: 'course',
8351: ([$seclevelr, 'resource'],
8352: [$seclevelm, 'map' ],
8353: [$seclevel, 'course' ],
8354: [$courselevelr,'resource']));
8355: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8356:
1.60 www 8357: # ------------------------------------------------------ third, check map parms
1.218 albertel 8358: my %parmhash=();
8359: my $thisparm='';
8360: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8361: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8362: &GDBM_READER(),0640)) {
1.218 albertel 8363: $thisparm=$parmhash{$symbparm};
8364: untie(%parmhash);
8365: }
1.927 albertel 8366: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8367: }
1.594 albertel 8368: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8369:
1.218 albertel 8370: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8371: my $filename;
8372: if (!$symbparm) { $symbparm=&symbread(); }
8373: if ($symbparm) {
1.409 www 8374: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8375: } else {
1.620 albertel 8376: $filename=$env{'request.filename'};
1.282 albertel 8377: }
8378: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8379: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8380: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8381: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8382:
1.927 albertel 8383: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8384: if ($symbparm && defined($courseid) &&
1.620 albertel 8385: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8386: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8387: $env{'course.'.$courseid.'.domain'},
8388: 'course',
1.927 albertel 8389: ([$courselevelm,'map' ],
8390: [$courselevel, 'course']));
8391: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8392: }
1.145 www 8393: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8394: unless ($space eq '0') {
1.336 albertel 8395: my @parts=split(/_/,$space);
8396: my $id=pop(@parts);
8397: my $part=join('_',@parts);
8398: if ($part eq '') { $part='0'; }
1.927 albertel 8399: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8400: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8401: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8402: }
1.395 albertel 8403: if ($recurse) { return undef; }
8404: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8405: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8406: # ---------------------------------------------------- Any other user namespace
8407: } elsif ($realm eq 'environment') {
8408: # ----------------------------------------------------------------- environment
1.620 albertel 8409: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8410: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8411: } else {
1.770 albertel 8412: if ($uname eq 'anonymous' && $udom eq '') {
8413: return '';
8414: }
1.219 albertel 8415: my %returnhash=&userenvironment($udom,$uname,
8416: $spacequalifierrest);
8417: return $returnhash{$spacequalifierrest};
8418: }
1.28 www 8419: } elsif ($realm eq 'system') {
1.48 www 8420: # ----------------------------------------------------------------- system.time
8421: if ($space eq 'time') {
8422: return time;
8423: }
1.696 albertel 8424: } elsif ($realm eq 'server') {
8425: # ----------------------------------------------------------------- system.time
8426: if ($space eq 'name') {
8427: return $ENV{'SERVER_NAME'};
8428: }
1.28 www 8429: }
1.48 www 8430: return '';
1.61 www 8431: }
8432:
1.927 albertel 8433: sub get_reply {
8434: my ($reply_value) = @_;
1.940 raeburn 8435: if (ref($reply_value) eq 'ARRAY') {
8436: if (wantarray) {
8437: return @$reply_value;
8438: }
8439: return $reply_value->[0];
8440: } else {
8441: return $reply_value;
1.927 albertel 8442: }
8443: }
8444:
1.691 raeburn 8445: sub check_group_parms {
8446: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8447: my @groupitems = ();
8448: my $resultitem;
1.927 albertel 8449: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8450: foreach my $group (@{$groups}) {
8451: foreach my $level (@levels) {
1.927 albertel 8452: my $item = $courseid.'.['.$group.'].'.$level->[0];
8453: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8454: }
8455: }
8456: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8457: $env{'course.'.$courseid.'.domain'},
8458: 'course',@groupitems);
8459: return $coursereply;
8460: }
8461:
8462: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8463: my ($courseid,@groups) = @_;
8464: @groups = sort(@groups);
1.691 raeburn 8465: return @groups;
8466: }
8467:
1.395 albertel 8468: sub packages_tab_default {
8469: my ($uri,$varname)=@_;
8470: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8471:
8472: my (@extension,@specifics,$do_default);
8473: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8474: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8475: if ($pack_type eq 'default') {
8476: $do_default=1;
8477: } elsif ($pack_type eq 'extension') {
8478: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8479: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8480: # only look at packages defaults for packages that this id is
1.738 albertel 8481: push(@specifics,[$package,$pack_type,$pack_part]);
8482: }
8483: }
8484: # first look for a package that matches the requested part id
8485: foreach my $package (@specifics) {
8486: my (undef,$pack_type,$pack_part)=@{$package};
8487: next if ($pack_part ne $part);
8488: if (defined($packagetab{"$pack_type&$name&default"})) {
8489: return $packagetab{"$pack_type&$name&default"};
8490: }
8491: }
8492: # look for any possible matching non extension_ package
8493: foreach my $package (@specifics) {
8494: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8495: if (defined($packagetab{"$pack_type&$name&default"})) {
8496: return $packagetab{"$pack_type&$name&default"};
8497: }
1.585 albertel 8498: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8499: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8500: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8501: }
8502: }
1.738 albertel 8503: # look for any posible extension_ match
8504: foreach my $package (@extension) {
8505: my ($package,$pack_type)=@{$package};
8506: if (defined($packagetab{"$pack_type&$name&default"})) {
8507: return $packagetab{"$pack_type&$name&default"};
8508: }
8509: if (defined($packagetab{$package."&$name&default"})) {
8510: return $packagetab{$package."&$name&default"};
8511: }
8512: }
8513: # look for a global default setting
8514: if ($do_default && defined($packagetab{"default&$name&default"})) {
8515: return $packagetab{"default&$name&default"};
8516: }
1.395 albertel 8517: return undef;
8518: }
8519:
1.334 albertel 8520: sub add_prefix_and_part {
8521: my ($prefix,$part)=@_;
8522: my $keyroot;
8523: if (defined($prefix) && $prefix !~ /^__/) {
8524: # prefix that has a part already
8525: $keyroot=$prefix;
8526: } elsif (defined($prefix)) {
8527: # prefix that is missing a part
8528: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8529: } else {
8530: # no prefix at all
8531: if (defined($part)) { $keyroot='_'.$part; }
8532: }
8533: return $keyroot;
8534: }
8535:
1.71 www 8536: # ---------------------------------------------------------------- Get metadata
8537:
1.599 albertel 8538: my %metaentry;
1.1070 www 8539: my %importedpartids;
1.71 www 8540: sub metadata {
1.176 www 8541: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8542: $uri=&declutter($uri);
1.288 albertel 8543: # if it is a non metadata possible uri return quickly
1.529 albertel 8544: if (($uri eq '') ||
8545: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8546: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1100 raeburn 8547: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$}) || ($uri =~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.924 albertel 8548: return undef;
8549: }
8550: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8551: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8552: return undef;
1.288 albertel 8553: }
1.73 www 8554: my $filename=$uri;
8555: $uri=~s/\.meta$//;
1.172 www 8556: #
8557: # Is the metadata already cached?
1.177 www 8558: # Look at timestamp of caching
1.172 www 8559: # Everything is cached by the main uri, libraries are never directly cached
8560: #
1.428 albertel 8561: if (!defined($liburi)) {
1.599 albertel 8562: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8563: if (defined($cached)) { return $result->{':'.$what}; }
8564: }
8565: {
1.1069 www 8566: # Imported parts would go here
1.1070 www 8567: my %importedids=();
8568: my @origfileimportpartids=();
1.1069 www 8569: my $importedparts=0;
1.172 www 8570: #
8571: # Is this a recursive call for a library?
8572: #
1.599 albertel 8573: # if (! exists($metacache{$uri})) {
8574: # $metacache{$uri}={};
8575: # }
1.924 albertel 8576: my $cachetime = 60*60;
1.171 www 8577: if ($liburi) {
8578: $liburi=&declutter($liburi);
8579: $filename=$liburi;
1.401 bowersj2 8580: } else {
1.599 albertel 8581: &devalidate_cache_new('meta',$uri);
8582: undef(%metaentry);
1.401 bowersj2 8583: }
1.140 www 8584: my %metathesekeys=();
1.73 www 8585: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8586: my $metastring;
1.924 albertel 8587: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8588: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8589: $metastring =
1.929 albertel 8590: &Apache::lonnet::ssi_body($which,
1.924 albertel 8591: ('grade_target' => 'meta'));
8592: $cachetime = 1; # only want this cached in the child not long term
8593: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8594: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8595: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8596: $metastring=&getfile($file);
1.489 albertel 8597: }
1.208 albertel 8598: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8599: my $token;
1.140 www 8600: undef %metathesekeys;
1.71 www 8601: while ($token=$parser->get_token) {
1.339 albertel 8602: if ($token->[0] eq 'S') {
8603: if (defined($token->[2]->{'package'})) {
1.172 www 8604: #
8605: # This is a package - get package info
8606: #
1.339 albertel 8607: my $package=$token->[2]->{'package'};
8608: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8609: if (defined($token->[2]->{'id'})) {
8610: $keyroot.='_'.$token->[2]->{'id'};
8611: }
1.599 albertel 8612: if ($metaentry{':packages'}) {
8613: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8614: } else {
1.599 albertel 8615: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8616: }
1.736 albertel 8617: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8618: my $part=$keyroot;
8619: $part=~s/^\_//;
1.736 albertel 8620: if ($pack_entry=~/^\Q$package\E\&/ ||
8621: $pack_entry=~/^\Q$package\E_0\&/) {
8622: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8623: # ignore package.tab specified default values
8624: # here &package_tab_default() will fetch those
8625: if ($subp eq 'default') { next; }
1.736 albertel 8626: my $value=$packagetab{$pack_entry};
1.432 albertel 8627: my $unikey;
8628: if ($pack =~ /_0$/) {
8629: $unikey='parameter_0_'.$name;
8630: $part=0;
8631: } else {
8632: $unikey='parameter'.$keyroot.'_'.$name;
8633: }
1.339 albertel 8634: if ($subp eq 'display') {
8635: $value.=' [Part: '.$part.']';
8636: }
1.599 albertel 8637: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8638: $metathesekeys{$unikey}=1;
1.599 albertel 8639: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8640: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8641: }
1.599 albertel 8642: if (defined($metaentry{':'.$unikey.'.default'})) {
8643: $metaentry{':'.$unikey}=
8644: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8645: }
1.339 albertel 8646: }
8647: }
8648: } else {
1.172 www 8649: #
8650: # This is not a package - some other kind of start tag
1.339 albertel 8651: #
8652: my $entry=$token->[1];
1.1068 www 8653: my $unikey='';
1.175 www 8654:
1.339 albertel 8655: if ($entry eq 'import') {
1.175 www 8656: #
8657: # Importing a library here
1.339 albertel 8658: #
1.1067 www 8659: my $location=$parser->get_text('/import');
8660: my $dir=$filename;
8661: $dir=~s|[^/]*$||;
8662: $location=&filelocation($dir,$location);
1.1069 www 8663:
1.1068 www 8664: my $importmode=$token->[2]->{'importmode'};
8665: if ($importmode eq 'problem') {
1.1069 www 8666: # Import as problem/response
1.1068 www 8667: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8668: } elsif ($importmode eq 'part') {
8669: # Import as part(s)
1.1069 www 8670: $importedparts=1;
8671: # We need to get the original file and the imported file to get the part order correct
8672: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8673: # Load and inspect original file
1.1070 www 8674: if ($#origfileimportpartids<0) {
8675: undef(%importedpartids);
8676: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8677: my $origfile=&getfile($origfilelocation);
8678: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8679: }
8680:
1.1069 www 8681: # Load and inspect imported file
8682: my $impfile=&getfile($location);
8683: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8684: if ($#impfilepartids>=0) {
8685: # This problem had parts
1.1070 www 8686: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8687: } else {
8688: # Importing by turning a single problem into a problem part
8689: # It gets the import-tags ID as part-ID
8690: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8691: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8692: }
1.1068 www 8693: } else {
8694: # Normal import
8695: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8696: if (defined($token->[2]->{'id'})) {
8697: $unikey.='_'.$token->[2]->{'id'};
8698: }
1.1067 www 8699: }
8700:
1.339 albertel 8701: if ($depthcount<20) {
1.736 albertel 8702: my $metadata =
8703: &metadata($uri,'keys', $location,$unikey,
8704: $depthcount+1);
8705: foreach my $meta (split(',',$metadata)) {
8706: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8707: $metathesekeys{$meta}=1;
1.339 albertel 8708: }
1.1068 www 8709:
8710: }
1.1067 www 8711: } else {
8712: #
8713: # Not importing, some other kind of non-package, non-library start tag
8714: #
8715: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8716: if (defined($token->[2]->{'id'})) {
8717: $unikey.='_'.$token->[2]->{'id'};
8718: }
1.339 albertel 8719: if (defined($token->[2]->{'name'})) {
8720: $unikey.='_'.$token->[2]->{'name'};
8721: }
8722: $metathesekeys{$unikey}=1;
1.736 albertel 8723: foreach my $param (@{$token->[3]}) {
8724: $metaentry{':'.$unikey.'.'.$param} =
8725: $token->[2]->{$param};
1.339 albertel 8726: }
8727: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8728: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8729: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8730: # only ws inside the tag, and not in default, so use default
8731: # as value
1.599 albertel 8732: $metaentry{':'.$unikey}=$default;
1.908 albertel 8733: } elsif ( $internaltext =~ /\S/ ) {
8734: # something interesting inside the tag
8735: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8736: } else {
1.908 albertel 8737: # no interesting values, don't set a default
1.339 albertel 8738: }
1.172 www 8739: # end of not-a-package not-a-library import
1.339 albertel 8740: }
1.172 www 8741: # end of not-a-package start tag
1.339 albertel 8742: }
1.172 www 8743: # the next is the end of "start tag"
1.339 albertel 8744: }
8745: }
1.483 albertel 8746: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8747: $extension = lc($extension);
8748: if ($extension eq 'htm') { $extension='html'; }
8749:
1.737 albertel 8750: foreach my $key (keys(%packagetab)) {
1.483 albertel 8751: #no specific packages #how's our extension
8752: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8753: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8754: \%metathesekeys);
8755: }
1.883 albertel 8756:
8757: if (!exists($metaentry{':packages'})
8758: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8759: foreach my $key (keys(%packagetab)) {
1.483 albertel 8760: #no specific packages well let's get default then
8761: if ($key!~/^default&/) { next; }
1.488 albertel 8762: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8763: \%metathesekeys);
8764: }
8765: }
1.338 www 8766: # are there custom rights to evaluate
1.599 albertel 8767: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8768:
1.338 www 8769: #
8770: # Importing a rights file here
1.339 albertel 8771: #
8772: unless ($depthcount) {
1.599 albertel 8773: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8774: my $dir=$filename;
8775: $dir=~s|[^/]*$||;
8776: $location=&filelocation($dir,$location);
1.736 albertel 8777: my $rights_metadata =
8778: &metadata($uri,'keys',$location,'_rights',
8779: $depthcount+1);
8780: foreach my $rights (split(',',$rights_metadata)) {
8781: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8782: $metathesekeys{$rights}=1;
1.339 albertel 8783: }
8784: }
8785: }
1.737 albertel 8786: # uniqifiy package listing
8787: my %seen;
8788: my @uniq_packages =
8789: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8790: $metaentry{':packages'} = join(',',@uniq_packages);
8791:
1.1070 www 8792: if ($importedparts) {
8793: # We had imported parts and need to rebuild partorder
8794: $metaentry{':partorder'}='';
8795: $metathesekeys{'partorder'}=1;
8796: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8797: if ($origfileimportpartids[$index] eq 'part') {
8798: # original part, part of the problem
8799: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8800: } else {
8801: # we have imported parts at this position
8802: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8803: }
8804: }
8805: $metaentry{':partorder'}=~s/^\,//;
8806: }
8807:
1.737 albertel 8808: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8809: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8810: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8811: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8812: # this is the end of "was not already recently cached
1.71 www 8813: }
1.599 albertel 8814: return $metaentry{':'.$what};
1.261 albertel 8815: }
8816:
1.488 albertel 8817: sub metadata_create_package_def {
1.483 albertel 8818: my ($uri,$key,$package,$metathesekeys)=@_;
8819: my ($pack,$name,$subp)=split(/\&/,$key);
8820: if ($subp eq 'default') { next; }
8821:
1.599 albertel 8822: if (defined($metaentry{':packages'})) {
8823: $metaentry{':packages'}.=','.$package;
1.483 albertel 8824: } else {
1.599 albertel 8825: $metaentry{':packages'}=$package;
1.483 albertel 8826: }
8827: my $value=$packagetab{$key};
8828: my $unikey;
8829: $unikey='parameter_0_'.$name;
1.599 albertel 8830: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8831: $$metathesekeys{$unikey}=1;
1.599 albertel 8832: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8833: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8834: }
1.599 albertel 8835: if (defined($metaentry{':'.$unikey.'.default'})) {
8836: $metaentry{':'.$unikey}=
8837: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8838: }
8839: }
8840:
1.261 albertel 8841: sub metadata_generate_part0 {
8842: my ($metadata,$metacache,$uri) = @_;
8843: my %allnames;
1.737 albertel 8844: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8845: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8846: my $part=$$metacache{':'.$metakey.'.part'};
8847: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8848: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8849: $allnames{$name}=$part;
8850: }
8851: }
8852: }
8853: foreach my $name (keys(%allnames)) {
8854: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8855: my $key=":parameter_0_$name";
1.261 albertel 8856: $$metacache{"$key.part"}='0';
8857: $$metacache{"$key.name"}=$name;
1.428 albertel 8858: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8859: $allnames{$name}.'_'.$name.
8860: '.type'};
1.428 albertel 8861: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8862: '.display'};
1.644 www 8863: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8864: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8865: $$metacache{"$key.display"}=$olddis;
8866: }
1.71 www 8867: }
8868:
1.764 albertel 8869: # ------------------------------------------------------ Devalidate title cache
8870:
8871: sub devalidate_title_cache {
8872: my ($url)=@_;
8873: if (!$env{'request.course.id'}) { return; }
8874: my $symb=&symbread($url);
8875: if (!$symb) { return; }
8876: my $key=$env{'request.course.id'}."\0".$symb;
8877: &devalidate_cache_new('title',$key);
8878: }
8879:
1.1014 droeschl 8880: # ------------------------------------------------- Get the title of a course
8881:
8882: sub current_course_title {
8883: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8884: }
1.301 www 8885: # ------------------------------------------------- Get the title of a resource
8886:
8887: sub gettitle {
8888: my $urlsymb=shift;
8889: my $symb=&symbread($urlsymb);
1.534 albertel 8890: if ($symb) {
1.620 albertel 8891: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8892: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8893: if (defined($cached)) {
8894: return $result;
8895: }
1.534 albertel 8896: my ($map,$resid,$url)=&decode_symb($symb);
8897: my $title='';
1.907 albertel 8898: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8899: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8900: } else {
8901: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8902: &GDBM_READER(),0640)) {
8903: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8904: $title=$bighash{'title_'.$mapid.'.'.$resid};
8905: untie(%bighash);
8906: }
1.534 albertel 8907: }
8908: $title=~s/\&colon\;/\:/gs;
8909: if ($title) {
1.599 albertel 8910: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8911: }
8912: $urlsymb=$url;
8913: }
8914: my $title=&metadata($urlsymb,'title');
8915: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8916: return $title;
1.301 www 8917: }
1.613 albertel 8918:
1.614 albertel 8919: sub get_slot {
8920: my ($which,$cnum,$cdom)=@_;
8921: if (!$cnum || !$cdom) {
1.790 albertel 8922: (undef,my $courseid)=&whichuser();
1.620 albertel 8923: $cdom=$env{'course.'.$courseid.'.domain'};
8924: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8925: }
1.703 albertel 8926: my $key=join("\0",'slots',$cdom,$cnum,$which);
8927: my %slotinfo;
8928: if (exists($remembered{$key})) {
8929: $slotinfo{$which} = $remembered{$key};
8930: } else {
8931: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8932: &Apache::lonhomework::showhash(%slotinfo);
8933: my ($tmp)=keys(%slotinfo);
8934: if ($tmp=~/^error:/) { return (); }
8935: $remembered{$key} = $slotinfo{$which};
8936: }
1.616 albertel 8937: if (ref($slotinfo{$which}) eq 'HASH') {
8938: return %{$slotinfo{$which}};
8939: }
8940: return $slotinfo{$which};
1.614 albertel 8941: }
1.31 www 8942: # ------------------------------------------------- Update symbolic store links
8943:
8944: sub symblist {
8945: my ($mapname,%newhash)=@_;
1.438 www 8946: $mapname=&deversion(&declutter($mapname));
1.31 www 8947: my %hash;
1.620 albertel 8948: if (($env{'request.course.fn'}) && (%newhash)) {
8949: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8950: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8951: foreach my $url (keys(%newhash)) {
1.711 albertel 8952: next if ($url eq 'last_known'
8953: && $env{'form.no_update_last_known'});
8954: $hash{declutter($url)}=&encode_symb($mapname,
8955: $newhash{$url}->[1],
8956: $newhash{$url}->[0]);
1.191 harris41 8957: }
1.31 www 8958: if (untie(%hash)) {
8959: return 'ok';
8960: }
8961: }
8962: }
8963: return 'error';
1.212 www 8964: }
8965:
8966: # --------------------------------------------------------------- Verify a symb
8967:
8968: sub symbverify {
1.510 www 8969: my ($symb,$thisurl)=@_;
8970: my $thisfn=$thisurl;
1.439 www 8971: $thisfn=&declutter($thisfn);
1.215 www 8972: # direct jump to resource in page or to a sequence - will construct own symbs
8973: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8974: # check URL part
1.409 www 8975: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8976:
1.431 www 8977: unless ($url eq $thisfn) { return 0; }
1.213 www 8978:
1.216 www 8979: $symb=&symbclean($symb);
1.510 www 8980: $thisurl=&deversion($thisurl);
1.439 www 8981: $thisfn=&deversion($thisfn);
1.213 www 8982:
8983: my %bighash;
8984: my $okay=0;
1.431 www 8985:
1.620 albertel 8986: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8987: &GDBM_READER(),0640)) {
1.1032 raeburn 8988: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8989: $thisurl =~ s/\?.+$//;
8990: }
1.510 www 8991: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 8992: unless ($ids) {
8993: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
8994: $ids=$bighash{$idkey};
1.216 www 8995: }
8996: if ($ids) {
8997: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8998: foreach my $id (split(/\,/,$ids)) {
8999: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9000: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9001: $symb =~ s/\?.+$//;
9002: }
1.216 www 9003: if (
9004: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9005: eq $symb) {
1.620 albertel 9006: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9007: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9008: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9009: $okay=1;
9010: }
9011: }
1.216 www 9012: }
9013: }
1.213 www 9014: untie(%bighash);
9015: }
9016: return $okay;
1.31 www 9017: }
9018:
1.210 www 9019: # --------------------------------------------------------------- Clean-up symb
9020:
9021: sub symbclean {
9022: my $symb=shift;
1.568 albertel 9023: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9024: # remove version from map
9025: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9026:
1.210 www 9027: # remove version from URL
9028: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9029:
1.507 www 9030: # remove wrapper
9031:
1.510 www 9032: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9033: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9034: return $symb;
1.409 www 9035: }
9036:
9037: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9038:
9039: sub encode_symb {
9040: my ($map,$resid,$url)=@_;
9041: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9042: }
1.409 www 9043:
9044: sub decode_symb {
1.568 albertel 9045: my $symb=shift;
9046: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9047: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9048: return (&fixversion($map),$resid,&fixversion($url));
9049: }
9050:
9051: sub fixversion {
9052: my $fn=shift;
1.609 banghart 9053: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9054: my %bighash;
9055: my $uri=&clutter($fn);
1.620 albertel 9056: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9057: # is this cached?
1.599 albertel 9058: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9059: if (defined($cached)) { return $result; }
9060: # unfortunately not cached, or expired
1.620 albertel 9061: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9062: &GDBM_READER(),0640)) {
9063: if ($bighash{'version_'.$uri}) {
9064: my $version=$bighash{'version_'.$uri};
1.444 www 9065: unless (($version eq 'mostrecent') ||
9066: ($version==&getversion($uri))) {
1.440 www 9067: $uri=~s/\.(\w+)$/\.$version\.$1/;
9068: }
9069: }
9070: untie %bighash;
1.413 www 9071: }
1.599 albertel 9072: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9073: }
9074:
9075: sub deversion {
9076: my $url=shift;
9077: $url=~s/\.\d+\.(\w+)$/\.$1/;
9078: return $url;
1.210 www 9079: }
9080:
1.31 www 9081: # ------------------------------------------------------ Return symb list entry
9082:
9083: sub symbread {
1.249 www 9084: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9085: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9086: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9087: # no filename provided? try from environment
1.44 www 9088: unless ($thisfn) {
1.620 albertel 9089: if ($env{'request.symb'}) {
9090: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9091: }
1.620 albertel 9092: $thisfn=$env{'request.filename'};
1.44 www 9093: }
1.569 albertel 9094: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9095: # is that filename actually a symb? Verify, clean, and return
9096: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9097: if (&symbverify($thisfn,$1)) {
1.620 albertel 9098: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9099: }
1.242 www 9100: }
1.44 www 9101: $thisfn=declutter($thisfn);
1.31 www 9102: my %hash;
1.37 www 9103: my %bighash;
9104: my $syval='';
1.620 albertel 9105: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9106: my $targetfn = $thisfn;
1.609 banghart 9107: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9108: $targetfn = 'adm/wrapper/'.$thisfn;
9109: }
1.687 albertel 9110: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9111: $targetfn=$1;
9112: }
1.620 albertel 9113: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9114: &GDBM_READER(),0640)) {
1.481 raeburn 9115: $syval=$hash{$targetfn};
1.37 www 9116: untie(%hash);
9117: }
9118: # ---------------------------------------------------------- There was an entry
9119: if ($syval) {
1.601 albertel 9120: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9121: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9122: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9123: #return $env{$cache_str}='';
1.601 albertel 9124: #}
9125: #$syval.=$1;
9126: #}
1.37 www 9127: } else {
9128: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9129: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9130: &GDBM_READER(),0640)) {
1.37 www 9131: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9132: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9133: unless ($ids) {
9134: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9135: }
9136: unless ($ids) {
9137: # alias?
9138: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9139: }
1.37 www 9140: if ($ids) {
9141: # ------------------------------------------------------------------- Has ID(s)
9142: my @possibilities=split(/\,/,$ids);
1.39 www 9143: if ($#possibilities==0) {
9144: # ----------------------------------------------- There is only one possibility
1.37 www 9145: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9146: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9147: $resid,$thisfn);
1.249 www 9148: } elsif (!$donotrecurse) {
1.39 www 9149: # ------------------------------------------ There is more than one possibility
9150: my $realpossible=0;
1.800 albertel 9151: foreach my $id (@possibilities) {
9152: my $file=$bighash{'src_'.$id};
1.39 www 9153: if (&allowed('bre',$file)) {
1.800 albertel 9154: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9155: if ($bighash{'map_type_'.$mapid} ne 'page') {
9156: $realpossible++;
1.626 albertel 9157: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9158: $resid,$thisfn);
1.39 www 9159: }
9160: }
1.191 harris41 9161: }
1.39 www 9162: if ($realpossible!=1) { $syval=''; }
1.249 www 9163: } else {
9164: $syval='';
1.37 www 9165: }
9166: }
9167: untie(%bighash)
1.481 raeburn 9168: }
1.31 www 9169: }
1.62 www 9170: if ($syval) {
1.620 albertel 9171: return $env{$cache_str}=$syval;
1.62 www 9172: }
1.31 www 9173: }
1.949 raeburn 9174: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9175: return $env{$cache_str}='';
1.31 www 9176: }
9177:
9178: # ---------------------------------------------------------- Return random seed
9179:
1.32 www 9180: sub numval {
9181: my $txt=shift;
9182: $txt=~tr/A-J/0-9/;
9183: $txt=~tr/a-j/0-9/;
9184: $txt=~tr/K-T/0-9/;
9185: $txt=~tr/k-t/0-9/;
9186: $txt=~tr/U-Z/0-5/;
9187: $txt=~tr/u-z/0-5/;
9188: $txt=~s/\D//g;
1.564 albertel 9189: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9190: return int($txt);
1.368 albertel 9191: }
9192:
1.484 albertel 9193: sub numval2 {
9194: my $txt=shift;
9195: $txt=~tr/A-J/0-9/;
9196: $txt=~tr/a-j/0-9/;
9197: $txt=~tr/K-T/0-9/;
9198: $txt=~tr/k-t/0-9/;
9199: $txt=~tr/U-Z/0-5/;
9200: $txt=~tr/u-z/0-5/;
9201: $txt=~s/\D//g;
9202: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9203: my $total;
9204: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9205: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9206: return int($total);
9207: }
9208:
1.575 albertel 9209: sub numval3 {
9210: use integer;
9211: my $txt=shift;
9212: $txt=~tr/A-J/0-9/;
9213: $txt=~tr/a-j/0-9/;
9214: $txt=~tr/K-T/0-9/;
9215: $txt=~tr/k-t/0-9/;
9216: $txt=~tr/U-Z/0-5/;
9217: $txt=~tr/u-z/0-5/;
9218: $txt=~s/\D//g;
9219: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9220: my $total;
9221: foreach my $val (@txts) { $total+=$val; }
9222: if ($_64bit) { $total=(($total<<32)>>32); }
9223: return $total;
9224: }
9225:
1.675 albertel 9226: sub digest {
9227: my ($data)=@_;
9228: my $digest=&Digest::MD5::md5($data);
9229: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9230: my ($e,$f);
9231: {
9232: use integer;
9233: $e=($a+$b);
9234: $f=($c+$d);
9235: if ($_64bit) {
9236: $e=(($e<<32)>>32);
9237: $f=(($f<<32)>>32);
9238: }
9239: }
9240: if (wantarray) {
9241: return ($e,$f);
9242: } else {
9243: my $g;
9244: {
9245: use integer;
9246: $g=($e+$f);
9247: if ($_64bit) {
9248: $g=(($g<<32)>>32);
9249: }
9250: }
9251: return $g;
9252: }
9253: }
9254:
1.368 albertel 9255: sub latest_rnd_algorithm_id {
1.675 albertel 9256: return '64bit5';
1.366 albertel 9257: }
1.32 www 9258:
1.503 albertel 9259: sub get_rand_alg {
9260: my ($courseid)=@_;
1.790 albertel 9261: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9262: if ($courseid) {
1.620 albertel 9263: return $env{"course.$courseid.rndseed"};
1.503 albertel 9264: }
9265: return &latest_rnd_algorithm_id();
9266: }
9267:
1.562 albertel 9268: sub validCODE {
9269: my ($CODE)=@_;
9270: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9271: return 0;
9272: }
9273:
1.491 albertel 9274: sub getCODE {
1.620 albertel 9275: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9276: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9277: defined($Apache::lonhomework::parsing_a_task) ) &&
9278: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9279: return $Apache::lonhomework::history{'resource.CODE'};
9280: }
9281: return undef;
9282: }
9283:
1.31 www 9284: sub rndseed {
1.155 albertel 9285: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9286: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9287: if (!defined($symb)) {
1.366 albertel 9288: unless ($symb=$wsymb) { return time; }
9289: }
9290: if (!$courseid) { $courseid=$wcourseid; }
9291: if (!$domain) { $domain=$wdomain; }
9292: if (!$username) { $username=$wusername }
1.503 albertel 9293: my $which=&get_rand_alg();
1.803 albertel 9294:
1.491 albertel 9295: if (defined(&getCODE())) {
1.675 albertel 9296: if ($which eq '64bit5') {
9297: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9298: } elsif ($which eq '64bit4') {
1.575 albertel 9299: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9300: } else {
9301: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9302: }
1.675 albertel 9303: } elsif ($which eq '64bit5') {
9304: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9305: } elsif ($which eq '64bit4') {
9306: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9307: } elsif ($which eq '64bit3') {
9308: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9309: } elsif ($which eq '64bit2') {
9310: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9311: } elsif ($which eq '64bit') {
9312: return &rndseed_64bit($symb,$courseid,$domain,$username);
9313: }
9314: return &rndseed_32bit($symb,$courseid,$domain,$username);
9315: }
9316:
9317: sub rndseed_32bit {
9318: my ($symb,$courseid,$domain,$username)=@_;
9319: {
9320: use integer;
9321: my $symbchck=unpack("%32C*",$symb) << 27;
9322: my $symbseed=numval($symb) << 22;
9323: my $namechck=unpack("%32C*",$username) << 17;
9324: my $nameseed=numval($username) << 12;
9325: my $domainseed=unpack("%32C*",$domain) << 7;
9326: my $courseseed=unpack("%32C*",$courseid);
9327: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9328: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9329: #&logthis("rndseed :$num:$symb");
1.564 albertel 9330: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9331: return $num;
9332: }
9333: }
9334:
9335: sub rndseed_64bit {
9336: my ($symb,$courseid,$domain,$username)=@_;
9337: {
9338: use integer;
9339: my $symbchck=unpack("%32S*",$symb) << 21;
9340: my $symbseed=numval($symb) << 10;
9341: my $namechck=unpack("%32S*",$username);
9342:
9343: my $nameseed=numval($username) << 21;
9344: my $domainseed=unpack("%32S*",$domain) << 10;
9345: my $courseseed=unpack("%32S*",$courseid);
9346:
9347: my $num1=$symbchck+$symbseed+$namechck;
9348: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9349: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9350: #&logthis("rndseed :$num:$symb");
1.564 albertel 9351: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9352: return "$num1,$num2";
1.155 albertel 9353: }
1.366 albertel 9354: }
9355:
1.443 albertel 9356: sub rndseed_64bit2 {
9357: my ($symb,$courseid,$domain,$username)=@_;
9358: {
9359: use integer;
9360: # strings need to be an even # of cahracters long, it it is odd the
9361: # last characters gets thrown away
9362: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9363: my $symbseed=numval($symb) << 10;
9364: my $namechck=unpack("%32S*",$username.' ');
9365:
9366: my $nameseed=numval($username) << 21;
1.501 albertel 9367: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9368: my $courseseed=unpack("%32S*",$courseid.' ');
9369:
9370: my $num1=$symbchck+$symbseed+$namechck;
9371: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9372: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9373: #&logthis("rndseed :$num:$symb");
1.803 albertel 9374: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9375: return "$num1,$num2";
9376: }
9377: }
9378:
9379: sub rndseed_64bit3 {
9380: my ($symb,$courseid,$domain,$username)=@_;
9381: {
9382: use integer;
9383: # strings need to be an even # of cahracters long, it it is odd the
9384: # last characters gets thrown away
9385: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9386: my $symbseed=numval2($symb) << 10;
9387: my $namechck=unpack("%32S*",$username.' ');
9388:
9389: my $nameseed=numval2($username) << 21;
1.443 albertel 9390: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9391: my $courseseed=unpack("%32S*",$courseid.' ');
9392:
9393: my $num1=$symbchck+$symbseed+$namechck;
9394: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9395: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9396: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9397: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9398:
1.503 albertel 9399: return "$num1:$num2";
1.443 albertel 9400: }
9401: }
9402:
1.575 albertel 9403: sub rndseed_64bit4 {
9404: my ($symb,$courseid,$domain,$username)=@_;
9405: {
9406: use integer;
9407: # strings need to be an even # of cahracters long, it it is odd the
9408: # last characters gets thrown away
9409: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9410: my $symbseed=numval3($symb) << 10;
9411: my $namechck=unpack("%32S*",$username.' ');
9412:
9413: my $nameseed=numval3($username) << 21;
9414: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9415: my $courseseed=unpack("%32S*",$courseid.' ');
9416:
9417: my $num1=$symbchck+$symbseed+$namechck;
9418: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9419: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9420: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9421: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9422:
9423: return "$num1:$num2";
9424: }
9425: }
9426:
1.675 albertel 9427: sub rndseed_64bit5 {
9428: my ($symb,$courseid,$domain,$username)=@_;
9429: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9430: return "$num1:$num2";
9431: }
9432:
1.366 albertel 9433: sub rndseed_CODE_64bit {
9434: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9435: {
1.366 albertel 9436: use integer;
1.443 albertel 9437: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9438: my $symbseed=numval2($symb);
1.491 albertel 9439: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9440: my $CODEseed=numval(&getCODE());
1.443 albertel 9441: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9442: my $num1=$symbseed+$CODEchck;
9443: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9444: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9445: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9446: if ($_64bit) { $num1=(($num1<<32)>>32); }
9447: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9448: return "$num1:$num2";
1.366 albertel 9449: }
9450: }
9451:
1.575 albertel 9452: sub rndseed_CODE_64bit4 {
9453: my ($symb,$courseid,$domain,$username)=@_;
9454: {
9455: use integer;
9456: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9457: my $symbseed=numval3($symb);
9458: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9459: my $CODEseed=numval3(&getCODE());
9460: my $courseseed=unpack("%32S*",$courseid.' ');
9461: my $num1=$symbseed+$CODEchck;
9462: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9463: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9464: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9465: if ($_64bit) { $num1=(($num1<<32)>>32); }
9466: if ($_64bit) { $num2=(($num2<<32)>>32); }
9467: return "$num1:$num2";
9468: }
9469: }
9470:
1.675 albertel 9471: sub rndseed_CODE_64bit5 {
9472: my ($symb,$courseid,$domain,$username)=@_;
9473: my $code = &getCODE();
9474: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9475: return "$num1:$num2";
9476: }
9477:
1.366 albertel 9478: sub setup_random_from_rndseed {
9479: my ($rndseed)=@_;
1.503 albertel 9480: if ($rndseed =~/([,:])/) {
9481: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9482: &Math::Random::random_set_seed(abs($num1),abs($num2));
9483: } else {
9484: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9485: }
1.36 albertel 9486: }
9487:
1.474 albertel 9488: sub latest_receipt_algorithm_id {
1.835 albertel 9489: return 'receipt3';
1.474 albertel 9490: }
9491:
1.480 www 9492: sub recunique {
9493: my $fucourseid=shift;
9494: my $unique;
1.835 albertel 9495: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9496: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9497: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9498: } else {
9499: $unique=$perlvar{'lonReceipt'};
9500: }
9501: return unpack("%32C*",$unique);
9502: }
9503:
9504: sub recprefix {
9505: my $fucourseid=shift;
9506: my $prefix;
1.835 albertel 9507: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9508: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9509: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9510: } else {
9511: $prefix=$perlvar{'lonHostID'};
9512: }
9513: return unpack("%32C*",$prefix);
9514: }
9515:
1.76 www 9516: sub ireceipt {
1.474 albertel 9517: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9518:
9519: my $return =&recprefix($fucourseid).'-';
9520:
9521: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9522: $env{'request.state'} eq 'construct') {
9523: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9524: return $return;
9525: }
9526:
1.76 www 9527: my $cuname=unpack("%32C*",$funame);
9528: my $cudom=unpack("%32C*",$fudom);
9529: my $cucourseid=unpack("%32C*",$fucourseid);
9530: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9531: my $cunique=&recunique($fucourseid);
1.474 albertel 9532: my $cpart=unpack("%32S*",$part);
1.835 albertel 9533: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9534:
1.790 albertel 9535: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9536:
9537: $return.= ($cunique%$cuname+
9538: $cunique%$cudom+
9539: $cusymb%$cuname+
9540: $cusymb%$cudom+
9541: $cucourseid%$cuname+
9542: $cucourseid%$cudom+
9543: $cpart%$cuname+
9544: $cpart%$cudom);
9545: } else {
9546: $return.= ($cunique%$cuname+
9547: $cunique%$cudom+
9548: $cusymb%$cuname+
9549: $cusymb%$cudom+
9550: $cucourseid%$cuname+
9551: $cucourseid%$cudom);
9552: }
9553: return $return;
1.76 www 9554: }
9555:
9556: sub receipt {
1.474 albertel 9557: my ($part)=@_;
1.790 albertel 9558: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9559: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9560: }
1.260 ng 9561:
1.790 albertel 9562: sub whichuser {
9563: my ($passedsymb)=@_;
9564: my ($symb,$courseid,$domain,$name,$publicuser);
9565: if (defined($env{'form.grade_symb'})) {
9566: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9567: my $allowed=&allowed('vgr',$tmp_courseid);
9568: if (!$allowed &&
9569: exists($env{'request.course.sec'}) &&
9570: $env{'request.course.sec'} !~ /^\s*$/) {
9571: $allowed=&allowed('vgr',$tmp_courseid.
9572: '/'.$env{'request.course.sec'});
9573: }
9574: if ($allowed) {
9575: ($symb)=&get_env_multiple('form.grade_symb');
9576: $courseid=$tmp_courseid;
9577: ($domain)=&get_env_multiple('form.grade_domain');
9578: ($name)=&get_env_multiple('form.grade_username');
9579: return ($symb,$courseid,$domain,$name,$publicuser);
9580: }
9581: }
9582: if (!$passedsymb) {
9583: $symb=&symbread();
9584: } else {
9585: $symb=$passedsymb;
9586: }
9587: $courseid=$env{'request.course.id'};
9588: $domain=$env{'user.domain'};
9589: $name=$env{'user.name'};
9590: if ($name eq 'public' && $domain eq 'public') {
9591: if (!defined($env{'form.username'})) {
9592: $env{'form.username'}.=time.rand(10000000);
9593: }
9594: $name.=$env{'form.username'};
9595: }
9596: return ($symb,$courseid,$domain,$name,$publicuser);
9597:
9598: }
9599:
1.36 albertel 9600: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9601: # returns either the contents of the file or
9602: # -1 if the file doesn't exist
1.481 raeburn 9603: #
9604: # if the target is a file that was uploaded via DOCS,
9605: # a check will be made to see if a current copy exists on the local server,
9606: # if it does this will be served, otherwise a copy will be retrieved from
9607: # the home server for the course and stored in /home/httpd/html/userfiles on
9608: # the local server.
1.472 albertel 9609:
1.36 albertel 9610: sub getfile {
1.538 albertel 9611: my ($file) = @_;
1.609 banghart 9612: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9613: &repcopy($file);
9614: return &readfile($file);
9615: }
9616:
9617: sub repcopy_userfile {
9618: my ($file)=@_;
1.609 banghart 9619: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9620: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9621: my ($cdom,$cnum,$filename) =
1.811 albertel 9622: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9623: my $uri="/uploaded/$cdom/$cnum/$filename";
9624: if (-e "$file") {
1.828 www 9625: # we already have a local copy, check it out
1.538 albertel 9626: my @fileinfo = stat($file);
1.828 www 9627: my $rtncode;
9628: my $info;
1.538 albertel 9629: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9630: if ($lwpresp ne 'ok') {
1.828 www 9631: # there is no such file anymore, even though we had a local copy
1.482 albertel 9632: if ($rtncode eq '404') {
1.538 albertel 9633: unlink($file);
1.482 albertel 9634: }
9635: return -1;
9636: }
9637: if ($info < $fileinfo[9]) {
1.828 www 9638: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9639: return 'ok';
1.828 www 9640: } else {
9641: # the file is outdated, get rid of it
9642: unlink($file);
1.482 albertel 9643: }
1.828 www 9644: }
9645: # one way or the other, at this point, we don't have the file
9646: # construct the correct path for the file
9647: my @parts = ($cdom,$cnum);
9648: if ($filename =~ m|^(.+)/[^/]+$|) {
9649: push @parts, split(/\//,$1);
9650: }
9651: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9652: foreach my $part (@parts) {
9653: $path .= '/'.$part;
9654: if (!-e $path) {
9655: mkdir($path,0770);
1.482 albertel 9656: }
9657: }
1.828 www 9658: # now the path exists for sure
9659: # get a user agent
9660: my $ua=new LWP::UserAgent;
9661: my $transferfile=$file.'.in.transfer';
9662: # FIXME: this should flock
9663: if (-e $transferfile) { return 'ok'; }
9664: my $request;
9665: $uri=~s/^\///;
1.980 raeburn 9666: my $homeserver = &homeserver($cnum,$cdom);
9667: my $protocol = $protocol{$homeserver};
9668: $protocol = 'http' if ($protocol ne 'https');
9669: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9670: my $response=$ua->request($request,$transferfile);
9671: # did it work?
9672: if ($response->is_error()) {
9673: unlink($transferfile);
9674: &logthis("Userfile repcopy failed for $uri");
9675: return -1;
9676: }
9677: # worked, rename the transfer file
9678: rename($transferfile,$file);
1.607 raeburn 9679: return 'ok';
1.481 raeburn 9680: }
9681:
1.517 albertel 9682: sub tokenwrapper {
9683: my $uri=shift;
1.980 raeburn 9684: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9685: $uri=~s|^/||;
1.620 albertel 9686: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9687: my $token=$1;
1.552 albertel 9688: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9689: if ($udom && $uname && $file) {
9690: $file=~s|(\?\.*)*$||;
1.949 raeburn 9691: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9692: my $homeserver = &homeserver($uname,$udom);
9693: my $protocol = $protocol{$homeserver};
9694: $protocol = 'http' if ($protocol ne 'https');
9695: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9696: (($uri=~/\?/)?'&':'?').'token='.$token.
9697: '&tokenissued='.$perlvar{'lonHostID'};
9698: } else {
9699: return '/adm/notfound.html';
9700: }
9701: }
9702:
1.828 www 9703: # call with reqtype HEAD: get last modification time
9704: # call with reqtype GET: get the file contents
9705: # Do not call this with reqtype GET for large files! It loads everything into memory
9706: #
1.481 raeburn 9707: sub getuploaded {
9708: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9709: $uri=~s/^\///;
1.980 raeburn 9710: my $homeserver = &homeserver($cnum,$cdom);
9711: my $protocol = $protocol{$homeserver};
9712: $protocol = 'http' if ($protocol ne 'https');
9713: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9714: my $ua=new LWP::UserAgent;
9715: my $request=new HTTP::Request($reqtype,$uri);
9716: my $response=$ua->request($request);
9717: $$rtncode = $response->code;
1.482 albertel 9718: if (! $response->is_success()) {
9719: return 'failed';
9720: }
9721: if ($reqtype eq 'HEAD') {
1.486 www 9722: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9723: } elsif ($reqtype eq 'GET') {
9724: $$info = $response->content;
1.472 albertel 9725: }
1.482 albertel 9726: return 'ok';
1.36 albertel 9727: }
9728:
1.481 raeburn 9729: sub readfile {
9730: my $file = shift;
9731: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9732: my $fh;
9733: open($fh,"<$file");
9734: my $a='';
1.800 albertel 9735: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9736: return $a;
9737: }
9738:
1.36 albertel 9739: sub filelocation {
1.590 banghart 9740: my ($dir,$file) = @_;
9741: my $location;
9742: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9743:
9744: if ($file =~ m-^/adm/-) {
9745: $file=~s-^/adm/wrapper/-/-;
9746: $file=~s-^/adm/coursedocs/showdoc/-/-;
9747: }
1.882 albertel 9748:
1.590 banghart 9749: if ($file=~m:^/~:) { # is a contruction space reference
9750: $location = $file;
9751: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9752: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9753: # is a correct contruction space reference
9754: $location = $file;
1.956 raeburn 9755: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9756: $location = $file;
1.609 banghart 9757: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9758: my ($udom,$uname,$filename)=
1.811 albertel 9759: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9760: my $home=&homeserver($uname,$udom);
9761: my $is_me=0;
9762: my @ids=¤t_machine_ids();
9763: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9764: if ($is_me) {
1.955 raeburn 9765: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9766: } else {
9767: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9768: $udom.'/'.$uname.'/'.$filename;
9769: }
1.882 albertel 9770: } elsif ($file =~ m-^/adm/-) {
9771: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9772: } else {
9773: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9774: $file=~s:^/res/:/:;
9775: if ( !( $file =~ m:^/:) ) {
9776: $location = $dir. '/'.$file;
9777: } else {
9778: $location = '/home/httpd/html/res'.$file;
9779: }
1.59 albertel 9780: }
1.590 banghart 9781: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9782: while ($location=~m{/\.\./}) {
9783: if ($location =~ m{/[^/]+/\.\./}) {
9784: $location=~ s{/[^/]+/\.\./}{/}g;
9785: } else {
9786: $location=~ s{/\.\./}{/}g;
9787: }
9788: } #remove dir/..
1.590 banghart 9789: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9790: return $location;
1.46 www 9791: }
1.36 albertel 9792:
1.46 www 9793: sub hreflocation {
9794: my ($dir,$file)=@_;
1.980 raeburn 9795: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9796: $file=filelocation($dir,$file);
1.700 albertel 9797: } elsif ($file=~m-^/adm/-) {
9798: $file=~s-^/adm/wrapper/-/-;
9799: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9800: }
9801: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9802: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9803: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9804: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9805: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9806: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9807: -/uploaded/$1/$2/-x;
1.46 www 9808: }
1.913 albertel 9809: if ($file=~ m{^/userfiles/}) {
9810: $file =~ s{^/userfiles/}{/uploaded/};
9811: }
1.462 albertel 9812: return $file;
1.465 albertel 9813: }
9814:
9815: sub current_machine_domains {
1.853 albertel 9816: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9817: }
9818:
9819: sub machine_domains {
9820: my ($hostname) = @_;
1.465 albertel 9821: my @domains;
1.838 albertel 9822: my %hostname = &all_hostnames();
1.465 albertel 9823: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9824: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9825: if ($hostname eq $name) {
1.844 albertel 9826: push(@domains,&host_domain($id));
1.465 albertel 9827: }
9828: }
9829: return @domains;
9830: }
9831:
9832: sub current_machine_ids {
1.853 albertel 9833: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9834: }
9835:
9836: sub machine_ids {
9837: my ($hostname) = @_;
9838: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9839: my @ids;
1.888 albertel 9840: my %name_to_host = &all_names();
1.889 albertel 9841: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9842: return @{ $name_to_host{$hostname} };
9843: }
9844: return;
1.31 www 9845: }
9846:
1.824 raeburn 9847: sub additional_machine_domains {
9848: my @domains;
9849: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9850: while( my $line = <$fh>) {
9851: $line =~ s/\s//g;
9852: push(@domains,$line);
9853: }
9854: return @domains;
9855: }
9856:
9857: sub default_login_domain {
9858: my $domain = $perlvar{'lonDefDomain'};
9859: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9860: foreach my $posdom (¤t_machine_domains(),
9861: &additional_machine_domains()) {
9862: if (lc($posdom) eq lc($testdomain)) {
9863: $domain=$posdom;
9864: last;
9865: }
9866: }
9867: return $domain;
9868: }
9869:
1.31 www 9870: # ------------------------------------------------------------- Declutters URLs
9871:
9872: sub declutter {
9873: my $thisfn=shift;
1.569 albertel 9874: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9875: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9876: $thisfn=~s/^\///;
1.697 albertel 9877: $thisfn=~s|^adm/wrapper/||;
9878: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9879: $thisfn=~s/^res\///;
1.1032 raeburn 9880: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9881: $thisfn=~s/\?.+$//;
9882: }
1.268 www 9883: return $thisfn;
9884: }
9885:
9886: # ------------------------------------------------------------- Clutter up URLs
9887:
9888: sub clutter {
9889: my $thisfn='/'.&declutter(shift);
1.887 albertel 9890: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9891: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9892: $thisfn='/res'.$thisfn;
9893: }
1.1031 raeburn 9894: if ($thisfn !~m|^/adm|) {
9895: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9896: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9897: } else {
9898: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9899: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9900: if ($embstyle eq 'ssi'
9901: || ($embstyle eq 'hdn')
9902: || ($embstyle eq 'rat')
9903: || ($embstyle eq 'prv')
9904: || ($embstyle eq 'ign')) {
9905: #do nothing with these
9906: } elsif (($embstyle eq 'img')
1.695 albertel 9907: || ($embstyle eq 'emb')
9908: || ($embstyle eq 'wrp')) {
9909: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9910: } elsif ($embstyle eq 'unk'
9911: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9912: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9913: } else {
1.718 www 9914: # &logthis("Got a blank emb style");
1.695 albertel 9915: }
1.694 albertel 9916: }
9917: }
1.31 www 9918: return $thisfn;
1.12 www 9919: }
9920:
1.787 albertel 9921: sub clutter_with_no_wrapper {
9922: my $uri = &clutter(shift);
9923: if ($uri =~ m-^/adm/-) {
9924: $uri =~ s-^/adm/wrapper/-/-;
9925: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9926: }
9927: return $uri;
9928: }
9929:
1.557 albertel 9930: sub freeze_escape {
9931: my ($value)=@_;
9932: if (ref($value)) {
9933: $value=&nfreeze($value);
9934: return '__FROZEN__'.&escape($value);
9935: }
9936: return &escape($value);
9937: }
9938:
1.11 www 9939:
1.557 albertel 9940: sub thaw_unescape {
9941: my ($value)=@_;
9942: if ($value =~ /^__FROZEN__/) {
9943: substr($value,0,10,undef);
9944: $value=&unescape($value);
9945: return &thaw($value);
9946: }
9947: return &unescape($value);
9948: }
9949:
1.436 albertel 9950: sub correct_line_ends {
9951: my ($result)=@_;
9952: $$result =~s/\r\n/\n/mg;
9953: $$result =~s/\r/\n/mg;
1.415 albertel 9954: }
1.1 albertel 9955: # ================================================================ Main Program
9956:
1.184 www 9957: sub goodbye {
1.204 albertel 9958: &logthis("Starting Shut down");
1.443 albertel 9959: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9960: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9961: #converted
1.599 albertel 9962: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9963: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9964: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9965: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9966: #1.1 only
1.870 albertel 9967: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9968: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9969: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9970: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9971: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9972: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9973: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9974: &flushcourselogs();
9975: &logthis("Shutting down");
9976: }
9977:
1.852 albertel 9978: sub get_dns {
1.869 albertel 9979: my ($url,$func,$ignore_cache) = @_;
9980: if (!$ignore_cache) {
9981: my ($content,$cached)=
9982: &Apache::lonnet::is_cached_new('dns',$url);
9983: if ($cached) {
9984: &$func($content);
9985: return;
9986: }
9987: }
9988:
9989: my %alldns;
1.852 albertel 9990: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9991: foreach my $dns (<$config>) {
9992: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9993: my $line = $1;
9994: my ($host,$protocol) = split(/:/,$line);
9995: if ($protocol ne 'https') {
9996: $protocol = 'http';
9997: }
9998: $alldns{$host} = $protocol;
1.869 albertel 9999: }
10000: while (%alldns) {
10001: my ($dns) = keys(%alldns);
1.852 albertel 10002: my $ua=new LWP::UserAgent;
1.979 raeburn 10003: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10004: my $response=$ua->request($request);
1.979 raeburn 10005: delete($alldns{$dns});
1.852 albertel 10006: next if ($response->is_error());
10007: my @content = split("\n",$response->content);
1.869 albertel 10008: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10009: &$func(\@content);
1.869 albertel 10010: return;
1.852 albertel 10011: }
10012: close($config);
1.871 albertel 10013: my $which = (split('/',$url))[3];
10014: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10015: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10016: my @content = <$config>;
10017: &$func(\@content);
10018: return;
1.852 albertel 10019: }
1.327 albertel 10020: # ------------------------------------------------------------ Read domain file
10021: {
1.852 albertel 10022: my $loaded;
1.846 albertel 10023: my %domain;
10024:
1.852 albertel 10025: sub parse_domain_tab {
10026: my ($lines) = @_;
10027: foreach my $line (@$lines) {
10028: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10029:
1.846 albertel 10030: chomp($line);
1.852 albertel 10031: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10032: my %this_domain;
10033: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10034: 'lang_def', 'city', 'longi', 'lati',
10035: 'primary') {
10036: $this_domain{$field} = shift(@elements);
10037: }
10038: $domain{$name} = \%this_domain;
1.852 albertel 10039: }
10040: }
1.864 albertel 10041:
10042: sub reset_domain_info {
10043: undef($loaded);
10044: undef(%domain);
10045: }
10046:
1.852 albertel 10047: sub load_domain_tab {
1.869 albertel 10048: my ($ignore_cache) = @_;
10049: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10050: my $fh;
10051: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10052: my @lines = <$fh>;
10053: &parse_domain_tab(\@lines);
1.448 albertel 10054: }
1.852 albertel 10055: close($fh);
10056: $loaded = 1;
1.327 albertel 10057: }
1.846 albertel 10058:
10059: sub domain {
1.852 albertel 10060: &load_domain_tab() if (!$loaded);
10061:
1.846 albertel 10062: my ($name,$what) = @_;
10063: return if ( !exists($domain{$name}) );
10064:
10065: if (!$what) {
10066: return $domain{$name}{'description'};
10067: }
10068: return $domain{$name}{$what};
10069: }
1.974 raeburn 10070:
10071: sub domain_info {
10072: &load_domain_tab() if (!$loaded);
10073: return %domain;
10074: }
10075:
1.327 albertel 10076: }
10077:
10078:
1.1 albertel 10079: # ------------------------------------------------------------- Read hosts file
10080: {
1.838 albertel 10081: my %hostname;
1.844 albertel 10082: my %hostdom;
1.845 albertel 10083: my %libserv;
1.852 albertel 10084: my $loaded;
1.888 albertel 10085: my %name_to_host;
1.1074 raeburn 10086: my %internetdom;
1.852 albertel 10087:
10088: sub parse_hosts_tab {
10089: my ($file) = @_;
10090: foreach my $configline (@$file) {
10091: next if ($configline =~ /^(\#|\s*$ )/x);
10092: next if ($configline =~ /^\^/);
10093: chomp($configline);
1.1074 raeburn 10094: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10095: $name=~s/\s//g;
10096: if ($id && $domain && $role && $name) {
10097: $hostname{$id}=$name;
1.888 albertel 10098: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10099: $hostdom{$id}=$domain;
10100: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10101: if (defined($protocol)) {
10102: if ($protocol eq 'https') {
10103: $protocol{$id} = $protocol;
10104: } else {
10105: $protocol{$id} = 'http';
10106: }
1.968 raeburn 10107: } else {
1.969 raeburn 10108: $protocol{$id} = 'http';
1.968 raeburn 10109: }
1.1074 raeburn 10110: if (defined($intdom)) {
10111: $internetdom{$id} = $intdom;
10112: }
1.852 albertel 10113: }
10114: }
10115: }
1.864 albertel 10116:
10117: sub reset_hosts_info {
1.897 albertel 10118: &purge_remembered();
1.864 albertel 10119: &reset_domain_info();
10120: &reset_hosts_ip_info();
1.892 albertel 10121: undef(%name_to_host);
1.864 albertel 10122: undef(%hostname);
10123: undef(%hostdom);
10124: undef(%libserv);
10125: undef($loaded);
10126: }
1.1 albertel 10127:
1.852 albertel 10128: sub load_hosts_tab {
1.869 albertel 10129: my ($ignore_cache) = @_;
10130: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10131: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10132: my @config = <$config>;
10133: &parse_hosts_tab(\@config);
10134: close($config);
10135: $loaded=1;
1.1 albertel 10136: }
1.852 albertel 10137:
1.838 albertel 10138: sub hostname {
1.852 albertel 10139: &load_hosts_tab() if (!$loaded);
10140:
1.838 albertel 10141: my ($lonid) = @_;
10142: return $hostname{$lonid};
10143: }
1.845 albertel 10144:
1.838 albertel 10145: sub all_hostnames {
1.852 albertel 10146: &load_hosts_tab() if (!$loaded);
10147:
1.838 albertel 10148: return %hostname;
10149: }
1.845 albertel 10150:
1.888 albertel 10151: sub all_names {
10152: &load_hosts_tab() if (!$loaded);
10153:
10154: return %name_to_host;
10155: }
10156:
1.974 raeburn 10157: sub all_host_domain {
10158: &load_hosts_tab() if (!$loaded);
10159: return %hostdom;
10160: }
10161:
1.845 albertel 10162: sub is_library {
1.852 albertel 10163: &load_hosts_tab() if (!$loaded);
10164:
1.845 albertel 10165: return exists($libserv{$_[0]});
10166: }
10167:
10168: sub all_library {
1.852 albertel 10169: &load_hosts_tab() if (!$loaded);
10170:
1.845 albertel 10171: return %libserv;
10172: }
10173:
1.1062 droeschl 10174: sub unique_library {
10175: #2x reverse removes all hostnames that appear more than once
10176: my %unique = reverse &all_library();
10177: return reverse %unique;
10178: }
10179:
1.841 albertel 10180: sub get_servers {
1.852 albertel 10181: &load_hosts_tab() if (!$loaded);
10182:
1.841 albertel 10183: my ($domain,$type) = @_;
10184: my %possible_hosts = ($type eq 'library') ? %libserv
10185: : %hostname;
10186: my %result;
1.842 albertel 10187: if (ref($domain) eq 'ARRAY') {
10188: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10189: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10190: $result{$host} = $hostname;
10191: }
10192: }
10193: } else {
10194: while ( my ($host,$hostname) = each(%possible_hosts)) {
10195: if ($hostdom{$host} eq $domain) {
10196: $result{$host} = $hostname;
10197: }
1.841 albertel 10198: }
10199: }
10200: return %result;
10201: }
1.845 albertel 10202:
1.1062 droeschl 10203: sub get_unique_servers {
10204: my %unique = reverse &get_servers(@_);
10205: return reverse %unique;
10206: }
10207:
1.844 albertel 10208: sub host_domain {
1.852 albertel 10209: &load_hosts_tab() if (!$loaded);
10210:
1.844 albertel 10211: my ($lonid) = @_;
10212: return $hostdom{$lonid};
10213: }
10214:
1.841 albertel 10215: sub all_domains {
1.852 albertel 10216: &load_hosts_tab() if (!$loaded);
10217:
1.841 albertel 10218: my %seen;
10219: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10220: return @uniq;
10221: }
1.1074 raeburn 10222:
10223: sub internet_dom {
10224: &load_hosts_tab() if (!$loaded);
10225:
10226: my ($lonid) = @_;
10227: return $internetdom{$lonid};
10228: }
1.1 albertel 10229: }
10230:
1.847 albertel 10231: {
10232: my %iphost;
1.856 albertel 10233: my %name_to_ip;
10234: my %lonid_to_ip;
1.869 albertel 10235:
1.847 albertel 10236: sub get_hosts_from_ip {
10237: my ($ip) = @_;
10238: my %iphosts = &get_iphost();
10239: if (ref($iphosts{$ip})) {
10240: return @{$iphosts{$ip}};
10241: }
10242: return;
1.839 albertel 10243: }
1.864 albertel 10244:
10245: sub reset_hosts_ip_info {
10246: undef(%iphost);
10247: undef(%name_to_ip);
10248: undef(%lonid_to_ip);
10249: }
1.856 albertel 10250:
10251: sub get_host_ip {
10252: my ($lonid) = @_;
10253: if (exists($lonid_to_ip{$lonid})) {
10254: return $lonid_to_ip{$lonid};
10255: }
10256: my $name=&hostname($lonid);
10257: my $ip = gethostbyname($name);
10258: return if (!$ip || length($ip) ne 4);
10259: $ip=inet_ntoa($ip);
10260: $name_to_ip{$name} = $ip;
10261: $lonid_to_ip{$lonid} = $ip;
10262: return $ip;
10263: }
1.847 albertel 10264:
10265: sub get_iphost {
1.869 albertel 10266: my ($ignore_cache) = @_;
1.894 albertel 10267:
1.869 albertel 10268: if (!$ignore_cache) {
10269: if (%iphost) {
10270: return %iphost;
10271: }
10272: my ($ip_info,$cached)=
10273: &Apache::lonnet::is_cached_new('iphost','iphost');
10274: if ($cached) {
10275: %iphost = %{$ip_info->[0]};
10276: %name_to_ip = %{$ip_info->[1]};
10277: %lonid_to_ip = %{$ip_info->[2]};
10278: return %iphost;
10279: }
10280: }
1.894 albertel 10281:
10282: # get yesterday's info for fallback
10283: my %old_name_to_ip;
10284: my ($ip_info,$cached)=
10285: &Apache::lonnet::is_cached_new('iphost','iphost');
10286: if ($cached) {
10287: %old_name_to_ip = %{$ip_info->[1]};
10288: }
10289:
1.888 albertel 10290: my %name_to_host = &all_names();
10291: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10292: my $ip;
10293: if (!exists($name_to_ip{$name})) {
10294: $ip = gethostbyname($name);
10295: if (!$ip || length($ip) ne 4) {
1.894 albertel 10296: if (defined($old_name_to_ip{$name})) {
10297: $ip = $old_name_to_ip{$name};
10298: &logthis("Can't find $name defaulting to old $ip");
10299: } else {
10300: &logthis("Name $name no IP found");
10301: next;
10302: }
10303: } else {
10304: $ip=inet_ntoa($ip);
1.847 albertel 10305: }
10306: $name_to_ip{$name} = $ip;
10307: } else {
10308: $ip = $name_to_ip{$name};
1.653 albertel 10309: }
1.888 albertel 10310: foreach my $id (@{ $name_to_host{$name} }) {
10311: $lonid_to_ip{$id} = $ip;
10312: }
10313: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10314: }
1.869 albertel 10315: &Apache::lonnet::do_cache_new('iphost','iphost',
10316: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10317: 48*60*60);
1.869 albertel 10318:
1.847 albertel 10319: return %iphost;
1.598 albertel 10320: }
10321:
1.992 raeburn 10322: #
10323: # Given a DNS returns the loncapa host name for that DNS
10324: #
10325: sub host_from_dns {
10326: my ($dns) = @_;
10327: my @hosts;
10328: my $ip;
10329:
1.993 raeburn 10330: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10331: $ip = $name_to_ip{$dns};
10332: }
10333: if (!$ip) {
10334: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10335: if (length($ip) == 4) {
10336: $ip = &IO::Socket::inet_ntoa($ip);
10337: }
10338: }
10339: if ($ip) {
10340: @hosts = get_hosts_from_ip($ip);
10341: return $hosts[0];
10342: }
10343: return undef;
1.986 foxr 10344: }
1.992 raeburn 10345:
1.1074 raeburn 10346: sub get_internet_names {
10347: my ($lonid) = @_;
10348: return if ($lonid eq '');
10349: my ($idnref,$cached)=
10350: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10351: if ($cached) {
10352: return $idnref;
10353: }
10354: my $ip = &get_host_ip($lonid);
10355: my @hosts = &get_hosts_from_ip($ip);
10356: my %iphost = &get_iphost();
10357: my (@idns,%seen);
10358: foreach my $id (@hosts) {
10359: my $dom = &host_domain($id);
10360: my $prim_id = &domain($dom,'primary');
10361: my $prim_ip = &get_host_ip($prim_id);
10362: next if ($seen{$prim_ip});
10363: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10364: foreach my $id (@{$iphost{$prim_ip}}) {
10365: my $intdom = &internet_dom($id);
10366: unless (grep(/^\Q$intdom\E$/,@idns)) {
10367: push(@idns,$intdom);
10368: }
10369: }
10370: }
10371: $seen{$prim_ip} = 1;
10372: }
10373: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10374: }
10375:
1.986 foxr 10376: }
10377:
1.1079 raeburn 10378: sub all_loncaparevs {
10379: 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);
10380: }
10381:
1.862 albertel 10382: BEGIN {
10383:
10384: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10385: unless ($readit) {
10386: {
10387: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10388: %perlvar = (%perlvar,%{$configvars});
10389: }
10390:
10391:
1.1 albertel 10392: # ------------------------------------------------------ Read spare server file
10393: {
1.448 albertel 10394: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10395:
10396: while (my $configline=<$config>) {
10397: chomp($configline);
1.284 matthew 10398: if ($configline) {
1.784 albertel 10399: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10400: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10401: push(@{ $spareid{$type} }, $host);
1.1 albertel 10402: }
10403: }
1.448 albertel 10404: close($config);
1.1 albertel 10405: }
1.11 www 10406: # ------------------------------------------------------------ Read permissions
10407: {
1.448 albertel 10408: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10409:
10410: while (my $configline=<$config>) {
1.448 albertel 10411: chomp($configline);
10412: if ($configline) {
10413: my ($role,$perm)=split(/ /,$configline);
10414: if ($perm ne '') { $pr{$role}=$perm; }
10415: }
1.11 www 10416: }
1.448 albertel 10417: close($config);
1.11 www 10418: }
10419:
10420: # -------------------------------------------- Read plain texts for permissions
10421: {
1.448 albertel 10422: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10423:
10424: while (my $configline=<$config>) {
1.448 albertel 10425: chomp($configline);
10426: if ($configline) {
1.742 raeburn 10427: my ($short,@plain)=split(/:/,$configline);
10428: %{$prp{$short}} = ();
10429: if (@plain > 0) {
10430: $prp{$short}{'std'} = $plain[0];
10431: for (my $i=1; $i<@plain; $i++) {
10432: $prp{$short}{'alt'.$i} = $plain[$i];
10433: }
10434: }
1.448 albertel 10435: }
1.135 www 10436: }
1.448 albertel 10437: close($config);
1.135 www 10438: }
10439:
10440: # ---------------------------------------------------------- Read package table
10441: {
1.448 albertel 10442: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10443:
10444: while (my $configline=<$config>) {
1.483 albertel 10445: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10446: chomp($configline);
10447: my ($short,$plain)=split(/:/,$configline);
10448: my ($pack,$name)=split(/\&/,$short);
10449: if ($plain ne '') {
10450: $packagetab{$pack.'&'.$name.'&name'}=$name;
10451: $packagetab{$short}=$plain;
10452: }
1.11 www 10453: }
1.448 albertel 10454: close($config);
1.329 matthew 10455: }
10456:
1.1073 raeburn 10457: # ---------------------------------------------------------- Read loncaparev table
10458: {
10459: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10460: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10461: while (my $configline=<$config>) {
10462: chomp($configline);
10463: my ($hostid,$loncaparev)=split(/:/,$configline);
10464: $loncaparevs{$hostid}=$loncaparev;
10465: }
10466: close($config);
10467: }
10468: }
10469: }
10470:
1.1074 raeburn 10471: # ---------------------------------------------------------- Read serverhostID table
10472: {
10473: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10474: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10475: while (my $configline=<$config>) {
10476: chomp($configline);
10477: my ($name,$id)=split(/:/,$configline);
10478: $serverhomeIDs{$name}=$id;
10479: }
10480: close($config);
10481: }
10482: }
10483: }
10484:
1.1079 raeburn 10485: {
10486: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10487: if (-e $file) {
10488: my $parser = HTML::LCParser->new($file);
10489: while (my $token = $parser->get_token()) {
10490: if ($token->[0] eq 'S') {
10491: my $item = $token->[1];
10492: my $name = $token->[2]{'name'};
10493: my $value = $token->[2]{'value'};
10494: if ($item ne '' && $name ne '' && $value ne '') {
10495: my $release = $parser->get_text();
10496: $release =~ s/(^\s*|\s*$ )//gx;
10497: $needsrelease{$item.':'.$name.':'.$value} = $release;
10498: }
10499: }
10500: }
10501: }
1.1073 raeburn 10502: }
10503:
1.329 matthew 10504: # ------------- set up temporary directory
10505: {
10506: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10507:
1.11 www 10508: }
10509:
1.794 albertel 10510: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10511: 'compress_threshold'=> 20_000,
10512: });
1.185 www 10513:
1.281 www 10514: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10515: $dumpcount=0;
1.958 www 10516: $locknum=0;
1.22 www 10517:
1.163 harris41 10518: &logtouch();
1.672 albertel 10519: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10520: $readit=1;
1.564 albertel 10521: {
10522: use integer;
10523: my $test=(2**32)+1;
1.568 albertel 10524: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10525: &logthis(" Detected 64bit platform ($_64bit)");
10526: }
1.195 www 10527: }
1.1 albertel 10528: }
1.179 www 10529:
1.1 albertel 10530: 1;
1.191 harris41 10531: __END__
10532:
1.243 albertel 10533: =pod
10534:
1.191 harris41 10535: =head1 NAME
10536:
1.243 albertel 10537: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10538:
10539: =head1 SYNOPSIS
10540:
1.243 albertel 10541: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10542:
10543: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10544:
1.243 albertel 10545: Common parameters:
10546:
10547: =over 4
10548:
10549: =item *
10550:
10551: $uname : an internal username (if $cname expecting a course Id specifically)
10552:
10553: =item *
10554:
10555: $udom : a domain (if $cdom expecting a course's domain specifically)
10556:
10557: =item *
10558:
10559: $symb : a resource instance identifier
10560:
10561: =item *
10562:
10563: $namespace : the name of a .db file that contains the data needed or
10564: being set.
10565:
10566: =back
10567:
1.394 bowersj2 10568: =head1 OVERVIEW
1.191 harris41 10569:
1.394 bowersj2 10570: lonnet provides subroutines which interact with the
10571: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10572: about classes, users, and resources.
1.243 albertel 10573:
10574: For many of these objects you can also use this to store data about
10575: them or modify them in various ways.
1.191 harris41 10576:
1.394 bowersj2 10577: =head2 Symbs
1.191 harris41 10578:
1.394 bowersj2 10579: To identify a specific instance of a resource, LON-CAPA uses symbols
10580: or "symbs"X<symb>. These identifiers are built from the URL of the
10581: map, the resource number of the resource in the map, and the URL of
10582: the resource itself. The latter is somewhat redundant, but might help
10583: if maps change.
10584:
10585: An example is
10586:
10587: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10588:
10589: The respective map entry is
10590:
10591: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10592: title="Problem 2">
10593: </resource>
10594:
10595: Symbs are used by the random number generator, as well as to store and
10596: restore data specific to a certain instance of for example a problem.
10597:
10598: =head2 Storing And Retrieving Data
10599:
10600: X<store()>X<cstore()>X<restore()>Three of the most important functions
10601: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10602: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10603: is is the non-critical message twin of cstore. These functions are for
10604: handlers to store a perl hash to a user's permanent data space in an
10605: easy manner, and to retrieve it again on another call. It is expected
10606: that a handler would use this once at the beginning to retrieve data,
10607: and then again once at the end to send only the new data back.
10608:
10609: The data is stored in the user's data directory on the user's
10610: homeserver under the ID of the course.
10611:
10612: The hash that is returned by restore will have all of the previous
10613: value for all of the elements of the hash.
10614:
10615: Example:
10616:
10617: #creating a hash
10618: my %hash;
10619: $hash{'foo'}='bar';
10620:
10621: #storing it
10622: &Apache::lonnet::cstore(\%hash);
10623:
10624: #changing a value
10625: $hash{'foo'}='notbar';
10626:
10627: #adding a new value
10628: $hash{'bar'}='foo';
10629: &Apache::lonnet::cstore(\%hash);
10630:
10631: #retrieving the hash
10632: my %history=&Apache::lonnet::restore();
10633:
10634: #print the hash
10635: foreach my $key (sort(keys(%history))) {
10636: print("\%history{$key} = $history{$key}");
10637: }
10638:
10639: Will print out:
1.191 harris41 10640:
1.394 bowersj2 10641: %history{1:foo} = bar
10642: %history{1:keys} = foo:timestamp
10643: %history{1:timestamp} = 990455579
10644: %history{2:bar} = foo
10645: %history{2:foo} = notbar
10646: %history{2:keys} = foo:bar:timestamp
10647: %history{2:timestamp} = 990455580
10648: %history{bar} = foo
10649: %history{foo} = notbar
10650: %history{timestamp} = 990455580
10651: %history{version} = 2
10652:
10653: Note that the special hash entries C<keys>, C<version> and
10654: C<timestamp> were added to the hash. C<version> will be equal to the
10655: total number of versions of the data that have been stored. The
10656: C<timestamp> attribute will be the UNIX time the hash was
10657: stored. C<keys> is available in every historical section to list which
10658: keys were added or changed at a specific historical revision of a
10659: hash.
10660:
10661: B<Warning>: do not store the hash that restore returns directly. This
10662: will cause a mess since it will restore the historical keys as if the
10663: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10664:
1.394 bowersj2 10665: Calling convention:
1.191 harris41 10666:
1.394 bowersj2 10667: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10668: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10669:
1.394 bowersj2 10670: For more detailed information, see lonnet specific documentation.
1.191 harris41 10671:
1.394 bowersj2 10672: =head1 RETURN MESSAGES
1.191 harris41 10673:
1.394 bowersj2 10674: =over 4
1.191 harris41 10675:
1.394 bowersj2 10676: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10677:
1.394 bowersj2 10678: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10679: when the connection is brought back up
1.191 harris41 10680:
1.394 bowersj2 10681: =item * B<con_failed>: unable to contact remote host and unable to save message
10682: for later delivery
1.191 harris41 10683:
1.967 bisitz 10684: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10685:
1.394 bowersj2 10686: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10687: that was requested
1.191 harris41 10688:
1.243 albertel 10689: =back
1.191 harris41 10690:
1.243 albertel 10691: =head1 PUBLIC SUBROUTINES
1.191 harris41 10692:
1.243 albertel 10693: =head2 Session Environment Functions
1.191 harris41 10694:
1.243 albertel 10695: =over 4
1.191 harris41 10696:
1.394 bowersj2 10697: =item *
10698: X<appenv()>
1.949 raeburn 10699: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10700: the user envirnoment file, and will be restored for each access this
1.620 albertel 10701: user makes during this session, also modifies the %env for the current
1.949 raeburn 10702: process. Optional rolesarrayref - if defined contains a reference to an array
10703: of roles which are exempt from the restriction on modifying user.role entries
10704: in the user's environment.db and in %env.
1.191 harris41 10705:
10706: =item *
1.394 bowersj2 10707: X<delenv()>
1.987 raeburn 10708: B<delenv($delthis,$regexp)>: removes all items from the session
10709: environment file that begin with $delthis. If the
10710: optional second arg - $regexp - is true, $delthis is treated as a
10711: regular expression, otherwise \Q$delthis\E is used.
10712: The values are also deleted from the current processes %env.
1.191 harris41 10713:
1.795 albertel 10714: =item * get_env_multiple($name)
10715:
10716: gets $name from the %env hash, it seemlessly handles the cases where multiple
10717: values may be defined and end up as an array ref.
10718:
10719: returns an array of values
10720:
1.243 albertel 10721: =back
10722:
10723: =head2 User Information
1.191 harris41 10724:
1.243 albertel 10725: =over 4
1.191 harris41 10726:
10727: =item *
1.394 bowersj2 10728: X<queryauthenticate()>
10729: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10730: authentication scheme
10731:
10732: =item *
1.394 bowersj2 10733: X<authenticate()>
1.1073 raeburn 10734: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10735: authenticate user from domain's lib servers (first use the current
10736: one). C<$upass> should be the users password.
1.1073 raeburn 10737: $checkdefauth is optional (value is 1 if a check should be made to
10738: authenticate user using default authentication method, and allow
10739: account creation if username does not have account in the domain).
10740: $clientcancheckhost is optional (value is 1 if checking whether the
10741: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10742:
10743: =item *
1.394 bowersj2 10744: X<homeserver()>
10745: B<homeserver($uname,$udom)>: find the server which has
10746: the user's directory and files (there must be only one), this caches
10747: the answer, and also caches if there is a borken connection.
1.191 harris41 10748:
10749: =item *
1.394 bowersj2 10750: X<idget()>
10751: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10752: (IDs are a unique resource in a domain, there must be only 1 ID per
10753: username, and only 1 username per ID in a specific domain) (returns
10754: hash: id=>name,id=>name)
1.191 harris41 10755:
10756: =item *
1.394 bowersj2 10757: X<idrget()>
10758: B<idrget($udom,@unames)>: find the IDs behind a list of
10759: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10760:
10761: =item *
1.394 bowersj2 10762: X<idput()>
10763: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10764:
10765: =item *
1.394 bowersj2 10766: X<rolesinit()>
10767: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10768:
10769: =item *
1.551 albertel 10770: X<getsection()>
10771: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10772: course $cname, return section name/number or '' for "not in course"
10773: and '-1' for "no section"
10774:
10775: =item *
1.394 bowersj2 10776: X<userenvironment()>
10777: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10778: passed in @what from the requested user's environment, returns a hash
10779:
1.858 raeburn 10780: =item *
10781: X<userlog_query()>
1.859 albertel 10782: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10783: activity.log file. %filters defines filters applied when parsing the
10784: log file. These can be start or end timestamps, or the type of action
10785: - log to look for Login or Logout events, check for Checkin or
10786: Checkout, role for role selection. The response is in the form
10787: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10788: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10789:
1.243 albertel 10790: =back
10791:
10792: =head2 User Roles
10793:
10794: =over 4
10795:
10796: =item *
10797:
1.810 raeburn 10798: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10799: F: full access
10800: U,I,K: authentication modes (cxx only)
10801: '': forbidden
10802: 1: user needs to choose course
10803: 2: browse allowed
1.766 albertel 10804: A: passphrase authentication needed
1.243 albertel 10805:
10806: =item *
10807:
10808: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10809: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10810: and course level
10811:
10812: =item *
10813:
1.988 raeburn 10814: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10815: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10816: $type is Course (default) or Community.
1.988 raeburn 10817: If $forcedefault evaluates to true, text returned will be default
10818: text for $type. Otherwise, if this is a course, the text returned
10819: will be a custom name for the role (if defined in the course's
10820: environment). If no custom name is defined the default is returned.
10821:
1.832 raeburn 10822: =item *
10823:
1.935 raeburn 10824: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10825: All arguments are optional. Returns a hash of a roles, either for
10826: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10827: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10828: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10829: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10830: For each key, value is set to colon-separated start and end times for
10831: the role. If no username and domain are specified, will default to
1.934 raeburn 10832: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10833: of role statuses (active, future or previous), roles
10834: (e.g., cc,in, st etc.) and domains of the roles which can be used
10835: to restrict the list of roles reported. If no array ref is
10836: provided for types, will default to return only active roles.
1.834 albertel 10837:
1.243 albertel 10838: =back
10839:
10840: =head2 User Modification
10841:
10842: =over 4
10843:
10844: =item *
10845:
1.957 raeburn 10846: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10847: user for the level given by URL. Optional start and end dates (leave empty
10848: string or zero for "no date")
1.191 harris41 10849:
10850: =item *
10851:
1.243 albertel 10852: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10853: change a users, password, possible return values are: ok,
10854: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10855: refused
1.191 harris41 10856:
10857: =item *
10858:
1.243 albertel 10859: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10860:
10861: =item *
10862:
1.1058 raeburn 10863: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10864: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10865:
10866: will update user information (firstname,middlename,lastname,generation,
10867: permanentemail), and if forceid is true, student/employee ID also.
10868: A user's institutional affiliation(s) can also be updated.
10869: User information fields will not be overwritten with empty entries
10870: unless the field is included in the $candelete array reference.
10871: This array is included when a single user is modified via "Manage Users",
10872: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10873:
10874: =item *
10875:
1.286 matthew 10876: modifystudent
10877:
1.957 raeburn 10878: modify a student's enrollment and identification information.
1.286 matthew 10879: The course id is resolved based on the current users environment.
10880: This means the envoking user must be a course coordinator or otherwise
10881: associated with a course.
10882:
1.297 matthew 10883: This call is essentially a wrapper for lonnet::modifyuser and
10884: lonnet::modify_student_enrollment
1.286 matthew 10885:
10886: Inputs:
10887:
10888: =over 4
10889:
1.957 raeburn 10890: =item B<$udom> Student's loncapa domain
1.286 matthew 10891:
1.957 raeburn 10892: =item B<$uname> Student's loncapa login name
1.286 matthew 10893:
1.964 bisitz 10894: =item B<$uid> Student/Employee ID
1.286 matthew 10895:
1.957 raeburn 10896: =item B<$umode> Student's authentication mode
1.286 matthew 10897:
1.957 raeburn 10898: =item B<$upass> Student's password
1.286 matthew 10899:
1.957 raeburn 10900: =item B<$first> Student's first name
1.286 matthew 10901:
1.957 raeburn 10902: =item B<$middle> Student's middle name
1.286 matthew 10903:
1.957 raeburn 10904: =item B<$last> Student's last name
1.286 matthew 10905:
1.957 raeburn 10906: =item B<$gene> Student's generation
1.286 matthew 10907:
1.957 raeburn 10908: =item B<$usec> Student's section in course
1.286 matthew 10909:
10910: =item B<$end> Unix time of the roles expiration
10911:
10912: =item B<$start> Unix time of the roles start date
10913:
10914: =item B<$forceid> If defined, allow $uid to be changed
10915:
10916: =item B<$desiredhome> server to use as home server for student
10917:
1.957 raeburn 10918: =item B<$email> Student's permanent e-mail address
10919:
10920: =item B<$type> Type of enrollment (auto or manual)
10921:
1.963 raeburn 10922: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10923:
10924: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10925:
1.963 raeburn 10926: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10927:
1.963 raeburn 10928: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10929:
1.963 raeburn 10930: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10931:
1.286 matthew 10932: =back
1.297 matthew 10933:
10934: =item *
10935:
10936: modify_student_enrollment
10937:
10938: Change a students enrollment status in a class. The environment variable
10939: 'role.request.course' must be defined for this function to proceed.
10940:
10941: Inputs:
10942:
10943: =over 4
10944:
10945: =item $udom, students domain
10946:
10947: =item $uname, students name
10948:
10949: =item $uid, students user id
10950:
10951: =item $first, students first name
10952:
10953: =item $middle
10954:
10955: =item $last
10956:
10957: =item $gene
10958:
10959: =item $usec
10960:
10961: =item $end
10962:
10963: =item $start
10964:
1.957 raeburn 10965: =item $type
10966:
10967: =item $locktype
10968:
10969: =item $cid
10970:
10971: =item $selfenroll
10972:
10973: =item $context
10974:
1.297 matthew 10975: =back
10976:
1.191 harris41 10977:
10978: =item *
10979:
1.243 albertel 10980: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10981: custom role; give a custom role to a user for the level given by URL. Specify
10982: name and domain of role author, and role name
1.191 harris41 10983:
10984: =item *
10985:
1.243 albertel 10986: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10987:
10988: =item *
10989:
1.243 albertel 10990: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10991:
10992: =back
10993:
10994: =head2 Course Infomation
10995:
10996: =over 4
1.191 harris41 10997:
10998: =item *
10999:
1.631 albertel 11000: coursedescription($courseid) : returns a hash of information about the
11001: specified course id, including all environment settings for the
11002: course, the description of the course will be in the hash under the
11003: key 'description'
1.191 harris41 11004:
11005: =item *
11006:
1.624 albertel 11007: resdata($name,$domain,$type,@which) : request for current parameter
11008: setting for a specific $type, where $type is either 'course' or 'user',
11009: @what should be a list of parameters to ask about. This routine caches
11010: answers for 5 minutes.
1.243 albertel 11011:
1.877 foxr 11012: =item *
11013:
11014: get_courseresdata($courseid, $domain) : dump the entire course resource
11015: data base, returning a hash that is keyed by the resource name and has
11016: values that are the resource value. I believe that the timestamps and
11017: versions are also returned.
11018:
11019:
1.243 albertel 11020: =back
11021:
11022: =head2 Course Modification
11023:
11024: =over 4
1.191 harris41 11025:
11026: =item *
11027:
1.243 albertel 11028: writecoursepref($courseid,%prefs) : write preferences (environment
11029: database) for a course
1.191 harris41 11030:
11031: =item *
11032:
1.1011 raeburn 11033: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11034:
11035: =item *
11036:
1.1038 raeburn 11037: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11038:
11039: =back
11040:
11041: =head2 Resource Subroutines
11042:
11043: =over 4
1.191 harris41 11044:
11045: =item *
11046:
1.243 albertel 11047: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11048:
11049: =item *
11050:
1.243 albertel 11051: repcopy($filename) : subscribes to the requested file, and attempts to
11052: replicate from the owning library server, Might return
1.607 raeburn 11053: 'unavailable', 'not_found', 'forbidden', 'ok', or
11054: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11055: resource. Expects the local filesystem pathname
11056: (/home/httpd/html/res/....)
11057:
11058: =back
11059:
11060: =head2 Resource Information
11061:
11062: =over 4
1.191 harris41 11063:
11064: =item *
11065:
1.243 albertel 11066: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11067: a vairety of different possible values, $varname should be a request
11068: string, and the other parameters can be used to specify who and what
11069: one is asking about.
11070:
11071: Possible values for $varname are environment.lastname (or other item
11072: from the envirnment hash), user.name (or someother aspect about the
11073: user), resource.0.maxtries (or some other part and parameter of a
11074: resource)
1.204 albertel 11075:
11076: =item *
11077:
1.243 albertel 11078: directcondval($number) : get current value of a condition; reads from a state
11079: string
1.204 albertel 11080:
11081: =item *
11082:
1.243 albertel 11083: condval($condidx) : value of condition index based on state
1.204 albertel 11084:
11085: =item *
11086:
1.243 albertel 11087: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11088: resource's metadata, $what should be either a specific key, or either
11089: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11090: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11091:
11092: this function automatically caches all requests
1.191 harris41 11093:
11094: =item *
11095:
1.243 albertel 11096: metadata_query($query,$custom,$customshow) : make a metadata query against the
11097: network of library servers; returns file handle of where SQL and regex results
11098: will be stored for query
1.191 harris41 11099:
11100: =item *
11101:
1.243 albertel 11102: symbread($filename) : return symbolic list entry (filename argument optional);
11103: returns the data handle
1.191 harris41 11104:
11105: =item *
11106:
1.243 albertel 11107: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11108: a possible symb for the URL in $thisfn, and if is an encryypted
11109: resource that the user accessed using /enc/ returns a 1 on success, 0
11110: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11111: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11112:
1.191 harris41 11113:
11114: =item *
11115:
1.243 albertel 11116: symbclean($symb) : removes versions numbers from a symb, returns the
11117: cleaned symb
1.191 harris41 11118:
11119: =item *
11120:
1.243 albertel 11121: is_on_map($uri) : checks if the $uri is somewhere on the current
11122: course map, user must be in a course for it to work.
1.191 harris41 11123:
11124: =item *
11125:
1.243 albertel 11126: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11127:
11128: =item *
11129:
1.243 albertel 11130: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11131: a random seed, all arguments are optional, if they aren't sent it uses the
11132: environment to derive them. Note: if symb isn't sent and it can't get one
11133: from &symbread it will use the current time as its return value
1.191 harris41 11134:
11135: =item *
11136:
1.243 albertel 11137: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11138: unfakeable, receipt
1.191 harris41 11139:
11140: =item *
11141:
1.620 albertel 11142: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11143:
11144: =item *
11145:
1.243 albertel 11146: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11147:
11148: =item *
11149:
1.243 albertel 11150: 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 11151:
11152: =item *
11153:
1.243 albertel 11154: 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 11155:
11156: =item *
11157:
1.243 albertel 11158: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11159:
11160: =item *
11161:
1.243 albertel 11162: devalidate($symb) : devalidate temporary spreadsheet calculations,
11163: forcing spreadsheet to reevaluate the resource scores next time.
11164:
11165: =back
11166:
11167: =head2 Storing/Retreiving Data
11168:
11169: =over 4
1.191 harris41 11170:
11171: =item *
11172:
1.243 albertel 11173: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11174: for this url; hashref needs to be given and should be a \%hashname; the
11175: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11176: be derived from the env
1.191 harris41 11177:
11178: =item *
11179:
1.243 albertel 11180: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11181: uses critical subroutine
1.191 harris41 11182:
11183: =item *
11184:
1.243 albertel 11185: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11186: all args are optional
1.191 harris41 11187:
11188: =item *
11189:
1.717 albertel 11190: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11191: dumps the complete (or key matching regexp) namespace into a hash
11192: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11193: normally &store()ed into
11194:
11195: $range should be either an integer '100' (give me the first 100
11196: matching records)
11197: or be two integers sperated by a - with no spaces
11198: '30-50' (give me the 30th through the 50th matching
11199: records)
11200:
11201:
11202: =item *
11203:
11204: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11205: replaces a &store() version of data with a replacement set of data
11206: for a particular resource in a namespace passed in the $storehash hash
11207: reference
11208:
11209: =item *
11210:
1.243 albertel 11211: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11212: works very similar to store/cstore, but all data is stored in a
11213: temporary location and can be reset using tmpreset, $storehash should
11214: be a hash reference, returns nothing on success
1.191 harris41 11215:
11216: =item *
11217:
1.243 albertel 11218: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11219: similar to restore, but all data is stored in a temporary location and
11220: can be reset using tmpreset. Returns a hash of values on success,
11221: error string otherwise.
1.191 harris41 11222:
11223: =item *
11224:
1.243 albertel 11225: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11226: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11227:
11228: =item *
11229:
1.243 albertel 11230: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11231: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11232:
11233: =item *
11234:
1.243 albertel 11235: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11236: namesp ($udom and $uname are optional)
1.191 harris41 11237:
11238: =item *
11239:
1.702 albertel 11240: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11241: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11242: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11243:
1.702 albertel 11244: $range should be either an integer '100' (give me the first 100
11245: matching records)
11246: or be two integers sperated by a - with no spaces
11247: '30-50' (give me the 30th through the 50th matching
11248: records)
1.449 matthew 11249: =item *
11250:
11251: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11252: $store can be a scalar, an array reference, or if the amount to be
11253: incremented is > 1, a hash reference.
11254:
11255: ($udom and $uname are optional)
1.191 harris41 11256:
11257: =item *
11258:
1.243 albertel 11259: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11260: ($udom and $uname are optional)
1.191 harris41 11261:
11262: =item *
11263:
1.243 albertel 11264: cput($namespace,$storehash,$udom,$uname) : critical put
11265: ($udom and $uname are optional)
1.191 harris41 11266:
11267: =item *
11268:
1.748 albertel 11269: newput($namespace,$storehash,$udom,$uname) :
11270:
11271: Attempts to store the items in the $storehash, but only if they don't
11272: currently exist, if this succeeds you can be certain that you have
11273: successfully created a new key value pair in the $namespace db.
11274:
11275:
11276: Args:
11277: $namespace: name of database to store values to
11278: $storehash: hashref to store to the db
11279: $udom: (optional) domain of user containing the db
11280: $uname: (optional) name of user caontaining the db
11281:
11282: Returns:
11283: 'ok' -> succeeded in storing all keys of $storehash
11284: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11285: least <key> already existed in the db (other
11286: requested keys may also already exist)
1.967 bisitz 11287: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11288: 'con_lost' -> unable to contact request server
11289: 'refused' -> action was not allowed by remote machine
11290:
11291:
11292: =item *
11293:
1.243 albertel 11294: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11295: reference filled in from namesp (encrypts the return communication)
11296: ($udom and $uname are optional)
1.191 harris41 11297:
11298: =item *
11299:
1.243 albertel 11300: log($udom,$name,$home,$message) : write to permanent log for user; use
11301: critical subroutine
11302:
1.806 raeburn 11303: =item *
11304:
1.860 raeburn 11305: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11306: array reference filled in from namespace found in domain level on either
11307: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11308:
11309: =item *
11310:
1.860 raeburn 11311: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11312: domain level either on specified domain server ($uhome) or primary domain
11313: server ($udom and $uhome are optional)
1.806 raeburn 11314:
1.943 raeburn 11315: =item *
11316:
11317: get_domain_defaults($target_domain) : returns hash with defaults for
11318: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11319: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11320: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11321: Values are retrieved from cache (if current), or from domain's configuration.db
11322: (if available), or lastly from values in lonTabs/dns_domain,tab,
11323: or lonTabs/domain.tab.
11324:
11325: %domdefaults = &get_auth_defaults($target_domain);
11326:
1.243 albertel 11327: =back
11328:
11329: =head2 Network Status Functions
11330:
11331: =over 4
1.191 harris41 11332:
11333: =item *
11334:
11335: dirlist($uri) : return directory list based on URI
11336:
11337: =item *
11338:
1.243 albertel 11339: spareserver() : find server with least workload from spare.tab
11340:
1.986 foxr 11341:
11342: =item *
11343:
11344: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11345: if there is no corresponding loncapa host.
11346:
1.243 albertel 11347: =back
11348:
1.986 foxr 11349:
1.243 albertel 11350: =head2 Apache Request
11351:
11352: =over 4
1.191 harris41 11353:
11354: =item *
11355:
1.243 albertel 11356: ssi($url,%hash) : server side include, does a complete request cycle on url to
11357: localhost, posts hash
11358:
11359: =back
11360:
11361: =head2 Data to String to Data
11362:
11363: =over 4
1.191 harris41 11364:
11365: =item *
11366:
1.243 albertel 11367: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11368: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11369:
11370: =item *
11371:
1.243 albertel 11372: hashref2str($hashref) : convert a hashref into a string complete with
11373: escaping and '=' and '&' separators, supports elements that are
11374: arrayrefs and hashrefs
1.191 harris41 11375:
11376: =item *
11377:
1.243 albertel 11378: arrayref2str($arrayref) : convert an arrayref into a string complete
11379: with escaping and '&' separators, supports elements that are arrayrefs
11380: and hashrefs
1.191 harris41 11381:
11382: =item *
11383:
1.243 albertel 11384: str2hash($string) : convert string to hash using unescaping and
11385: splitting on '=' and '&', supports elements that are arrayrefs and
11386: hashrefs
1.191 harris41 11387:
11388: =item *
11389:
1.243 albertel 11390: str2array($string) : convert string to hash using unescaping and
11391: splitting on '&', supports elements that are arrayrefs and hashrefs
11392:
11393: =back
11394:
11395: =head2 Logging Routines
11396:
11397: =over 4
11398:
11399: These routines allow one to make log messages in the lonnet.log and
11400: lonnet.perm logfiles.
1.191 harris41 11401:
11402: =item *
11403:
1.243 albertel 11404: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11405:
11406: =item *
11407:
1.243 albertel 11408: logthis() : append message to the normal lonnet.log file, it gets
11409: preiodically rolled over and deleted.
1.191 harris41 11410:
11411: =item *
11412:
1.243 albertel 11413: logperm() : append a permanent message to lonnet.perm.log, this log
11414: file never gets deleted by any automated portion of the system, only
11415: messages of critical importance should go in here.
11416:
11417: =back
11418:
11419: =head2 General File Helper Routines
11420:
11421: =over 4
1.191 harris41 11422:
11423: =item *
11424:
1.481 raeburn 11425: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11426: (a) files in /uploaded
11427: (i) If a local copy of the file exists -
11428: compares modification date of local copy with last-modified date for
11429: definitive version stored on home server for course. If local copy is
11430: stale, requests a new version from the home server and stores it.
11431: If the original has been removed from the home server, then local copy
11432: is unlinked.
11433: (ii) If local copy does not exist -
11434: requests the file from the home server and stores it.
11435:
11436: If $caller is 'uploadrep':
11437: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11438: for request for files originally uploaded via DOCS.
11439: - returns 'ok' if fresh local copy now available, -1 otherwise.
11440:
11441: Otherwise:
11442: This indicates a call from the content generation phase of the request.
11443: - returns the entire contents of the file or -1.
11444:
11445: (b) files in /res
11446: - returns the entire contents of a file or -1;
11447: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11448:
1.712 albertel 11449:
11450: =item *
11451:
11452: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11453: reference
11454:
11455: returns either a stat() list of data about the file or an empty list
11456: if the file doesn't exist or couldn't find out about it (connection
11457: problems or user unknown)
11458:
1.191 harris41 11459: =item *
11460:
1.243 albertel 11461: filelocation($dir,$file) : returns file system location of a file
11462: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11463: directory that relative $file lookups are to looked in ($dir of /a/dir
11464: and a file of ../bob will become /a/bob)
1.191 harris41 11465:
11466: =item *
11467:
11468: hreflocation($dir,$file) : returns file system location or a URL; same as
11469: filelocation except for hrefs
11470:
11471: =item *
11472:
11473: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11474:
1.243 albertel 11475: =back
11476:
1.608 albertel 11477: =head2 Usererfile file routines (/uploaded*)
11478:
11479: =over 4
11480:
11481: =item *
11482:
11483: userfileupload(): main rotine for putting a file in a user or course's
11484: filespace, arguments are,
11485:
1.620 albertel 11486: formname - required - this is the name of the element in $env where the
1.608 albertel 11487: filename, and the contents of the file to create/modifed exist
1.620 albertel 11488: the filename is in $env{'form.'.$formname.'.filename'} and the
11489: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 11490: context - if coursedoc, store the file in the course of the active role
11491: of the current user;
11492: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11493: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11494: subdir - required - subdirectory to put the file in under ../userfiles/
11495: if undefined, it will be placed in "unknown"
11496:
11497: (This routine calls clean_filename() to remove any dangerous
11498: characters from the filename, and then calls finuserfileupload() to
11499: complete the transaction)
11500:
11501: returns either the url of the uploaded file (/uploaded/....) if successful
11502: and /adm/notfound.html if unsuccessful
11503:
11504: =item *
11505:
11506: clean_filename(): routine for cleaing a filename up for storage in
11507: userfile space, argument is:
11508:
11509: filename - proposed filename
11510:
11511: returns: the new clean filename
11512:
11513: =item *
11514:
1.1090 raeburn 11515: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11516: userspace, probably shouldn't be called directly
11517:
11518: docuname: username or courseid of destination for the file
11519: docudom: domain of user/course of destination for the file
11520: formname: same as for userfileupload()
1.1090 raeburn 11521: fname: filename (including subdirectories) for the file
11522: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11523: allfiles: reference to hash used to store objects found by parser
11524: codebase: reference to hash used for codebases of java objects found by parser
11525: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11526: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11527: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11528: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11529: context: if 'overwrite', will move the uploaded file from its temporary location to
11530: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 11531: mimetype: reference to scalar to accommodate mime type determined
11532: from File::MMagic if $parser = parse.
1.608 albertel 11533:
11534: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 11535: and /adm/notfound.html if unsuccessful (or an error message if context
11536: was 'overwrite').
11537:
1.608 albertel 11538:
11539: =item *
11540:
11541: renameuserfile(): renames an existing userfile to a new name
11542:
11543: Args:
11544: docuname: username or courseid of destination for the file
11545: docudom: domain of user/course of destination for the file
11546: old: current file name (including any subdirs under userfiles)
11547: new: desired file name (including any subdirs under userfiles)
11548:
11549: =item *
11550:
11551: mkdiruserfile(): creates a directory is a userfiles dir
11552:
11553: Args:
11554: docuname: username or courseid of destination for the file
11555: docudom: domain of user/course of destination for the file
11556: dir: dir to create (including any subdirs under userfiles)
11557:
11558: =item *
11559:
11560: removeuserfile(): removes a file that exists in userfiles
11561:
11562: Args:
11563: docuname: username or courseid of destination for the file
11564: docudom: domain of user/course of destination for the file
11565: fname: filname to delete (including any subdirs under userfiles)
11566:
11567: =item *
11568:
11569: removeuploadedurl(): convience function for removeuserfile()
11570:
11571: Args:
11572: url: a full /uploaded/... url to delete
11573:
1.747 albertel 11574: =item *
11575:
11576: get_portfile_permissions():
11577: Args:
11578: domain: domain of user or course contain the portfolio files
11579: user: name of user or num of course contain the portfolio files
11580: Returns:
11581: hashref of a dump of the proper file_permissions.db
11582:
11583:
11584: =item *
11585:
11586: get_access_controls():
11587:
11588: Args:
11589: current_permissions: the hash ref returned from get_portfile_permissions()
11590: group: (optional) the group you want the files associated with
11591: file: (optional) the file you want access info on
11592:
11593: Returns:
1.749 raeburn 11594: a hash (keys are file names) of hashes containing
11595: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11596: values are XML containing access control settings (see below)
1.747 albertel 11597:
11598: Internal notes:
11599:
1.749 raeburn 11600: access controls are stored in file_permissions.db as key=value pairs.
11601: key -> path to file/file_name\0uniqueID:scope_end_start
11602: where scope -> public,guest,course,group,domains or users.
11603: end -> UNIX time for end of access (0 -> no end date)
11604: start -> UNIX time for start of access
11605:
11606: value -> XML description of access control
11607: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11608: <start></start>
11609: <end></end>
11610:
11611: <password></password> for scope type = guest
11612:
11613: <domain></domain> for scope type = course or group
11614: <number></number>
11615: <roles id="">
11616: <role></role>
11617: <access></access>
11618: <section></section>
11619: <group></group>
11620: </roles>
11621:
11622: <dom></dom> for scope type = domains
11623:
11624: <users> for scope type = users
11625: <user>
11626: <uname></uname>
11627: <udom></udom>
11628: </user>
11629: </users>
11630: </scope>
11631:
11632: Access data is also aggregated for each file in an additional key=value pair:
11633: key -> path to file/file_name\0accesscontrol
11634: value -> reference to hash
11635: hash contains key = value pairs
11636: where key = uniqueID:scope_end_start
11637: value = UNIX time record was last updated
11638:
11639: Used to improve speed of look-ups of access controls for each file.
11640:
11641: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11642:
11643: modify_access_controls():
11644:
11645: Modifies access controls for a portfolio file
11646: Args
11647: 1. file name
11648: 2. reference to hash of required changes,
11649: 3. domain
11650: 4. username
11651: where domain,username are the domain of the portfolio owner
11652: (either a user or a course)
11653:
11654: Returns:
11655: 1. result of additions or updates ('ok' or 'error', with error message).
11656: 2. result of deletions ('ok' or 'error', with error message).
11657: 3. reference to hash of any new or updated access controls.
11658: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11659: key = integer (inbound ID)
11660: value = uniqueID
1.747 albertel 11661:
1.608 albertel 11662: =back
11663:
1.243 albertel 11664: =head2 HTTP Helper Routines
11665:
11666: =over 4
11667:
1.191 harris41 11668: =item *
11669:
11670: escape() : unpack non-word characters into CGI-compatible hex codes
11671:
11672: =item *
11673:
11674: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11675:
1.243 albertel 11676: =back
11677:
11678: =head1 PRIVATE SUBROUTINES
11679:
11680: =head2 Underlying communication routines (Shouldn't call)
11681:
11682: =over 4
11683:
11684: =item *
11685:
11686: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11687:
11688: =item *
11689:
11690: reply() : uses subreply to send a message to remote machine, logs all failures
11691:
11692: =item *
11693:
11694: critical() : passes a critical message to another server; if cannot
11695: get through then place message in connection buffer directory and
11696: returns con_delayed, if incapable of saving message, returns
11697: con_failed
11698:
11699: =item *
11700:
11701: reconlonc() : tries to reconnect lonc client processes.
11702:
11703: =back
11704:
11705: =head2 Resource Access Logging
11706:
11707: =over 4
11708:
11709: =item *
11710:
11711: flushcourselogs() : flush (save) buffer logs and access logs
11712:
11713: =item *
11714:
11715: courselog($what) : save message for course in hash
11716:
11717: =item *
11718:
11719: courseacclog($what) : save message for course using &courselog(). Perform
11720: special processing for specific resource types (problems, exams, quizzes, etc).
11721:
1.191 harris41 11722: =item *
11723:
11724: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11725: as a PerlChildExitHandler
1.243 albertel 11726:
11727: =back
11728:
11729: =head2 Other
11730:
11731: =over 4
11732:
11733: =item *
11734:
11735: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11736:
11737: =back
11738:
11739: =cut
1.877 foxr 11740:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>