Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1115
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1115 ! raeburn 4: # $Id: lonnet.pm,v 1.1114 2011/06/12 13:48:28 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.1114 raeburn 819: return ($spare_server, $lowest_load); #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 {
1.1115 ! raeburn 865: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 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)) {
1.1115 ! raeburn 871: my $loginvia;
! 872: if ($checkloginvia) {
! 873: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
! 874: }
1.1076 raeburn 875: if ($loginvia eq '') {
876: ($login_host, $lowest_load) =
877: &compare_server_load($lonhost, $login_host, $lowest_load);
878: }
879: }
880: if ($login_host ne '') {
881: $hostname = $servers{$login_host};
882: }
883: return ($login_host,$hostname);
884: }
885:
1.202 matthew 886: # --------------------------------------------- Try to change a user's password
887:
888: sub changepass {
1.799 raeburn 889: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 890: $currentpass = &escape($currentpass);
891: $newpass = &escape($newpass);
1.1030 raeburn 892: my $lonhost = $perlvar{'lonHostID'};
893: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 894: $server);
895: if (! $answer) {
896: &logthis("No reply on password change request to $server ".
897: "by $uname in domain $udom.");
898: } elsif ($answer =~ "^ok") {
899: &logthis("$uname in $udom successfully changed their password ".
900: "on $server.");
901: } elsif ($answer =~ "^pwchange_failure") {
902: &logthis("$uname in $udom was unable to change their password ".
903: "on $server. The action was blocked by either lcpasswd ".
904: "or pwchange");
905: } elsif ($answer =~ "^non_authorized") {
906: &logthis("$uname in $udom did not get their password correct when ".
907: "attempting to change it on $server.");
908: } elsif ($answer =~ "^auth_mode_error") {
909: &logthis("$uname in $udom attempted to change their password despite ".
910: "not being locally or internally authenticated on $server.");
911: } elsif ($answer =~ "^unknown_user") {
912: &logthis("$uname in $udom attempted to change their password ".
913: "on $server but were unable to because $server is not ".
914: "their home server.");
915: } elsif ($answer =~ "^refused") {
916: &logthis("$server refused to change $uname in $udom password because ".
917: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 918: } elsif ($answer =~ "invalid_client") {
919: &logthis("$server refused to change $uname in $udom password because ".
920: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 921: }
922: return $answer;
1.1 albertel 923: }
924:
1.169 harris41 925: # ----------------------- Try to determine user's current authentication scheme
926:
927: sub queryauthenticate {
928: my ($uname,$udom)=@_;
1.456 albertel 929: my $uhome=&homeserver($uname,$udom);
930: if (!$uhome) {
931: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
932: return 'no_host';
933: }
934: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
935: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
936: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 937: }
1.456 albertel 938: return $answer;
1.169 harris41 939: }
940:
1.1 albertel 941: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 942:
1.1 albertel 943: sub authenticate {
1.1073 raeburn 944: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 945: $upass=&escape($upass);
946: $uname= &LONCAPA::clean_username($uname);
1.836 www 947: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 948: my $newhome;
1.836 www 949: if ((!$uhome) || ($uhome eq 'no_host')) {
950: # Maybe the machine was offline and only re-appeared again recently?
951: &reconlonc();
952: # One more
1.952 raeburn 953: $uhome=&homeserver($uname,$udom,1);
954: if (($uhome eq 'no_host') && $checkdefauth) {
955: if (defined(&domain($udom,'primary'))) {
956: $newhome=&domain($udom,'primary');
957: }
958: if ($newhome ne '') {
959: $uhome = $newhome;
960: }
961: }
1.836 www 962: if ((!$uhome) || ($uhome eq 'no_host')) {
963: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 964: return 'no_host';
965: }
1.1 albertel 966: }
1.1073 raeburn 967: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 968: if ($answer eq 'authorized') {
1.952 raeburn 969: if ($newhome) {
970: &logthis("User $uname at $udom authorized by $uhome, but needs account");
971: return 'no_account_on_host';
972: } else {
973: &logthis("User $uname at $udom authorized by $uhome");
974: return $uhome;
975: }
1.471 albertel 976: }
977: if ($answer eq 'non_authorized') {
978: &logthis("User $uname at $udom rejected by $uhome");
979: return 'no_host';
1.9 www 980: }
1.471 albertel 981: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 982: return 'no_host';
983: }
984:
1.1073 raeburn 985: sub can_host_session {
1.1074 raeburn 986: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 987: my $canhost = 1;
1.1074 raeburn 988: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 989: if (ref($remotesessions) eq 'HASH') {
990: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 991: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 992: $canhost = 0;
993: } else {
994: $canhost = 1;
995: }
996: }
997: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 998: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 999: $canhost = 1;
1000: } else {
1001: $canhost = 0;
1002: }
1003: }
1004: if ($canhost) {
1005: if ($remotesessions->{'version'} ne '') {
1006: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1007: if ($reqmajor ne '' && $reqminor ne '') {
1008: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1009: my $major = $1;
1010: my $minor = $2;
1011: if (($major < $reqmajor ) ||
1012: (($major == $reqmajor) && ($minor < $reqminor))) {
1013: $canhost = 0;
1014: }
1015: } else {
1016: $canhost = 0;
1017: }
1018: }
1019: }
1020: }
1021: }
1022: if ($canhost) {
1023: if (ref($hostedsessions) eq 'HASH') {
1024: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1025: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
1026: $canhost = 0;
1027: } else {
1028: $canhost = 1;
1029: }
1030: }
1031: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1032: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
1033: $canhost = 1;
1034: } else {
1035: $canhost = 0;
1036: }
1037: }
1038: }
1039: }
1040: return $canhost;
1041: }
1042:
1.1083 raeburn 1043: sub spare_can_host {
1044: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1045: my $canhost=1;
1046: my @intdoms;
1047: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1048: if (ref($internet_names) eq 'ARRAY') {
1049: @intdoms = @{$internet_names};
1050: }
1051: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1052: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1053: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1054: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1055: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1056: $canhost = &can_host_session($udom,$try_server,$remoterev,
1057: $remotesessions,
1058: $defdomdefaults{'hostedsessions'});
1059: }
1060: return $canhost;
1061: }
1062:
1.1 albertel 1063: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1064:
1.599 albertel 1065: my %homecache;
1.1 albertel 1066: sub homeserver {
1.230 stredwic 1067: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1068: my $index="$uname:$udom";
1.426 albertel 1069:
1.599 albertel 1070: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1071:
1072: my %servers = &get_servers($udom,'library');
1073: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1074: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1075: exists($badServerCache{$tryserver}));
1.841 albertel 1076:
1077: my $answer=reply("home:$udom:$uname",$tryserver);
1078: if ($answer eq 'found') {
1079: delete($badServerCache{$tryserver});
1080: return $homecache{$index}=$tryserver;
1081: } elsif ($answer eq 'no_host') {
1082: $badServerCache{$tryserver}=1;
1083: }
1.1 albertel 1084: }
1085: return 'no_host';
1.70 www 1086: }
1087:
1088: # ------------------------------------- Find the usernames behind a list of IDs
1089:
1090: sub idget {
1091: my ($udom,@ids)=@_;
1092: my %returnhash=();
1093:
1.841 albertel 1094: my %servers = &get_servers($udom,'library');
1095: foreach my $tryserver (keys(%servers)) {
1096: my $idlist=join('&',@ids);
1097: $idlist=~tr/A-Z/a-z/;
1098: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1099: my @answer=();
1100: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1101: @answer=split(/\&/,$reply);
1102: } ;
1103: my $i;
1104: for ($i=0;$i<=$#ids;$i++) {
1105: if ($answer[$i]) {
1106: $returnhash{$ids[$i]}=$answer[$i];
1107: }
1108: }
1109: }
1.70 www 1110: return %returnhash;
1111: }
1112:
1113: # ------------------------------------- Find the IDs behind a list of usernames
1114:
1115: sub idrget {
1116: my ($udom,@unames)=@_;
1117: my %returnhash=();
1.800 albertel 1118: foreach my $uname (@unames) {
1119: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1120: }
1.70 www 1121: return %returnhash;
1122: }
1123:
1124: # ------------------------------- Store away a list of names and associated IDs
1125:
1126: sub idput {
1127: my ($udom,%ids)=@_;
1128: my %servers=();
1.800 albertel 1129: foreach my $uname (keys(%ids)) {
1130: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1131: my $uhom=&homeserver($uname,$udom);
1.70 www 1132: if ($uhom ne 'no_host') {
1.800 albertel 1133: my $id=&escape($ids{$uname});
1.70 www 1134: $id=~tr/A-Z/a-z/;
1.800 albertel 1135: my $esc_unam=&escape($uname);
1.70 www 1136: if ($servers{$uhom}) {
1.800 albertel 1137: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1138: } else {
1.800 albertel 1139: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1140: }
1141: }
1.191 harris41 1142: }
1.800 albertel 1143: foreach my $server (keys(%servers)) {
1144: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1145: }
1.344 www 1146: }
1147:
1.1023 raeburn 1148: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1149: sub dump_dom {
1.1023 raeburn 1150: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1151: if (!$udom) {
1152: $udom=$env{'user.domain'};
1153: }
1154: my %returnhash;
1.1023 raeburn 1155: if ($udom) {
1156: my $uname = &get_domainconfiguser($udom);
1157: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1158: }
1159: return %returnhash;
1160: }
1161:
1.1023 raeburn 1162: # ------------------------------------------ get items from domain db files
1.806 raeburn 1163:
1164: sub get_dom {
1.860 raeburn 1165: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1166: my $items='';
1167: foreach my $item (@$storearr) {
1168: $items.=&escape($item).'&';
1169: }
1170: $items=~s/\&$//;
1.860 raeburn 1171: if (!$udom) {
1172: $udom=$env{'user.domain'};
1173: if (defined(&domain($udom,'primary'))) {
1174: $uhome=&domain($udom,'primary');
1175: } else {
1.874 albertel 1176: undef($uhome);
1.860 raeburn 1177: }
1178: } else {
1179: if (!$uhome) {
1180: if (defined(&domain($udom,'primary'))) {
1181: $uhome=&domain($udom,'primary');
1182: }
1183: }
1184: }
1185: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1186: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1187: my %returnhash;
1.875 albertel 1188: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1189: return %returnhash;
1190: }
1.806 raeburn 1191: my @pairs=split(/\&/,$rep);
1192: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1193: return @pairs;
1194: }
1195: my $i=0;
1196: foreach my $item (@$storearr) {
1197: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1198: $i++;
1199: }
1200: return %returnhash;
1201: } else {
1.880 banghart 1202: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1203: }
1204: }
1205:
1206: # -------------------------------------------- put items in domain db files
1207:
1208: sub put_dom {
1.860 raeburn 1209: my ($namespace,$storehash,$udom,$uhome)=@_;
1210: if (!$udom) {
1211: $udom=$env{'user.domain'};
1212: if (defined(&domain($udom,'primary'))) {
1213: $uhome=&domain($udom,'primary');
1214: } else {
1.874 albertel 1215: undef($uhome);
1.860 raeburn 1216: }
1217: } else {
1218: if (!$uhome) {
1219: if (defined(&domain($udom,'primary'))) {
1220: $uhome=&domain($udom,'primary');
1221: }
1222: }
1223: }
1224: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1225: my $items='';
1226: foreach my $item (keys(%$storehash)) {
1227: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1228: }
1229: $items=~s/\&$//;
1230: return &reply("putdom:$udom:$namespace:$items",$uhome);
1231: } else {
1.860 raeburn 1232: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1233: }
1234: }
1235:
1.1023 raeburn 1236: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1237: sub newput_dom {
1.1023 raeburn 1238: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1239: my $result;
1240: if (!$udom) {
1241: $udom=$env{'user.domain'};
1242: }
1.1023 raeburn 1243: if ($udom) {
1244: my $uname = &get_domainconfiguser($udom);
1245: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1246: }
1247: return $result;
1248: }
1249:
1.1023 raeburn 1250: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1251: sub del_dom {
1.1023 raeburn 1252: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1253: if (ref($storearr) eq 'ARRAY') {
1254: if (!$udom) {
1255: $udom=$env{'user.domain'};
1256: }
1.1023 raeburn 1257: if ($udom) {
1258: my $uname = &get_domainconfiguser($udom);
1259: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1260: }
1261: }
1262: }
1263:
1.1023 raeburn 1264: # ----------------------------------construct domainconfig user for a domain
1265: sub get_domainconfiguser {
1266: my ($udom) = @_;
1267: return $udom.'-domainconfig';
1268: }
1269:
1.837 raeburn 1270: sub retrieve_inst_usertypes {
1271: my ($udom) = @_;
1272: my (%returnhash,@order);
1.989 raeburn 1273: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1274: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1275: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1276: %returnhash = %{$domdefs{'inststatustypes'}};
1277: @order = @{$domdefs{'inststatusorder'}};
1278: } else {
1279: if (defined(&domain($udom,'primary'))) {
1280: my $uhome=&domain($udom,'primary');
1281: my $rep=&reply("inst_usertypes:$udom",$uhome);
1282: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1283: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1284: return (\%returnhash,\@order);
1285: }
1286: my ($hashitems,$orderitems) = split(/:/,$rep);
1287: my @pairs=split(/\&/,$hashitems);
1288: foreach my $item (@pairs) {
1289: my ($key,$value)=split(/=/,$item,2);
1290: $key = &unescape($key);
1291: next if ($key =~ /^error: 2 /);
1292: $returnhash{$key}=&thaw_unescape($value);
1293: }
1294: my @esc_order = split(/\&/,$orderitems);
1295: foreach my $item (@esc_order) {
1296: push(@order,&unescape($item));
1297: }
1298: } else {
1299: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1300: }
1301: }
1302: return (\%returnhash,\@order);
1303: }
1304:
1.868 raeburn 1305: sub is_domainimage {
1306: my ($url) = @_;
1307: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1308: if (&domain($1) ne '') {
1309: return '1';
1310: }
1311: }
1312: return;
1313: }
1314:
1.899 raeburn 1315: sub inst_directory_query {
1316: my ($srch) = @_;
1317: my $udom = $srch->{'srchdomain'};
1318: my %results;
1319: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1320: my $outcome;
1.899 raeburn 1321: if ($homeserver ne '') {
1.904 albertel 1322: my $queryid=&reply("querysend:instdirsearch:".
1323: &escape($srch->{'srchby'}).':'.
1324: &escape($srch->{'srchterm'}).':'.
1325: &escape($srch->{'srchtype'}),$homeserver);
1326: my $host=&hostname($homeserver);
1327: if ($queryid !~/^\Q$host\E\_/) {
1328: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1329: return;
1330: }
1331: my $response = &get_query_reply($queryid);
1332: my $maxtries = 5;
1333: my $tries = 1;
1334: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1335: $response = &get_query_reply($queryid);
1336: $tries ++;
1337: }
1338:
1339: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1340: if ($response eq 'unavailable') {
1341: $outcome = $response;
1342: } else {
1343: $outcome = 'ok';
1344: my @matches = split(/\n/,$response);
1345: foreach my $match (@matches) {
1346: my ($key,$value) = split(/=/,$match);
1347: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1348: }
1.899 raeburn 1349: }
1350: }
1351: }
1.909 raeburn 1352: return ($outcome,%results);
1.899 raeburn 1353: }
1354:
1355: sub usersearch {
1356: my ($srch) = @_;
1357: my $dom = $srch->{'srchdomain'};
1358: my %results;
1359: my %libserv = &all_library();
1360: my $query = 'usersearch';
1361: foreach my $tryserver (keys(%libserv)) {
1362: if (&host_domain($tryserver) eq $dom) {
1363: my $host=&hostname($tryserver);
1364: my $queryid=
1.911 raeburn 1365: &reply("querysend:".&escape($query).':'.
1366: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1367: &escape($srch->{'srchtype'}).':'.
1368: &escape($srch->{'srchterm'}),$tryserver);
1369: if ($queryid !~/^\Q$host\E\_/) {
1370: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1371: next;
1.899 raeburn 1372: }
1373: my $reply = &get_query_reply($queryid);
1374: my $maxtries = 1;
1375: my $tries = 1;
1376: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1377: $reply = &get_query_reply($queryid);
1378: $tries ++;
1379: }
1380: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1381: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1382: } else {
1.911 raeburn 1383: my @matches;
1384: if ($reply =~ /\n/) {
1385: @matches = split(/\n/,$reply);
1386: } else {
1387: @matches = split(/\&/,$reply);
1388: }
1.899 raeburn 1389: foreach my $match (@matches) {
1390: my ($uname,$udom,%userhash);
1.911 raeburn 1391: foreach my $entry (split(/:/,$match)) {
1392: my ($key,$value) =
1393: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1394: $userhash{$key} = $value;
1395: if ($key eq 'username') {
1396: $uname = $value;
1397: } elsif ($key eq 'domain') {
1398: $udom = $value;
1.911 raeburn 1399: }
1.899 raeburn 1400: }
1401: $results{$uname.':'.$udom} = \%userhash;
1402: }
1403: }
1404: }
1405: }
1406: return %results;
1407: }
1408:
1.912 raeburn 1409: sub get_instuser {
1410: my ($udom,$uname,$id) = @_;
1411: my $homeserver = &domain($udom,'primary');
1412: my ($outcome,%results);
1413: if ($homeserver ne '') {
1414: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1415: &escape($id).':'.&escape($udom),$homeserver);
1416: my $host=&hostname($homeserver);
1417: if ($queryid !~/^\Q$host\E\_/) {
1418: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1419: return;
1420: }
1421: my $response = &get_query_reply($queryid);
1422: my $maxtries = 5;
1423: my $tries = 1;
1424: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1425: $response = &get_query_reply($queryid);
1426: $tries ++;
1427: }
1428: if (!&error($response) && $response ne 'refused') {
1429: if ($response eq 'unavailable') {
1430: $outcome = $response;
1431: } else {
1432: $outcome = 'ok';
1433: my @matches = split(/\n/,$response);
1434: foreach my $match (@matches) {
1435: my ($key,$value) = split(/=/,$match);
1436: $results{&unescape($key)} = &thaw_unescape($value);
1437: }
1438: }
1439: }
1440: }
1441: my %userinfo;
1442: if (ref($results{$uname}) eq 'HASH') {
1443: %userinfo = %{$results{$uname}};
1444: }
1445: return ($outcome,%userinfo);
1446: }
1447:
1448: sub inst_rulecheck {
1.923 raeburn 1449: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1450: my %returnhash;
1451: if ($udom ne '') {
1452: if (ref($rules) eq 'ARRAY') {
1453: @{$rules} = map {&escape($_);} (@{$rules});
1454: my $rulestr = join(':',@{$rules});
1455: my $homeserver=&domain($udom,'primary');
1456: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1457: my $response;
1458: if ($item eq 'username') {
1459: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1460: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1461: $homeserver));
1.923 raeburn 1462: } elsif ($item eq 'id') {
1463: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1464: ':'.&escape($id).':'.$rulestr,
1465: $homeserver));
1.945 raeburn 1466: } elsif ($item eq 'selfcreate') {
1467: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1468: &escape($udom).':'.&escape($uname).
1469: ':'.$rulestr,$homeserver));
1.923 raeburn 1470: }
1.912 raeburn 1471: if ($response ne 'refused') {
1472: my @pairs=split(/\&/,$response);
1473: foreach my $item (@pairs) {
1474: my ($key,$value)=split(/=/,$item,2);
1475: $key = &unescape($key);
1476: next if ($key =~ /^error: 2 /);
1477: $returnhash{$key}=&thaw_unescape($value);
1478: }
1479: }
1480: }
1481: }
1482: }
1483: return %returnhash;
1484: }
1485:
1486: sub inst_userrules {
1.923 raeburn 1487: my ($udom,$check) = @_;
1.912 raeburn 1488: my (%ruleshash,@ruleorder);
1489: if ($udom ne '') {
1490: my $homeserver=&domain($udom,'primary');
1491: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1492: my $response;
1493: if ($check eq 'id') {
1494: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1495: $homeserver);
1.943 raeburn 1496: } elsif ($check eq 'email') {
1497: $response=&reply('instemailrules:'.&escape($udom),
1498: $homeserver);
1.923 raeburn 1499: } else {
1500: $response=&reply('instuserrules:'.&escape($udom),
1501: $homeserver);
1502: }
1.912 raeburn 1503: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1504: ($response ne 'unknown_cmd') &&
1.912 raeburn 1505: ($response ne 'no_such_host')) {
1506: my ($hashitems,$orderitems) = split(/:/,$response);
1507: my @pairs=split(/\&/,$hashitems);
1508: foreach my $item (@pairs) {
1509: my ($key,$value)=split(/=/,$item,2);
1510: $key = &unescape($key);
1511: next if ($key =~ /^error: 2 /);
1512: $ruleshash{$key}=&thaw_unescape($value);
1513: }
1514: my @esc_order = split(/\&/,$orderitems);
1515: foreach my $item (@esc_order) {
1516: push(@ruleorder,&unescape($item));
1517: }
1518: }
1519: }
1520: }
1521: return (\%ruleshash,\@ruleorder);
1522: }
1523:
1.976 raeburn 1524: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1525:
1526: sub get_domain_defaults {
1527: my ($domain) = @_;
1528: my $cachetime = 60*60*24;
1529: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1530: if (defined($cached)) {
1531: if (ref($result) eq 'HASH') {
1532: return %{$result};
1533: }
1534: }
1535: my %domdefaults;
1536: my %domconfig =
1.989 raeburn 1537: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1538: 'requestcourses','inststatus',
1.1073 raeburn 1539: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1540: if (ref($domconfig{'defaults'}) eq 'HASH') {
1541: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1542: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1543: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1544: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1545: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1546: } else {
1547: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1548: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1549: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1550: }
1.976 raeburn 1551: if (ref($domconfig{'quotas'}) eq 'HASH') {
1552: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1553: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1554: } else {
1555: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1556: }
1557: my @usertools = ('aboutme','blog','portfolio');
1558: foreach my $item (@usertools) {
1559: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1560: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1561: }
1562: }
1563: }
1.985 raeburn 1564: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1565: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1566: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1567: }
1568: }
1.989 raeburn 1569: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1570: foreach my $item ('inststatustypes','inststatusorder') {
1571: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1572: }
1573: }
1.1047 raeburn 1574: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1575: foreach my $item ('canuse_pdfforms') {
1576: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1577: }
1578: }
1.1073 raeburn 1579: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1580: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1581: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1582: }
1583: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1584: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1585: }
1586: }
1.943 raeburn 1587: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1588: $cachetime);
1589: return %domdefaults;
1590: }
1591:
1.344 www 1592: # --------------------------------------------------- Assign a key to a student
1593:
1594: sub assign_access_key {
1.364 www 1595: #
1596: # a valid key looks like uname:udom#comments
1597: # comments are being appended
1598: #
1.498 www 1599: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1600: $kdom=
1.620 albertel 1601: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1602: $knum=
1.620 albertel 1603: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1604: $cdom=
1.620 albertel 1605: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1606: $cnum=
1.620 albertel 1607: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1608: $udom=$env{'user.name'} unless (defined($udom));
1609: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1610: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1611: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1612: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1613: # assigned to this person
1614: # - this should not happen,
1.345 www 1615: # unless something went wrong
1616: # the first time around
1617: # ready to assign
1.364 www 1618: $logentry=$1.'; '.$logentry;
1.496 www 1619: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1620: $kdom,$knum) eq 'ok') {
1.345 www 1621: # key now belongs to user
1.346 www 1622: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1623: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1624: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1625: return 'ok';
1626: } else {
1627: return
1628: 'error: Count not permanently assign key, will need to be re-entered later.';
1629: }
1630: } else {
1631: return 'error: Could not assign key, try again later.';
1632: }
1.364 www 1633: } elsif (!$existing{$ckey}) {
1.345 www 1634: # the key does not exist
1635: return 'error: The key does not exist';
1636: } else {
1637: # the key is somebody else's
1638: return 'error: The key is already in use';
1639: }
1.344 www 1640: }
1641:
1.364 www 1642: # ------------------------------------------ put an additional comment on a key
1643:
1644: sub comment_access_key {
1645: #
1646: # a valid key looks like uname:udom#comments
1647: # comments are being appended
1648: #
1649: my ($ckey,$cdom,$cnum,$logentry)=@_;
1650: $cdom=
1.620 albertel 1651: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1652: $cnum=
1.620 albertel 1653: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1654: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1655: if ($existing{$ckey}) {
1656: $existing{$ckey}.='; '.$logentry;
1657: # ready to assign
1.367 www 1658: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1659: $cdom,$cnum) eq 'ok') {
1660: return 'ok';
1661: } else {
1662: return 'error: Count not store comment.';
1663: }
1664: } else {
1665: # the key does not exist
1666: return 'error: The key does not exist';
1667: }
1668: }
1669:
1.344 www 1670: # ------------------------------------------------------ Generate a set of keys
1671:
1672: sub generate_access_keys {
1.364 www 1673: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1674: $cdom=
1.620 albertel 1675: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1676: $cnum=
1.620 albertel 1677: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1678: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1679: unless (($cdom) && ($cnum)) { return 0; }
1680: if ($number>10000) { return 0; }
1681: sleep(2); # make sure don't get same seed twice
1682: srand(time()^($$+($$<<15))); # from "Programming Perl"
1683: my $total=0;
1684: for (my $i=1;$i<=$number;$i++) {
1685: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1686: sprintf("%lx",int(100000*rand)).'-'.
1687: sprintf("%lx",int(100000*rand));
1688: $newkey=~s/1/g/g; # folks mix up 1 and l
1689: $newkey=~s/0/h/g; # and also 0 and O
1690: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1691: if ($existing{$newkey}) {
1692: $i--;
1693: } else {
1.364 www 1694: if (&put('accesskeys',
1695: { $newkey => '# generated '.localtime().
1.620 albertel 1696: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1697: '; '.$logentry },
1698: $cdom,$cnum) eq 'ok') {
1.344 www 1699: $total++;
1700: }
1701: }
1702: }
1.620 albertel 1703: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1704: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1705: return $total;
1706: }
1707:
1708: # ------------------------------------------------------- Validate an accesskey
1709:
1710: sub validate_access_key {
1711: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1712: $cdom=
1.620 albertel 1713: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1714: $cnum=
1.620 albertel 1715: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1716: $udom=$env{'user.domain'} unless (defined($udom));
1717: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1718: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1719: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1720: }
1721:
1722: # ------------------------------------- Find the section of student in a course
1.652 albertel 1723: sub devalidate_getsection_cache {
1724: my ($udom,$unam,$courseid)=@_;
1725: my $hashid="$udom:$unam:$courseid";
1726: &devalidate_cache_new('getsection',$hashid);
1727: }
1.298 matthew 1728:
1.815 albertel 1729: sub courseid_to_courseurl {
1730: my ($courseid) = @_;
1731: #already url style courseid
1732: return $courseid if ($courseid =~ m{^/});
1733:
1734: if (exists($env{'course.'.$courseid.'.num'})) {
1735: my $cnum = $env{'course.'.$courseid.'.num'};
1736: my $cdom = $env{'course.'.$courseid.'.domain'};
1737: return "/$cdom/$cnum";
1738: }
1739:
1740: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1741: if (exists($courseinfo{'num'})) {
1742: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1743: }
1744:
1745: return undef;
1746: }
1747:
1.298 matthew 1748: sub getsection {
1749: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1750: my $cachetime=1800;
1.551 albertel 1751:
1752: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1753: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1754: if (defined($cached)) { return $result; }
1755:
1.298 matthew 1756: my %Pending;
1757: my %Expired;
1758: #
1759: # Each role can either have not started yet (pending), be active,
1760: # or have expired.
1761: #
1762: # If there is an active role, we are done.
1763: #
1764: # If there is more than one role which has not started yet,
1765: # choose the one which will start sooner
1766: # If there is one role which has not started yet, return it.
1767: #
1768: # If there is more than one expired role, choose the one which ended last.
1769: # If there is a role which has expired, return it.
1770: #
1.815 albertel 1771: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 1772: my $extra = &freeze_escape({'skipcheck' => 1});
1773: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1774: foreach my $key (keys(%roleshash)) {
1.479 albertel 1775: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1776: my $section=$1;
1777: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1778: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1779: my $now=time;
1.548 albertel 1780: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1781: $Expired{$end}=$section;
1782: next;
1783: }
1.548 albertel 1784: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1785: $Pending{$start}=$section;
1786: next;
1787: }
1.599 albertel 1788: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1789: }
1790: #
1791: # Presumedly there will be few matching roles from the above
1792: # loop and the sorting time will be negligible.
1793: if (scalar(keys(%Pending))) {
1794: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1795: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1796: }
1797: if (scalar(keys(%Expired))) {
1798: my @sorted = sort {$a <=> $b} keys(%Expired);
1799: my $time = pop(@sorted);
1.599 albertel 1800: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1801: }
1.599 albertel 1802: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1803: }
1.70 www 1804:
1.599 albertel 1805: sub save_cache {
1806: &purge_remembered();
1.722 albertel 1807: #&Apache::loncommon::validate_page();
1.620 albertel 1808: undef(%env);
1.780 albertel 1809: undef($env_loaded);
1.599 albertel 1810: }
1.452 albertel 1811:
1.599 albertel 1812: my $to_remember=-1;
1813: my %remembered;
1814: my %accessed;
1815: my $kicks=0;
1816: my $hits=0;
1.849 albertel 1817: sub make_key {
1818: my ($name,$id) = @_;
1.872 albertel 1819: if (length($id) > 65
1820: && length(&escape($id)) > 200) {
1821: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1822: }
1.849 albertel 1823: return &escape($name.':'.$id);
1824: }
1825:
1.599 albertel 1826: sub devalidate_cache_new {
1827: my ($name,$id,$debug) = @_;
1828: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1829: $id=&make_key($name,$id);
1.599 albertel 1830: $memcache->delete($id);
1831: delete($remembered{$id});
1832: delete($accessed{$id});
1833: }
1834:
1835: sub is_cached_new {
1836: my ($name,$id,$debug) = @_;
1.849 albertel 1837: $id=&make_key($name,$id);
1.599 albertel 1838: if (exists($remembered{$id})) {
1839: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1840: $accessed{$id}=[&gettimeofday()];
1841: $hits++;
1842: return ($remembered{$id},1);
1843: }
1844: my $value = $memcache->get($id);
1845: if (!(defined($value))) {
1846: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1847: return (undef,undef);
1.416 albertel 1848: }
1.599 albertel 1849: if ($value eq '__undef__') {
1850: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1851: $value=undef;
1852: }
1853: &make_room($id,$value,$debug);
1854: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1855: return ($value,1);
1856: }
1857:
1858: sub do_cache_new {
1859: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1860: $id=&make_key($name,$id);
1.599 albertel 1861: my $setvalue=$value;
1862: if (!defined($setvalue)) {
1863: $setvalue='__undef__';
1864: }
1.623 albertel 1865: if (!defined($time) ) {
1866: $time=600;
1867: }
1.599 albertel 1868: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1869: my $result = $memcache->set($id,$setvalue,$time);
1870: if (! $result) {
1.872 albertel 1871: &logthis("caching of id -> $id failed");
1.910 albertel 1872: $memcache->disconnect_all();
1.872 albertel 1873: }
1.600 albertel 1874: # need to make a copy of $value
1.919 albertel 1875: &make_room($id,$value,$debug);
1.599 albertel 1876: return $value;
1877: }
1878:
1879: sub make_room {
1880: my ($id,$value,$debug)=@_;
1.919 albertel 1881:
1882: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1883: : $value;
1.599 albertel 1884: if ($to_remember<0) { return; }
1885: $accessed{$id}=[&gettimeofday()];
1886: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1887: my $to_kick;
1888: my $max_time=0;
1889: foreach my $other (keys(%accessed)) {
1890: if (&tv_interval($accessed{$other}) > $max_time) {
1891: $to_kick=$other;
1892: $max_time=&tv_interval($accessed{$other});
1893: }
1894: }
1895: delete($remembered{$to_kick});
1896: delete($accessed{$to_kick});
1897: $kicks++;
1898: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1899: return;
1900: }
1901:
1.599 albertel 1902: sub purge_remembered {
1.604 albertel 1903: #&logthis("Tossing ".scalar(keys(%remembered)));
1904: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1905: undef(%remembered);
1906: undef(%accessed);
1.428 albertel 1907: }
1.70 www 1908: # ------------------------------------- Read an entry from a user's environment
1909:
1910: sub userenvironment {
1911: my ($udom,$unam,@what)=@_;
1.976 raeburn 1912: my $items;
1913: foreach my $item (@what) {
1914: $items.=&escape($item).'&';
1915: }
1916: $items=~s/\&$//;
1.70 www 1917: my %returnhash=();
1.1009 raeburn 1918: my $uhome = &homeserver($unam,$udom);
1919: unless ($uhome eq 'no_host') {
1920: my @answer=split(/\&/,
1921: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1922: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1923: return %returnhash;
1924: }
1.1009 raeburn 1925: my $i;
1926: for ($i=0;$i<=$#what;$i++) {
1927: $returnhash{$what[$i]}=&unescape($answer[$i]);
1928: }
1.70 www 1929: }
1930: return %returnhash;
1.1 albertel 1931: }
1932:
1.617 albertel 1933: # ---------------------------------------------------------- Get a studentphoto
1934: sub studentphoto {
1935: my ($udom,$unam,$ext) = @_;
1936: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1937: if (defined($env{'request.course.id'})) {
1.708 raeburn 1938: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1939: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1940: return(&retrievestudentphoto($udom,$unam,$ext));
1941: } else {
1942: my ($result,$perm_reqd)=
1.707 albertel 1943: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1944: if ($result eq 'ok') {
1945: if (!($perm_reqd eq 'yes')) {
1946: return(&retrievestudentphoto($udom,$unam,$ext));
1947: }
1948: }
1949: }
1950: }
1951: } else {
1952: my ($result,$perm_reqd) =
1.707 albertel 1953: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1954: if ($result eq 'ok') {
1955: if (!($perm_reqd eq 'yes')) {
1956: return(&retrievestudentphoto($udom,$unam,$ext));
1957: }
1958: }
1959: }
1960: return '/adm/lonKaputt/lonlogo_broken.gif';
1961: }
1962:
1963: sub retrievestudentphoto {
1964: my ($udom,$unam,$ext,$type) = @_;
1965: my $home=&Apache::lonnet::homeserver($unam,$udom);
1966: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1967: if ($ret eq 'ok') {
1968: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1969: if ($type eq 'thumbnail') {
1970: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1971: }
1972: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1973: return $tokenurl;
1974: } else {
1975: if ($type eq 'thumbnail') {
1976: return '/adm/lonKaputt/genericstudent_tn.gif';
1977: } else {
1978: return '/adm/lonKaputt/lonlogo_broken.gif';
1979: }
1.617 albertel 1980: }
1981: }
1982:
1.263 www 1983: # -------------------------------------------------------------------- New chat
1984:
1985: sub chatsend {
1.724 raeburn 1986: my ($newentry,$anon,$group)=@_;
1.620 albertel 1987: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1988: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1989: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1990: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1991: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1992: &escape($newentry)).':'.$group,$chome);
1.292 www 1993: }
1994:
1995: # ------------------------------------------ Find current version of a resource
1996:
1997: sub getversion {
1998: my $fname=&clutter(shift);
1999: unless ($fname=~/^\/res\//) { return -1; }
2000: return ¤tversion(&filelocation('',$fname));
2001: }
2002:
2003: sub currentversion {
2004: my $fname=shift;
2005: my $author=$fname;
2006: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2007: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2008: my $home=&homeserver($uname,$udom);
1.292 www 2009: if ($home eq 'no_host') {
2010: return -1;
2011: }
1.1112 www 2012: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2013: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2014: return -1;
2015: }
1.1112 www 2016: return $answer;
1.263 www 2017: }
2018:
1.1111 www 2019: #
2020: # Return special version number of resource if set by override, empty otherwise
2021: #
2022: sub usedversion {
2023: my $fname=shift;
2024: unless ($fname) { $fname=$env{'request.uri'}; }
2025: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2026: if ($urlversion) { return $urlversion; }
2027: return '';
2028: }
2029:
1.1 albertel 2030: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2031:
1.1 albertel 2032: sub subscribe {
2033: my $fname=shift;
1.761 raeburn 2034: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2035: $fname=~s/[\n\r]//g;
1.1 albertel 2036: my $author=$fname;
2037: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2038: my ($udom,$uname)=split(/\//,$author);
2039: my $home=homeserver($uname,$udom);
1.335 albertel 2040: if ($home eq 'no_host') {
2041: return 'not_found';
1.1 albertel 2042: }
2043: my $answer=reply("sub:$fname",$home);
1.64 www 2044: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2045: $answer.=' by '.$home;
2046: }
1.1 albertel 2047: return $answer;
2048: }
2049:
1.8 www 2050: # -------------------------------------------------------------- Replicate file
2051:
2052: sub repcopy {
2053: my $filename=shift;
1.23 www 2054: $filename=~s/\/+/\//g;
1.607 raeburn 2055: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2056: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2057: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2058: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2059: return &repcopy_userfile($filename);
2060: }
1.532 albertel 2061: $filename=~s/[\n\r]//g;
1.8 www 2062: my $transname="$filename.in.transfer";
1.828 www 2063: # FIXME: this should flock
1.607 raeburn 2064: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2065: my $remoteurl=subscribe($filename);
1.64 www 2066: if ($remoteurl =~ /^con_lost by/) {
2067: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2068: return 'unavailable';
1.8 www 2069: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2070: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2071: return 'not_found';
1.64 www 2072: } elsif ($remoteurl =~ /^rejected by/) {
2073: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2074: return 'forbidden';
1.20 www 2075: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2076: return 'ok';
1.8 www 2077: } else {
1.290 www 2078: my $author=$filename;
2079: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2080: my ($udom,$uname)=split(/\//,$author);
2081: my $home=homeserver($uname,$udom);
2082: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2083: my @parts=split(/\//,$filename);
2084: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2085: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2086: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2087: return 'bad_request';
1.8 www 2088: }
2089: my $count;
2090: for ($count=5;$count<$#parts;$count++) {
2091: $path.="/$parts[$count]";
2092: if ((-e $path)!=1) {
2093: mkdir($path,0777);
2094: }
2095: }
2096: my $ua=new LWP::UserAgent;
2097: my $request=new HTTP::Request('GET',"$remoteurl");
2098: my $response=$ua->request($request,$transname);
2099: if ($response->is_error()) {
2100: unlink($transname);
2101: my $message=$response->status_line;
1.672 albertel 2102: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2103: ." LWP get: $message: $filename</font>");
1.607 raeburn 2104: return 'unavailable';
1.8 www 2105: } else {
1.16 www 2106: if ($remoteurl!~/\.meta$/) {
2107: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2108: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2109: if ($mresponse->is_error()) {
2110: unlink($filename.'.meta');
2111: &logthis(
1.672 albertel 2112: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2113: }
2114: }
1.8 www 2115: rename($transname,$filename);
1.607 raeburn 2116: return 'ok';
1.8 www 2117: }
1.290 www 2118: }
1.8 www 2119: }
1.330 www 2120: }
2121:
2122: # ------------------------------------------------ Get server side include body
2123: sub ssi_body {
1.381 albertel 2124: my ($filelink,%form)=@_;
1.606 matthew 2125: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2126: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2127: }
1.953 www 2128: my $output='';
2129: my $response;
1.980 raeburn 2130: if ($filelink=~/^https?\:/) {
1.954 raeburn 2131: ($output,$response)=&externalssi($filelink);
1.953 www 2132: } else {
1.1004 droeschl 2133: $filelink .= $filelink=~/\?/ ? '&' : '?';
2134: $filelink .= 'inhibitmenu=yes';
1.953 www 2135: ($output,$response)=&ssi($filelink,%form);
2136: }
1.778 albertel 2137: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2138: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2139: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2140: if (wantarray) {
2141: return ($output, $response);
2142: } else {
2143: return $output;
2144: }
1.8 www 2145: }
2146:
1.15 www 2147: # --------------------------------------------------------- Server Side Include
2148:
1.782 albertel 2149: sub absolute_url {
2150: my ($host_name) = @_;
2151: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2152: if ($host_name eq '') {
2153: $host_name = $ENV{'SERVER_NAME'};
2154: }
2155: return $protocol.$host_name;
2156: }
2157:
1.942 foxr 2158: #
2159: # Server side include.
2160: # Parameters:
2161: # fn Possibly encrypted resource name/id.
2162: # form Hash that describes how the rendering should be done
2163: # and other things.
1.944 foxr 2164: # Returns:
1.950 raeburn 2165: # Scalar context: The content of the response.
2166: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2167: #
1.15 www 2168: sub ssi {
2169:
1.944 foxr 2170: my ($fn,%form)=@_;
1.15 www 2171: my $ua=new LWP::UserAgent;
1.23 www 2172: my $request;
1.711 albertel 2173:
2174: $form{'no_update_last_known'}=1;
1.895 albertel 2175: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2176: if (%form) {
1.782 albertel 2177: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2178: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2179: } else {
1.782 albertel 2180: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2181: }
2182:
1.15 www 2183: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2184: my $response=$ua->request($request);
2185:
1.944 foxr 2186: if (wantarray) {
2187: return ($response->content, $response);
2188: } else {
2189: return $response->content;
1.942 foxr 2190: }
1.324 www 2191: }
2192:
2193: sub externalssi {
2194: my ($url)=@_;
2195: my $ua=new LWP::UserAgent;
2196: my $request=new HTTP::Request('GET',$url);
2197: my $response=$ua->request($request);
1.954 raeburn 2198: if (wantarray) {
2199: return ($response->content, $response);
2200: } else {
2201: return $response->content;
2202: }
1.15 www 2203: }
1.254 www 2204:
1.492 albertel 2205: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2206:
2207: sub allowuploaded {
2208: my ($srcurl,$url)=@_;
2209: $url=&clutter(&declutter($url));
2210: my $dir=$url;
2211: $dir=~s/\/[^\/]+$//;
2212: my %httpref=();
2213: my $httpurl=&hreflocation('',$url);
2214: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2215: &Apache::lonnet::appenv(\%httpref);
1.254 www 2216: }
1.477 raeburn 2217:
1.478 albertel 2218: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2219: # input: action, courseID, current domain, intended
1.637 raeburn 2220: # path to file, source of file, instruction to parse file for objects,
2221: # ref to hash for embedded objects,
2222: # ref to hash for codebase of java objects.
1.1095 raeburn 2223: # reference to scalar to accommodate mime type determined
2224: # from File::MMagic if $parser = parse.
1.637 raeburn 2225: #
1.485 raeburn 2226: # output: url to file (if action was uploaddoc),
2227: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2228: #
1.478 albertel 2229: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2230: # course.
1.477 raeburn 2231: #
1.478 albertel 2232: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2233: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2234: # course's home server.
1.477 raeburn 2235: #
1.478 albertel 2236: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2237: # be copied from $source (current location) to
2238: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2239: # and will then be copied to
2240: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2241: # course's home server.
1.485 raeburn 2242: #
1.481 raeburn 2243: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2244: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2245: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2246: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2247: # in course's home server.
1.637 raeburn 2248: #
1.477 raeburn 2249:
2250: sub process_coursefile {
1.1095 raeburn 2251: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2252: $mimetype)=@_;
1.477 raeburn 2253: my $fetchresult;
1.638 albertel 2254: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2255: if ($action eq 'propagate') {
1.638 albertel 2256: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2257: $home);
1.481 raeburn 2258: } else {
1.477 raeburn 2259: my $fpath = '';
2260: my $fname = $file;
1.478 albertel 2261: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2262: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2263: my $filepath = &build_filepath($fpath);
1.481 raeburn 2264: if ($action eq 'copy') {
2265: if ($source eq '') {
2266: $fetchresult = 'no source file';
2267: return $fetchresult;
2268: } else {
2269: my $destination = $filepath.'/'.$fname;
2270: rename($source,$destination);
2271: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2272: $home);
1.481 raeburn 2273: }
2274: } elsif ($action eq 'uploaddoc') {
2275: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2276: print $fh $env{'form.'.$source};
1.481 raeburn 2277: close($fh);
1.637 raeburn 2278: if ($parser eq 'parse') {
1.1024 raeburn 2279: my $mm = new File::MMagic;
1.1095 raeburn 2280: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2281: if ($type eq 'text/html') {
1.1024 raeburn 2282: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2283: unless ($parse_result eq 'ok') {
2284: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2285: }
1.637 raeburn 2286: }
1.1095 raeburn 2287: if (ref($mimetype)) {
2288: $$mimetype = $type;
2289: }
1.637 raeburn 2290: }
1.477 raeburn 2291: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2292: $home);
1.481 raeburn 2293: if ($fetchresult eq 'ok') {
2294: return '/uploaded/'.$fpath.'/'.$fname;
2295: } else {
2296: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2297: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2298: return '/adm/notfound.html';
2299: }
1.477 raeburn 2300: }
2301: }
1.485 raeburn 2302: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2303: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2304: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2305: }
2306: return $fetchresult;
2307: }
2308:
1.637 raeburn 2309: sub build_filepath {
2310: my ($fpath) = @_;
2311: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2312: unless ($fpath eq '') {
2313: my @parts=split('/',$fpath);
2314: foreach my $part (@parts) {
2315: $filepath.= '/'.$part;
2316: if ((-e $filepath)!=1) {
2317: mkdir($filepath,0777);
2318: }
2319: }
2320: }
2321: return $filepath;
2322: }
2323:
2324: sub store_edited_file {
1.638 albertel 2325: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2326: my $file = $primary_url;
2327: $file =~ s#^/uploaded/$docudom/$docuname/##;
2328: my $fpath = '';
2329: my $fname = $file;
2330: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2331: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2332: my $filepath = &build_filepath($fpath);
2333: open(my $fh,'>'.$filepath.'/'.$fname);
2334: print $fh $content;
2335: close($fh);
1.638 albertel 2336: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2337: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2338: $home);
1.637 raeburn 2339: if ($$fetchresult eq 'ok') {
2340: return '/uploaded/'.$fpath.'/'.$fname;
2341: } else {
1.638 albertel 2342: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2343: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2344: return '/adm/notfound.html';
2345: }
2346: }
2347:
1.531 albertel 2348: sub clean_filename {
1.831 albertel 2349: my ($fname,$args)=@_;
1.315 www 2350: # Replace Windows backslashes by forward slashes
1.257 www 2351: $fname=~s/\\/\//g;
1.831 albertel 2352: if (!$args->{'keep_path'}) {
2353: # Get rid of everything but the actual filename
2354: $fname=~s/^.*\/([^\/]+)$/$1/;
2355: }
1.315 www 2356: # Replace spaces by underscores
2357: $fname=~s/\s+/\_/g;
2358: # Replace all other weird characters by nothing
1.831 albertel 2359: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2360: # Replace all .\d. sequences with _\d. so they no longer look like version
2361: # numbers
2362: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2363: return $fname;
2364: }
1.1051 raeburn 2365: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2366: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2367: # image with the same aspect ratio as the original, but with dimensions which do
2368: # not exceed $resizewidth and $resizeheight.
2369:
1.984 neumanie 2370: sub resizeImage {
1.1051 raeburn 2371: my ($img_path,$resizewidth,$resizeheight) = @_;
2372: my $ima = Image::Magick->new;
2373: my $resized;
2374: if (-e $img_path) {
2375: $ima->Read($img_path);
2376: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2377: my $width = $ima->Get('width');
2378: my $height = $ima->Get('height');
2379: if ($width > $resizewidth) {
2380: my $factor = $width/$resizewidth;
2381: my $newheight = $height/$factor;
2382: $ima->Scale(width=>$resizewidth,height=>$newheight);
2383: $resized = 1;
2384: }
2385: }
2386: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2387: my $width = $ima->Get('width');
2388: my $height = $ima->Get('height');
2389: if ($height > $resizeheight) {
2390: my $factor = $height/$resizeheight;
2391: my $newwidth = $width/$factor;
2392: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2393: $resized = 1;
2394: }
2395: }
2396: if ($resized) {
2397: $ima->Write($img_path);
2398: }
2399: }
2400: return;
1.977 amueller 2401: }
2402:
1.608 albertel 2403: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2404: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2405: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2406: # $context - possible values: coursedoc, existingfile, overwrite,
2407: # canceloverwrite, or ''.
2408: # if 'coursedoc': upload to the current course
2409: # if 'existingfile': write file to tmp/overwrites directory
2410: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2411: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2412: # $subdir - directory in userfile to store the file into
1.858 raeburn 2413: # $parser - instruction to parse file for objects ($parser = parse)
2414: # $allfiles - reference to hash for embedded objects
2415: # $codebase - reference to hash for codebase of java objects
2416: # $desuname - username for permanent storage of uploaded file
2417: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2418: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2419: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2420: # $resizewidth - width (pixels) to which to resize uploaded image
2421: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2422: # $mimetype - reference to scalar to accommodate mime type determined
2423: # from File::MMagic if $parser = parse.
1.858 raeburn 2424: #
1.686 albertel 2425: # output: url of file in userspace, or error: <message>
2426: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2427:
1.531 albertel 2428: sub userfileupload {
1.1090 raeburn 2429: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2430: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2431: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2432: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2433: $fname=&clean_filename($fname);
1.1090 raeburn 2434: # See if there is anything left
1.257 www 2435: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2436: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2437: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2438: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2439: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2440: my $now = time;
1.1090 raeburn 2441: my $filepath;
1.1095 raeburn 2442: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2443: $filepath = 'tmp/helprequests/'.$now;
2444: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2445: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2446: '_'.$env{'user.domain'}.'/pending';
2447: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2448: my ($docuname,$docudom);
2449: if ($destudom) {
2450: $docudom = $destudom;
2451: } else {
2452: $docudom = $env{'user.domain'};
2453: }
2454: if ($destuname) {
2455: $docuname = $destuname;
2456: } else {
2457: $docuname = $env{'user.name'};
2458: }
2459: if (exists($env{'form.group'})) {
2460: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2461: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2462: }
2463: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2464: if ($context eq 'canceloverwrite') {
2465: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2466: if (-e $tempfile) {
2467: my @info = stat($tempfile);
2468: if ($info[9] eq $env{'form.timestamp'}) {
2469: unlink($tempfile);
2470: }
2471: }
2472: return;
1.523 raeburn 2473: }
2474: }
1.1090 raeburn 2475: # Create the directory if not present
1.741 raeburn 2476: my @parts=split(/\//,$filepath);
2477: my $fullpath = $perlvar{'lonDaemons'};
2478: for (my $i=0;$i<@parts;$i++) {
2479: $fullpath .= '/'.$parts[$i];
2480: if ((-e $fullpath)!=1) {
2481: mkdir($fullpath,0777);
2482: }
2483: }
2484: open(my $fh,'>'.$fullpath.'/'.$fname);
2485: print $fh $env{'form.'.$formname};
2486: close($fh);
1.1090 raeburn 2487: if ($context eq 'existingfile') {
2488: my @info = stat($fullpath.'/'.$fname);
2489: return ($fullpath.'/'.$fname,$info[9]);
2490: } else {
2491: return $fullpath.'/'.$fname;
2492: }
1.523 raeburn 2493: }
1.995 raeburn 2494: if ($subdir eq 'scantron') {
2495: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2496: } else {
1.995 raeburn 2497: $fname="$subdir/$fname";
2498: }
1.1090 raeburn 2499: if ($context eq 'coursedoc') {
1.638 albertel 2500: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2501: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2502: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2503: return &finishuserfileupload($docuname,$docudom,
2504: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2505: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2506: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2507: } else {
1.620 albertel 2508: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2509: return &process_coursefile('uploaddoc',$docuname,$docudom,
2510: $fname,$formname,$parser,
1.1095 raeburn 2511: $allfiles,$codebase,$mimetype);
1.481 raeburn 2512: }
1.719 banghart 2513: } elsif (defined($destuname)) {
2514: my $docuname=$destuname;
2515: my $docudom=$destudom;
1.860 raeburn 2516: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2517: $parser,$allfiles,$codebase,
1.1051 raeburn 2518: $thumbwidth,$thumbheight,
1.1095 raeburn 2519: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2520: } else {
1.638 albertel 2521: my $docuname=$env{'user.name'};
2522: my $docudom=$env{'user.domain'};
1.714 raeburn 2523: if (exists($env{'form.group'})) {
2524: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2525: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2526: }
1.860 raeburn 2527: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2528: $parser,$allfiles,$codebase,
1.1051 raeburn 2529: $thumbwidth,$thumbheight,
1.1095 raeburn 2530: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2531: }
1.271 www 2532: }
2533:
2534: sub finishuserfileupload {
1.860 raeburn 2535: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2536: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2537: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2538: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2539:
1.860 raeburn 2540: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2541: $file=$fname;
2542: if ($fname=~m|/|) {
2543: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2544: $path.=$fnamepath.'/';
2545: }
1.259 www 2546: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2547: my $count;
2548: for ($count=4;$count<=$#parts;$count++) {
2549: $filepath.="/$parts[$count]";
2550: if ((-e $filepath)!=1) {
2551: mkdir($filepath,0777);
2552: }
2553: }
1.984 neumanie 2554:
1.258 www 2555: # Save the file
2556: {
1.701 albertel 2557: if (!open(FH,'>'.$filepath.'/'.$file)) {
2558: &logthis('Failed to create '.$filepath.'/'.$file);
2559: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2560: return '/adm/notfound.html';
2561: }
1.1090 raeburn 2562: if ($context eq 'overwrite') {
2563: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2564: my $target = $filepath.'/'.$file;
2565: if (-e $source) {
2566: my @info = stat($source);
2567: if ($info[9] eq $env{'form.timestamp'}) {
2568: unless (&File::Copy::move($source,$target)) {
2569: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2570: return "Moving from $source failed";
2571: }
2572: } else {
2573: return "Temporary file: $source had unexpected date/time for last modification";
2574: }
2575: } else {
2576: return "Temporary file: $source missing";
2577: }
2578: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2579: &logthis('Failed to write to '.$filepath.'/'.$file);
2580: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2581: return '/adm/notfound.html';
2582: }
1.570 albertel 2583: close(FH);
1.1051 raeburn 2584: if ($resizewidth && $resizeheight) {
2585: my $mm = new File::MMagic;
2586: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2587: if ($mime_type =~ m{^image/}) {
2588: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2589: }
1.977 amueller 2590: }
1.258 www 2591: }
1.637 raeburn 2592: if ($parser eq 'parse') {
1.1024 raeburn 2593: my $mm = new File::MMagic;
1.1095 raeburn 2594: my $type = $mm->checktype_filename($filepath.'/'.$file);
2595: if ($type eq 'text/html') {
1.1024 raeburn 2596: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2597: $allfiles,$codebase);
2598: unless ($parse_result eq 'ok') {
2599: &logthis('Failed to parse '.$filepath.$file.
2600: ' for embedded media: '.$parse_result);
2601: }
1.637 raeburn 2602: }
1.1095 raeburn 2603: if (ref($mimetype)) {
2604: $$mimetype = $type;
2605: }
1.637 raeburn 2606: }
1.860 raeburn 2607: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2608: my $input = $filepath.'/'.$file;
2609: my $output = $filepath.'/'.'tn-'.$file;
2610: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2611: system("convert -sample $thumbsize $input $output");
2612: if (-e $filepath.'/'.'tn-'.$file) {
2613: $fetchthumb = 1;
2614: }
2615: }
1.858 raeburn 2616:
1.259 www 2617: # Notify homeserver to grep it
2618: #
1.984 neumanie 2619: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2620: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2621: if ($fetchresult eq 'ok') {
1.860 raeburn 2622: if ($fetchthumb) {
2623: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2624: if ($thumbresult ne 'ok') {
2625: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2626: $docuhome.': '.$thumbresult);
2627: }
2628: }
1.259 www 2629: #
1.258 www 2630: # Return the URL to it
1.494 albertel 2631: return '/uploaded/'.$path.$file;
1.263 www 2632: } else {
1.494 albertel 2633: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2634: ': '.$fetchresult);
1.263 www 2635: return '/adm/notfound.html';
1.858 raeburn 2636: }
1.493 albertel 2637: }
2638:
1.637 raeburn 2639: sub extract_embedded_items {
1.961 raeburn 2640: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2641: my @state = ();
2642: my %javafiles = (
2643: codebase => '',
2644: code => '',
2645: archive => ''
2646: );
2647: my %mediafiles = (
2648: src => '',
2649: movie => '',
2650: );
1.648 raeburn 2651: my $p;
2652: if ($content) {
2653: $p = HTML::LCParser->new($content);
2654: } else {
1.961 raeburn 2655: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2656: }
1.641 albertel 2657: while (my $t=$p->get_token()) {
1.640 albertel 2658: if ($t->[0] eq 'S') {
2659: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2660: push(@state, $tagname);
1.648 raeburn 2661: if (lc($tagname) eq 'allow') {
2662: &add_filetype($allfiles,$attr->{'src'},'src');
2663: }
1.640 albertel 2664: if (lc($tagname) eq 'img') {
2665: &add_filetype($allfiles,$attr->{'src'},'src');
2666: }
1.886 albertel 2667: if (lc($tagname) eq 'a') {
2668: &add_filetype($allfiles,$attr->{'href'},'href');
2669: }
1.645 raeburn 2670: if (lc($tagname) eq 'script') {
2671: if ($attr->{'archive'} =~ /\.jar$/i) {
2672: &add_filetype($allfiles,$attr->{'archive'},'archive');
2673: } else {
2674: &add_filetype($allfiles,$attr->{'src'},'src');
2675: }
2676: }
2677: if (lc($tagname) eq 'link') {
2678: if (lc($attr->{'rel'}) eq 'stylesheet') {
2679: &add_filetype($allfiles,$attr->{'href'},'href');
2680: }
2681: }
1.640 albertel 2682: if (lc($tagname) eq 'object' ||
2683: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2684: foreach my $item (keys(%javafiles)) {
2685: $javafiles{$item} = '';
2686: }
2687: }
2688: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2689: my $name = lc($attr->{'name'});
2690: foreach my $item (keys(%javafiles)) {
2691: if ($name eq $item) {
2692: $javafiles{$item} = $attr->{'value'};
2693: last;
2694: }
2695: }
2696: foreach my $item (keys(%mediafiles)) {
2697: if ($name eq $item) {
2698: &add_filetype($allfiles, $attr->{'value'}, 'value');
2699: last;
2700: }
2701: }
2702: }
2703: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2704: foreach my $item (keys(%javafiles)) {
2705: if ($attr->{$item}) {
2706: $javafiles{$item} = $attr->{$item};
2707: last;
2708: }
2709: }
2710: foreach my $item (keys(%mediafiles)) {
2711: if ($attr->{$item}) {
2712: &add_filetype($allfiles,$attr->{$item},$item);
2713: last;
2714: }
2715: }
2716: }
2717: } elsif ($t->[0] eq 'E') {
2718: my ($tagname) = ($t->[1]);
2719: if ($javafiles{'codebase'} ne '') {
2720: $javafiles{'codebase'} .= '/';
2721: }
2722: if (lc($tagname) eq 'applet' ||
2723: lc($tagname) eq 'object' ||
2724: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2725: ) {
2726: foreach my $item (keys(%javafiles)) {
2727: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2728: my $file=$javafiles{'codebase'}.$javafiles{$item};
2729: &add_filetype($allfiles,$file,$item);
2730: }
2731: }
2732: }
2733: pop @state;
2734: }
2735: }
1.637 raeburn 2736: return 'ok';
2737: }
2738:
1.639 albertel 2739: sub add_filetype {
2740: my ($allfiles,$file,$type)=@_;
2741: if (exists($allfiles->{$file})) {
2742: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2743: push(@{$allfiles->{$file}}, &escape($type));
2744: }
2745: } else {
2746: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2747: }
2748: }
2749:
1.493 albertel 2750: sub removeuploadedurl {
1.984 neumanie 2751: my ($url)=@_;
2752: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2753: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2754: }
2755:
2756: sub removeuserfile {
2757: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2758: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2759: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2760: if ($result eq 'ok') {
1.798 raeburn 2761: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2762: my $metafile = $fname.'.meta';
2763: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2764: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2765: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2766: my $sqlresult =
1.823 albertel 2767: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2768: 'portfolio_metadata',$group,
2769: 'delete');
1.798 raeburn 2770: }
2771: }
2772: return $result;
1.257 www 2773: }
1.15 www 2774:
1.530 albertel 2775: sub mkdiruserfile {
2776: my ($docuname,$docudom,$dir)=@_;
2777: my $home=&homeserver($docuname,$docudom);
2778: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2779: }
2780:
1.531 albertel 2781: sub renameuserfile {
2782: my ($docuname,$docudom,$old,$new)=@_;
2783: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2784: my $result = &reply("renameuserfile:$docudom:$docuname:".
2785: &escape("$old").':'.&escape("$new"),$home);
2786: if ($result eq 'ok') {
2787: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2788: my $oldmeta = $old.'.meta';
2789: my $newmeta = $new.'.meta';
2790: my $metaresult =
2791: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2792: my $url = "/uploaded/$docudom/$docuname/$old";
2793: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2794: my $sqlresult =
1.823 albertel 2795: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2796: 'portfolio_metadata',$group,
2797: 'delete');
1.798 raeburn 2798: }
2799: }
2800: return $result;
1.531 albertel 2801: }
2802:
1.14 www 2803: # ------------------------------------------------------------------------- Log
2804:
2805: sub log {
2806: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2807: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2808: }
2809:
2810: # ------------------------------------------------------------------ Course Log
1.352 www 2811: #
2812: # This routine flushes several buffers of non-mission-critical nature
2813: #
1.157 www 2814:
2815: sub flushcourselogs {
1.352 www 2816: &logthis('Flushing log buffers');
2817: #
2818: # course logs
2819: # This is a log of all transactions in a course, which can be used
2820: # for data mining purposes
2821: #
2822: # It also collects the courseid database, which lists last transaction
2823: # times and course titles for all courseids
2824: #
2825: my %courseidbuffer=();
1.921 raeburn 2826: foreach my $crsid (keys(%courselogs)) {
1.352 www 2827: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2828: &escape($courselogs{$crsid}),
2829: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2830: delete $courselogs{$crsid};
2831: } else {
2832: &logthis('Failed to flush log buffer for '.$crsid);
2833: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2834: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2835: " exceeded maximum size, deleting.</font>");
2836: delete $courselogs{$crsid};
2837: }
1.352 www 2838: }
1.920 raeburn 2839: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2840: 'description' => $coursedescrbuf{$crsid},
2841: 'inst_code' => $courseinstcodebuf{$crsid},
2842: 'type' => $coursetypebuf{$crsid},
2843: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2844: };
1.191 harris41 2845: }
1.352 www 2846: #
2847: # Write course id database (reverse lookup) to homeserver of courses
2848: # Is used in pickcourse
2849: #
1.840 albertel 2850: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2851: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2852: $courseidbuffer{$crs_home},
2853: $crs_home,'timeonly');
1.352 www 2854: }
2855: #
2856: # File accesses
2857: # Writes to the dynamic metadata of resources to get hit counts, etc.
2858: #
1.449 matthew 2859: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2860: if ($entry =~ /___count$/) {
2861: my ($dom,$name);
1.807 albertel 2862: ($dom,$name,undef)=
1.811 albertel 2863: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2864: if (! defined($dom) || $dom eq '' ||
2865: ! defined($name) || $name eq '') {
1.620 albertel 2866: my $cid = $env{'request.course.id'};
2867: $dom = $env{'request.'.$cid.'.domain'};
2868: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2869: }
1.450 matthew 2870: my $value = $accesshash{$entry};
2871: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2872: my %temphash=($url => $value);
1.449 matthew 2873: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2874: if ($result eq 'ok') {
2875: delete $accesshash{$entry};
2876: } elsif ($result eq 'unknown_cmd') {
2877: # Target server has old code running on it.
1.450 matthew 2878: my %temphash=($entry => $value);
1.449 matthew 2879: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2880: delete $accesshash{$entry};
2881: }
2882: }
2883: } else {
1.811 albertel 2884: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2885: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2886: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2887: delete $accesshash{$entry};
2888: }
1.185 www 2889: }
1.191 harris41 2890: }
1.352 www 2891: #
2892: # Roles
2893: # Reverse lookup of user roles for course faculty/staff and co-authorship
2894: #
1.800 albertel 2895: foreach my $entry (keys(%userrolehash)) {
1.351 www 2896: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2897: split(/\:/,$entry);
2898: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2899: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2900: $rudom,$runame) eq 'ok') {
2901: delete $userrolehash{$entry};
2902: }
2903: }
1.662 raeburn 2904: #
2905: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2906: #
2907: my %domrolebuffer = ();
1.1000 raeburn 2908: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2909: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2910: if ($domrolebuffer{$rudom}) {
2911: $domrolebuffer{$rudom}.='&'.&escape($entry).
2912: '='.&escape($domainrolehash{$entry});
2913: } else {
2914: $domrolebuffer{$rudom}.=&escape($entry).
2915: '='.&escape($domainrolehash{$entry});
2916: }
2917: delete $domainrolehash{$entry};
2918: }
2919: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2920: my %servers = &get_servers($dom,'library');
2921: foreach my $tryserver (keys(%servers)) {
2922: unless (&reply('domroleput:'.$dom.':'.
2923: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2924: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2925: }
1.662 raeburn 2926: }
2927: }
1.186 www 2928: $dumpcount++;
1.157 www 2929: }
2930:
2931: sub courselog {
2932: my $what=shift;
1.158 www 2933: $what=time.':'.$what;
1.620 albertel 2934: unless ($env{'request.course.id'}) { return ''; }
2935: $coursedombuf{$env{'request.course.id'}}=
2936: $env{'course.'.$env{'request.course.id'}.'.domain'};
2937: $coursenumbuf{$env{'request.course.id'}}=
2938: $env{'course.'.$env{'request.course.id'}.'.num'};
2939: $coursehombuf{$env{'request.course.id'}}=
2940: $env{'course.'.$env{'request.course.id'}.'.home'};
2941: $coursedescrbuf{$env{'request.course.id'}}=
2942: $env{'course.'.$env{'request.course.id'}.'.description'};
2943: $courseinstcodebuf{$env{'request.course.id'}}=
2944: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2945: $courseownerbuf{$env{'request.course.id'}}=
2946: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2947: $coursetypebuf{$env{'request.course.id'}}=
2948: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2949: if (defined $courselogs{$env{'request.course.id'}}) {
2950: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2951: } else {
1.620 albertel 2952: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2953: }
1.620 albertel 2954: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2955: &flushcourselogs();
2956: }
1.158 www 2957: }
2958:
2959: sub courseacclog {
2960: my $fnsymb=shift;
1.620 albertel 2961: unless ($env{'request.course.id'}) { return ''; }
2962: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2963: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2964: $what.=':POST';
1.583 matthew 2965: # FIXME: Probably ought to escape things....
1.800 albertel 2966: foreach my $key (keys(%env)) {
2967: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2968: my $formitem = $1;
2969: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2970: $what.=':'.$formitem.'='.$env{$key};
2971: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2972: $what.=':'.$formitem.'='.$env{$key};
2973: }
1.158 www 2974: }
1.191 harris41 2975: }
1.583 matthew 2976: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2977: # FIXME: We should not be depending on a form parameter that someone
2978: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2979: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2980: $what.= ':POST';
2981: # FIXME: Probably ought to escape things....
2982: foreach my $element ('courseexp','crsfulltext','crsrelated',
2983: 'crsdiscuss') {
1.620 albertel 2984: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2985: }
2986: }
1.158 www 2987: }
2988: &courselog($what);
1.149 www 2989: }
2990:
1.185 www 2991: sub countacc {
2992: my $url=&declutter(shift);
1.458 matthew 2993: return if (! defined($url) || $url eq '');
1.620 albertel 2994: unless ($env{'request.course.id'}) { return ''; }
2995: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2996: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2997: $accesshash{$key}++;
1.185 www 2998: }
1.349 www 2999:
1.361 www 3000: sub linklog {
3001: my ($from,$to)=@_;
3002: $from=&declutter($from);
3003: $to=&declutter($to);
3004: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3005: $accesshash{$to.'___'.$from.'___goto'}=1;
3006: }
3007:
1.349 www 3008: sub userrolelog {
3009: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3010: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3011: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3012: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3013: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3014: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3015: $userrolehash
3016: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3017: =$tend.':'.$tstart;
1.662 raeburn 3018: }
1.898 albertel 3019: if (($env{'request.role'} =~ /dc\./) &&
3020: (($trole=~/^au/) || ($trole=~/^in/) ||
3021: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3022: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3023: ($trole=~/^co/))) {
1.898 albertel 3024: $userrolehash
3025: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3026: =$tend.':'.$tstart;
3027: }
1.662 raeburn 3028: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3029: ($trole=~/^li/) || ($trole=~/^li/) ||
3030: ($trole=~/^au/) || ($trole=~/^dg/) ||
3031: ($trole=~/^sc/)) {
3032: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3033: $domainrolehash
3034: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3035: = $tend.':'.$tstart;
3036: }
1.351 www 3037: }
3038:
1.957 raeburn 3039: sub courserolelog {
3040: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3041: if (($trole eq 'cc') || ($trole eq 'in') ||
3042: ($trole eq 'ep') || ($trole eq 'ad') ||
3043: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3044: ($trole=~/^cr/) || ($trole eq 'gr') ||
3045: ($trole eq 'co')) {
1.957 raeburn 3046: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3047: my $cdom = $1;
3048: my $cnum = $2;
3049: my $sec = $3;
3050: my $namespace = 'rolelog';
3051: my %storehash = (
3052: role => $trole,
3053: start => $tstart,
3054: end => $tend,
3055: selfenroll => $selfenroll,
3056: context => $context,
3057: );
3058: if ($trole eq 'gr') {
3059: $namespace = 'groupslog';
3060: $storehash{'group'} = $sec;
3061: } else {
3062: $storehash{'section'} = $sec;
3063: }
3064: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3065: if (($trole ne 'st') || ($sec ne '')) {
3066: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3067: }
1.957 raeburn 3068: }
3069: }
3070: return;
3071: }
3072:
1.351 www 3073: sub get_course_adv_roles {
1.948 raeburn 3074: my ($cid,$codes) = @_;
1.620 albertel 3075: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3076: my %coursehash=&coursedescription($cid);
1.988 raeburn 3077: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3078: my %nothide=();
1.800 albertel 3079: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3080: if ($user !~ /:/) {
3081: $nothide{join(':',split(/[\@]/,$user))}=1;
3082: } else {
3083: $nothide{$user}=1;
3084: }
1.470 www 3085: }
1.351 www 3086: my %returnhash=();
3087: my %dumphash=
3088: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3089: my $now=time;
1.997 raeburn 3090: my %privileged;
1.1000 raeburn 3091: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3092: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3093: if (($tstart) && ($tstart<0)) { next; }
3094: if (($tend) && ($tend<$now)) { next; }
3095: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3096: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3097: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3098: unless (ref($privileged{$domain}) eq 'HASH') {
3099: my %dompersonnel =
1.998 raeburn 3100: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3101: $privileged{$domain} = {};
3102: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3103: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3104: foreach my $user (keys(%{$dompersonnel{$server}})) {
3105: my ($trole,$uname,$udom) = split(/:/,$user);
3106: $privileged{$udom}{$uname} = 1;
3107: }
3108: }
3109: }
3110: }
3111: if ((exists($privileged{$domain}{$username})) &&
3112: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3113: if ($role eq 'cr') { next; }
1.948 raeburn 3114: if ($codes) {
3115: if ($section) { $role .= ':'.$section; }
3116: if ($returnhash{$role}) {
3117: $returnhash{$role}.=','.$username.':'.$domain;
3118: } else {
3119: $returnhash{$role}=$username.':'.$domain;
3120: }
1.351 www 3121: } else {
1.988 raeburn 3122: my $key=&plaintext($role,$crstype);
1.973 bisitz 3123: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3124: if ($returnhash{$key}) {
3125: $returnhash{$key}.=','.$username.':'.$domain;
3126: } else {
3127: $returnhash{$key}=$username.':'.$domain;
3128: }
1.351 www 3129: }
1.948 raeburn 3130: }
1.400 www 3131: return %returnhash;
3132: }
3133:
3134: sub get_my_roles {
1.937 raeburn 3135: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3136: unless (defined($uname)) { $uname=$env{'user.name'}; }
3137: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3138: my (%dumphash,%nothide);
1.1086 raeburn 3139: if ($context eq 'userroles') {
3140: my $extra = &freeze_escape({'skipcheck' => 1});
3141: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3142: } else {
3143: %dumphash=
1.400 www 3144: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3145: if ($hidepriv) {
3146: my %coursehash=&coursedescription($udom.'_'.$uname);
3147: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3148: if ($user !~ /:/) {
3149: $nothide{join(':',split(/[\@]/,$user))} = 1;
3150: } else {
3151: $nothide{$user} = 1;
3152: }
3153: }
3154: }
1.858 raeburn 3155: }
1.400 www 3156: my %returnhash=();
3157: my $now=time;
1.999 raeburn 3158: my %privileged;
1.800 albertel 3159: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3160: my ($role,$tend,$tstart);
3161: if ($context eq 'userroles') {
3162: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3163: } else {
3164: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3165: }
1.400 www 3166: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3167: my $status = 'active';
1.939 raeburn 3168: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3169: $status = 'previous';
3170: }
3171: if (($tstart) && ($now<$tstart)) {
3172: $status = 'future';
3173: }
3174: if (ref($types) eq 'ARRAY') {
3175: if (!grep(/^\Q$status\E$/,@{$types})) {
3176: next;
3177: }
3178: } else {
3179: if ($status ne 'active') {
3180: next;
3181: }
3182: }
1.867 raeburn 3183: my ($rolecode,$username,$domain,$section,$area);
3184: if ($context eq 'userroles') {
3185: ($area,$rolecode) = split(/_/,$entry);
3186: (undef,$domain,$username,$section) = split(/\//,$area);
3187: } else {
3188: ($role,$username,$domain,$section) = split(/\:/,$entry);
3189: }
1.832 raeburn 3190: if (ref($roledoms) eq 'ARRAY') {
3191: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3192: next;
3193: }
3194: }
3195: if (ref($roles) eq 'ARRAY') {
3196: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3197: if ($role =~ /^cr\//) {
3198: if (!grep(/^cr$/,@{$roles})) {
3199: next;
3200: }
1.1104 raeburn 3201: } elsif ($role =~ /^gr\//) {
3202: if (!grep(/^gr$/,@{$roles})) {
3203: next;
3204: }
1.922 raeburn 3205: } else {
3206: next;
3207: }
1.832 raeburn 3208: }
1.867 raeburn 3209: }
1.937 raeburn 3210: if ($hidepriv) {
1.999 raeburn 3211: if ($context eq 'userroles') {
3212: if ((&privileged($username,$domain)) &&
3213: (!$nothide{$username.':'.$domain})) {
3214: next;
3215: }
3216: } else {
3217: unless (ref($privileged{$domain}) eq 'HASH') {
3218: my %dompersonnel =
3219: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3220: $privileged{$domain} = {};
3221: if (keys(%dompersonnel)) {
3222: foreach my $server (keys(%dompersonnel)) {
3223: if (ref($dompersonnel{$server}) eq 'HASH') {
3224: foreach my $user (keys(%{$dompersonnel{$server}})) {
3225: my ($trole,$uname,$udom) = split(/:/,$user);
3226: $privileged{$udom}{$uname} = $trole;
3227: }
3228: }
3229: }
3230: }
3231: }
3232: if (exists($privileged{$domain}{$username})) {
3233: if (!$nothide{$username.':'.$domain}) {
3234: next;
3235: }
3236: }
1.937 raeburn 3237: }
3238: }
1.933 raeburn 3239: if ($withsec) {
3240: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3241: $tstart.':'.$tend;
3242: } else {
3243: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3244: }
1.832 raeburn 3245: }
1.373 www 3246: return %returnhash;
1.399 www 3247: }
3248:
3249: # ----------------------------------------------------- Frontpage Announcements
3250: #
3251: #
3252:
3253: sub postannounce {
3254: my ($server,$text)=@_;
1.844 albertel 3255: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3256: unless ($text=~/\w/) { $text=''; }
3257: return &reply('setannounce:'.&escape($text),$server);
3258: }
3259:
3260: sub getannounce {
1.448 albertel 3261:
3262: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3263: my $announcement='';
1.800 albertel 3264: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3265: close($fh);
1.399 www 3266: if ($announcement=~/\w/) {
3267: return
3268: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3269: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3270: } else {
3271: return '';
3272: }
3273: } else {
3274: return '';
3275: }
1.351 www 3276: }
1.353 www 3277:
3278: # ---------------------------------------------------------- Course ID routines
3279: # Deal with domain's nohist_courseid.db files
3280: #
3281:
3282: sub courseidput {
1.921 raeburn 3283: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3284: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3285: my $outcome;
3286: if ($caller eq 'timeonly') {
3287: my $cids = '';
3288: foreach my $item (keys(%$storehash)) {
3289: $cids.=&escape($item).'&';
3290: }
3291: $cids=~s/\&$//;
3292: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3293: $coursehome);
3294: } else {
3295: my $items = '';
3296: foreach my $item (keys(%$storehash)) {
3297: $items.= &escape($item).'='.
3298: &freeze_escape($$storehash{$item}).'&';
3299: }
3300: $items=~s/\&$//;
3301: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3302: $coursehome);
1.918 raeburn 3303: }
3304: if ($outcome eq 'unknown_cmd') {
3305: my $what;
3306: foreach my $cid (keys(%$storehash)) {
3307: $what .= &escape($cid).'=';
1.921 raeburn 3308: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3309: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3310: }
3311: $what =~ s/\:$/&/;
3312: }
3313: $what =~ s/\&$//;
3314: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3315: } else {
3316: return $outcome;
3317: }
1.353 www 3318: }
3319:
3320: sub courseiddump {
1.921 raeburn 3321: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3322: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3323: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3324: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3325: my $as_hash = 1;
3326: my %returnhash;
3327: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3328: my %libserv = &all_library();
3329: foreach my $tryserver (keys(%libserv)) {
3330: if ( ( $hostidflag == 1
3331: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3332: || (!defined($hostidflag)) ) {
3333:
1.918 raeburn 3334: if (($domfilter eq '') ||
3335: (&host_domain($tryserver) eq $domfilter)) {
3336: my $rep =
3337: &reply('courseiddump:'.&host_domain($tryserver).':'.
3338: $sincefilter.':'.&escape($descfilter).':'.
3339: &escape($instcodefilter).':'.&escape($ownerfilter).
3340: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3341: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3342: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3343: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3344: &escape($cc_clone).':'.$cloneonly.':'.
3345: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3346: &escape($creationcontext).':'.$domcloner,
3347: $tryserver);
1.918 raeburn 3348: my @pairs=split(/\&/,$rep);
3349: foreach my $item (@pairs) {
3350: my ($key,$value)=split(/\=/,$item,2);
3351: $key = &unescape($key);
3352: next if ($key =~ /^error: 2 /);
3353: my $result = &thaw_unescape($value);
3354: if (ref($result) eq 'HASH') {
3355: $returnhash{$key}=$result;
3356: } else {
1.921 raeburn 3357: my @responses = split(/:/,$value);
3358: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3359: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3360: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3361: }
1.1008 raeburn 3362: }
1.353 www 3363: }
3364: }
3365: }
3366: }
3367: return %returnhash;
3368: }
3369:
1.1055 raeburn 3370: sub courselastaccess {
3371: my ($cdom,$cnum,$hostidref) = @_;
3372: my %returnhash;
3373: if ($cdom && $cnum) {
3374: my $chome = &homeserver($cnum,$cdom);
3375: if ($chome ne 'no_host') {
3376: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3377: &extract_lastaccess(\%returnhash,$rep);
3378: }
3379: } else {
3380: if (!$cdom) { $cdom=''; }
3381: my %libserv = &all_library();
3382: foreach my $tryserver (keys(%libserv)) {
3383: if (ref($hostidref) eq 'ARRAY') {
3384: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3385: }
3386: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3387: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3388: &extract_lastaccess(\%returnhash,$rep);
3389: }
3390: }
3391: }
3392: return %returnhash;
3393: }
3394:
3395: sub extract_lastaccess {
3396: my ($returnhash,$rep) = @_;
3397: if (ref($returnhash) eq 'HASH') {
3398: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3399: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3400: $rep eq '') {
3401: my @pairs=split(/\&/,$rep);
3402: foreach my $item (@pairs) {
3403: my ($key,$value)=split(/\=/,$item,2);
3404: $key = &unescape($key);
3405: next if ($key =~ /^error: 2 /);
3406: $returnhash->{$key} = &thaw_unescape($value);
3407: }
3408: }
3409: }
3410: return;
3411: }
3412:
1.658 raeburn 3413: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3414:
3415: sub dcmailput {
1.685 raeburn 3416: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3417: my $status = &Apache::lonnet::critical(
1.740 www 3418: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3419: &escape($message),$server);
1.662 raeburn 3420: return $status;
3421: }
3422:
1.658 raeburn 3423: sub dcmaildump {
3424: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3425: my %returnhash=();
1.846 albertel 3426:
3427: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3428: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3429: &escape($enddate).':';
3430: my @esc_senders=map { &escape($_)} @$senders;
3431: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3432: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3433: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3434: if (($key) && ($value)) {
3435: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3436: }
3437: }
3438: }
3439: return %returnhash;
3440: }
1.662 raeburn 3441: # ---------------------------------------------------------- Domain roles
3442:
3443: sub get_domain_roles {
3444: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3445: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3446: $startdate = '.';
3447: }
1.1018 raeburn 3448: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3449: $enddate = '.';
3450: }
1.922 raeburn 3451: my $rolelist;
3452: if (ref($roles) eq 'ARRAY') {
3453: $rolelist = join(':',@{$roles});
3454: }
1.662 raeburn 3455: my %personnel = ();
1.841 albertel 3456:
3457: my %servers = &get_servers($dom,'library');
3458: foreach my $tryserver (keys(%servers)) {
3459: %{$personnel{$tryserver}}=();
3460: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3461: &escape($startdate).':'.
3462: &escape($enddate).':'.
3463: &escape($rolelist), $tryserver))) {
3464: my ($key,$value) = split(/\=/,$line,2);
3465: if (($key) && ($value)) {
3466: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3467: }
3468: }
1.662 raeburn 3469: }
3470: return %personnel;
3471: }
1.658 raeburn 3472:
1.1057 www 3473: # ----------------------------------------------------------- Interval timing
1.149 www 3474:
1.504 albertel 3475: sub get_first_access {
3476: my ($type,$argsymb)=@_;
1.790 albertel 3477: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3478: if ($argsymb) { $symb=$argsymb; }
3479: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3480: if ($type eq 'course') {
3481: $res='course';
3482: } elsif ($type eq 'map') {
1.588 albertel 3483: $res=&symbread($map);
3484: } else {
3485: $res=$symb;
3486: }
3487: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3488: return $times{"$courseid\0$res"};
1.504 albertel 3489: }
3490:
3491: sub set_first_access {
3492: my ($type)=@_;
1.790 albertel 3493: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3494: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3495: if ($type eq 'course') {
3496: $res='course';
3497: } elsif ($type eq 'map') {
1.588 albertel 3498: $res=&symbread($map);
3499: } else {
3500: $res=$symb;
3501: }
3502: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3503: if (!$firstaccess) {
1.588 albertel 3504: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3505: }
3506: return 'already_set';
1.504 albertel 3507: }
3508:
1.110 www 3509: # --------------------------------------------- Set Expire Date for Spreadsheet
3510:
3511: sub expirespread {
3512: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3513: my $cid=$env{'request.course.id'};
1.110 www 3514: if ($cid) {
3515: my $now=time;
3516: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3517: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3518: $env{'course.'.$cid.'.num'}.
1.110 www 3519: ':nohist_expirationdates:'.
3520: &escape($key).'='.$now,
1.620 albertel 3521: $env{'course.'.$cid.'.home'})
1.110 www 3522: }
3523: return 'ok';
1.14 www 3524: }
3525:
1.109 www 3526: # ----------------------------------------------------- Devalidate Spreadsheets
3527:
3528: sub devalidate {
1.325 www 3529: my ($symb,$uname,$udom)=@_;
1.620 albertel 3530: my $cid=$env{'request.course.id'};
1.109 www 3531: if ($cid) {
1.391 matthew 3532: # delete the stored spreadsheets for
3533: # - the student level sheet of this user in course's homespace
3534: # - the assessment level sheet for this resource
3535: # for this user in user's homespace
1.553 albertel 3536: # - current conditional state info
1.325 www 3537: my $key=$uname.':'.$udom.':';
1.109 www 3538: my $status=
1.299 matthew 3539: &del('nohist_calculatedsheets',
1.391 matthew 3540: [$key.'studentcalc:'],
1.620 albertel 3541: $env{'course.'.$cid.'.domain'},
3542: $env{'course.'.$cid.'.num'})
1.133 albertel 3543: .' '.
3544: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3545: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3546: unless ($status eq 'ok ok') {
3547: &logthis('Could not devalidate spreadsheet '.
1.325 www 3548: $uname.' at '.$udom.' for '.
1.109 www 3549: $symb.': '.$status);
1.133 albertel 3550: }
1.553 albertel 3551: &delenv('user.state.'.$cid);
1.109 www 3552: }
3553: }
3554:
1.265 albertel 3555: sub get_scalar {
3556: my ($string,$end) = @_;
3557: my $value;
3558: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3559: $value = $1;
3560: } elsif ($$string =~ s/^([^&]*?)&//) {
3561: $value = $1;
3562: }
3563: return &unescape($value);
3564: }
3565:
3566: sub array2str {
3567: my (@array) = @_;
3568: my $result=&arrayref2str(\@array);
3569: $result=~s/^__ARRAY_REF__//;
3570: $result=~s/__END_ARRAY_REF__$//;
3571: return $result;
3572: }
3573:
1.204 albertel 3574: sub arrayref2str {
3575: my ($arrayref) = @_;
1.265 albertel 3576: my $result='__ARRAY_REF__';
1.204 albertel 3577: foreach my $elem (@$arrayref) {
1.265 albertel 3578: if(ref($elem) eq 'ARRAY') {
3579: $result.=&arrayref2str($elem).'&';
3580: } elsif(ref($elem) eq 'HASH') {
3581: $result.=&hashref2str($elem).'&';
3582: } elsif(ref($elem)) {
3583: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3584: } else {
3585: $result.=&escape($elem).'&';
3586: }
3587: }
3588: $result=~s/\&$//;
1.265 albertel 3589: $result .= '__END_ARRAY_REF__';
1.204 albertel 3590: return $result;
3591: }
3592:
1.168 albertel 3593: sub hash2str {
1.204 albertel 3594: my (%hash) = @_;
3595: my $result=&hashref2str(\%hash);
1.265 albertel 3596: $result=~s/^__HASH_REF__//;
3597: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3598: return $result;
3599: }
3600:
3601: sub hashref2str {
3602: my ($hashref)=@_;
1.265 albertel 3603: my $result='__HASH_REF__';
1.800 albertel 3604: foreach my $key (sort(keys(%$hashref))) {
3605: if (ref($key) eq 'ARRAY') {
3606: $result.=&arrayref2str($key).'=';
3607: } elsif (ref($key) eq 'HASH') {
3608: $result.=&hashref2str($key).'=';
3609: } elsif (ref($key)) {
1.265 albertel 3610: $result.='=';
1.800 albertel 3611: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3612: } else {
1.800 albertel 3613: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3614: }
3615:
1.800 albertel 3616: if(ref($hashref->{$key}) eq 'ARRAY') {
3617: $result.=&arrayref2str($hashref->{$key}).'&';
3618: } elsif(ref($hashref->{$key}) eq 'HASH') {
3619: $result.=&hashref2str($hashref->{$key}).'&';
3620: } elsif(ref($hashref->{$key})) {
1.265 albertel 3621: $result.='&';
1.800 albertel 3622: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3623: } else {
1.800 albertel 3624: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3625: }
3626: }
1.168 albertel 3627: $result=~s/\&$//;
1.265 albertel 3628: $result .= '__END_HASH_REF__';
1.168 albertel 3629: return $result;
3630: }
3631:
3632: sub str2hash {
1.265 albertel 3633: my ($string)=@_;
3634: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3635: return %$hash;
3636: }
3637:
3638: sub str2hashref {
1.168 albertel 3639: my ($string) = @_;
1.265 albertel 3640:
3641: my %hash;
3642:
3643: if($string !~ /^__HASH_REF__/) {
3644: if (! ($string eq '' || !defined($string))) {
3645: $hash{'error'}='Not hash reference';
3646: }
3647: return (\%hash, $string);
3648: }
3649:
3650: $string =~ s/^__HASH_REF__//;
3651:
3652: while($string !~ /^__END_HASH_REF__/) {
3653: #key
3654: my $key='';
3655: if($string =~ /^__HASH_REF__/) {
3656: ($key, $string)=&str2hashref($string);
3657: if(defined($key->{'error'})) {
3658: $hash{'error'}='Bad data';
3659: return (\%hash, $string);
3660: }
3661: } elsif($string =~ /^__ARRAY_REF__/) {
3662: ($key, $string)=&str2arrayref($string);
3663: if($key->[0] eq 'Array reference error') {
3664: $hash{'error'}='Bad data';
3665: return (\%hash, $string);
3666: }
3667: } else {
3668: $string =~ s/^(.*?)=//;
1.267 albertel 3669: $key=&unescape($1);
1.265 albertel 3670: }
3671: $string =~ s/^=//;
3672:
3673: #value
3674: my $value='';
3675: if($string =~ /^__HASH_REF__/) {
3676: ($value, $string)=&str2hashref($string);
3677: if(defined($value->{'error'})) {
3678: $hash{'error'}='Bad data';
3679: return (\%hash, $string);
3680: }
3681: } elsif($string =~ /^__ARRAY_REF__/) {
3682: ($value, $string)=&str2arrayref($string);
3683: if($value->[0] eq 'Array reference error') {
3684: $hash{'error'}='Bad data';
3685: return (\%hash, $string);
3686: }
3687: } else {
3688: $value=&get_scalar(\$string,'__END_HASH_REF__');
3689: }
3690: $string =~ s/^&//;
3691:
3692: $hash{$key}=$value;
1.204 albertel 3693: }
1.265 albertel 3694:
3695: $string =~ s/^__END_HASH_REF__//;
3696:
3697: return (\%hash, $string);
1.204 albertel 3698: }
3699:
3700: sub str2array {
1.265 albertel 3701: my ($string)=@_;
3702: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3703: return @$array;
3704: }
3705:
3706: sub str2arrayref {
1.204 albertel 3707: my ($string) = @_;
1.265 albertel 3708: my @array;
3709:
3710: if($string !~ /^__ARRAY_REF__/) {
3711: if (! ($string eq '' || !defined($string))) {
3712: $array[0]='Array reference error';
3713: }
3714: return (\@array, $string);
3715: }
3716:
3717: $string =~ s/^__ARRAY_REF__//;
3718:
3719: while($string !~ /^__END_ARRAY_REF__/) {
3720: my $value='';
3721: if($string =~ /^__HASH_REF__/) {
3722: ($value, $string)=&str2hashref($string);
3723: if(defined($value->{'error'})) {
3724: $array[0] ='Array reference error';
3725: return (\@array, $string);
3726: }
3727: } elsif($string =~ /^__ARRAY_REF__/) {
3728: ($value, $string)=&str2arrayref($string);
3729: if($value->[0] eq 'Array reference error') {
3730: $array[0] ='Array reference error';
3731: return (\@array, $string);
3732: }
3733: } else {
3734: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3735: }
3736: $string =~ s/^&//;
3737:
3738: push(@array, $value);
1.191 harris41 3739: }
1.265 albertel 3740:
3741: $string =~ s/^__END_ARRAY_REF__//;
3742:
3743: return (\@array, $string);
1.168 albertel 3744: }
3745:
1.167 albertel 3746: # -------------------------------------------------------------------Temp Store
3747:
1.168 albertel 3748: sub tmpreset {
3749: my ($symb,$namespace,$domain,$stuname) = @_;
3750: if (!$symb) {
3751: $symb=&symbread();
1.620 albertel 3752: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3753: }
3754: $symb=escape($symb);
3755:
1.620 albertel 3756: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3757: $namespace=~s/\//\_/g;
3758: $namespace=~s/\W//g;
3759:
1.620 albertel 3760: if (!$domain) { $domain=$env{'user.domain'}; }
3761: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3762: if ($domain eq 'public' && $stuname eq 'public') {
3763: $stuname=$ENV{'REMOTE_ADDR'};
3764: }
1.168 albertel 3765: my $path=$perlvar{'lonDaemons'}.'/tmp';
3766: my %hash;
3767: if (tie(%hash,'GDBM_File',
3768: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3769: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3770: foreach my $key (keys(%hash)) {
1.180 albertel 3771: if ($key=~ /:$symb/) {
1.168 albertel 3772: delete($hash{$key});
3773: }
3774: }
3775: }
3776: }
3777:
1.167 albertel 3778: sub tmpstore {
1.168 albertel 3779: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3780:
3781: if (!$symb) {
3782: $symb=&symbread();
1.620 albertel 3783: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3784: }
3785: $symb=escape($symb);
3786:
3787: if (!$namespace) {
3788: # I don't think we would ever want to store this for a course.
3789: # it seems this will only be used if we don't have a course.
1.620 albertel 3790: #$namespace=$env{'request.course.id'};
1.168 albertel 3791: #if (!$namespace) {
1.620 albertel 3792: $namespace=$env{'request.state'};
1.168 albertel 3793: #}
3794: }
3795: $namespace=~s/\//\_/g;
3796: $namespace=~s/\W//g;
1.620 albertel 3797: if (!$domain) { $domain=$env{'user.domain'}; }
3798: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3799: if ($domain eq 'public' && $stuname eq 'public') {
3800: $stuname=$ENV{'REMOTE_ADDR'};
3801: }
1.168 albertel 3802: my $now=time;
3803: my %hash;
3804: my $path=$perlvar{'lonDaemons'}.'/tmp';
3805: if (tie(%hash,'GDBM_File',
3806: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3807: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3808: $hash{"version:$symb"}++;
3809: my $version=$hash{"version:$symb"};
3810: my $allkeys='';
3811: foreach my $key (keys(%$storehash)) {
3812: $allkeys.=$key.':';
1.591 albertel 3813: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3814: }
3815: $hash{"$version:$symb:timestamp"}=$now;
3816: $allkeys.='timestamp';
3817: $hash{"$version:keys:$symb"}=$allkeys;
3818: if (untie(%hash)) {
3819: return 'ok';
3820: } else {
3821: return "error:$!";
3822: }
3823: } else {
3824: return "error:$!";
3825: }
3826: }
1.167 albertel 3827:
1.168 albertel 3828: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3829:
1.168 albertel 3830: sub tmprestore {
3831: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3832:
1.168 albertel 3833: if (!$symb) {
3834: $symb=&symbread();
1.620 albertel 3835: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3836: }
3837: $symb=escape($symb);
3838:
1.620 albertel 3839: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3840:
1.620 albertel 3841: if (!$domain) { $domain=$env{'user.domain'}; }
3842: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3843: if ($domain eq 'public' && $stuname eq 'public') {
3844: $stuname=$ENV{'REMOTE_ADDR'};
3845: }
1.168 albertel 3846: my %returnhash;
3847: $namespace=~s/\//\_/g;
3848: $namespace=~s/\W//g;
3849: my %hash;
3850: my $path=$perlvar{'lonDaemons'}.'/tmp';
3851: if (tie(%hash,'GDBM_File',
3852: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3853: &GDBM_READER(),0640)) {
1.168 albertel 3854: my $version=$hash{"version:$symb"};
3855: $returnhash{'version'}=$version;
3856: my $scope;
3857: for ($scope=1;$scope<=$version;$scope++) {
3858: my $vkeys=$hash{"$scope:keys:$symb"};
3859: my @keys=split(/:/,$vkeys);
3860: my $key;
3861: $returnhash{"$scope:keys"}=$vkeys;
3862: foreach $key (@keys) {
1.591 albertel 3863: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3864: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3865: }
3866: }
1.168 albertel 3867: if (!(untie(%hash))) {
3868: return "error:$!";
3869: }
3870: } else {
3871: return "error:$!";
3872: }
3873: return %returnhash;
1.167 albertel 3874: }
3875:
1.9 www 3876: # ----------------------------------------------------------------------- Store
3877:
3878: sub store {
1.124 www 3879: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3880: my $home='';
3881:
1.168 albertel 3882: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3883:
1.213 www 3884: $symb=&symbclean($symb);
1.122 albertel 3885: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3886:
1.620 albertel 3887: if (!$domain) { $domain=$env{'user.domain'}; }
3888: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3889:
3890: &devalidate($symb,$stuname,$domain);
1.109 www 3891:
3892: $symb=escape($symb);
1.187 www 3893: if (!$namespace) {
1.620 albertel 3894: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3895: return '';
3896: }
3897: }
1.620 albertel 3898: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3899:
3900: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3901: $$storehash{'host'}=$perlvar{'lonHostID'};
3902:
1.12 www 3903: my $namevalue='';
1.800 albertel 3904: foreach my $key (keys(%$storehash)) {
3905: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3906: }
1.12 www 3907: $namevalue=~s/\&$//;
1.187 www 3908: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3909: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3910: }
3911:
1.47 www 3912: # -------------------------------------------------------------- Critical Store
3913:
3914: sub cstore {
1.124 www 3915: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3916: my $home='';
3917:
1.168 albertel 3918: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3919:
1.213 www 3920: $symb=&symbclean($symb);
1.122 albertel 3921: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3922:
1.620 albertel 3923: if (!$domain) { $domain=$env{'user.domain'}; }
3924: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3925:
3926: &devalidate($symb,$stuname,$domain);
1.109 www 3927:
3928: $symb=escape($symb);
1.187 www 3929: if (!$namespace) {
1.620 albertel 3930: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3931: return '';
3932: }
3933: }
1.620 albertel 3934: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3935:
3936: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3937: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3938:
1.47 www 3939: my $namevalue='';
1.800 albertel 3940: foreach my $key (keys(%$storehash)) {
3941: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3942: }
1.47 www 3943: $namevalue=~s/\&$//;
1.187 www 3944: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3945: return critical
3946: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3947: }
3948:
1.9 www 3949: # --------------------------------------------------------------------- Restore
3950:
3951: sub restore {
1.124 www 3952: my ($symb,$namespace,$domain,$stuname) = @_;
3953: my $home='';
3954:
1.168 albertel 3955: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3956:
1.122 albertel 3957: if (!$symb) {
3958: unless ($symb=escape(&symbread())) { return ''; }
3959: } else {
1.213 www 3960: $symb=&escape(&symbclean($symb));
1.122 albertel 3961: }
1.188 www 3962: if (!$namespace) {
1.620 albertel 3963: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3964: return '';
3965: }
3966: }
1.620 albertel 3967: if (!$domain) { $domain=$env{'user.domain'}; }
3968: if (!$stuname) { $stuname=$env{'user.name'}; }
3969: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3970: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3971:
1.12 www 3972: my %returnhash=();
1.800 albertel 3973: foreach my $line (split(/\&/,$answer)) {
3974: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3975: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3976: }
1.75 www 3977: my $version;
3978: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3979: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3980: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3981: }
1.75 www 3982: }
1.13 www 3983: return %returnhash;
1.34 www 3984: }
3985:
3986: # ---------------------------------------------------------- Course Description
3987:
3988: sub coursedescription {
1.731 albertel 3989: my ($courseid,$args)=@_;
1.34 www 3990: $courseid=~s/^\///;
1.49 www 3991: $courseid=~s/\_/\//g;
1.34 www 3992: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3993: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3994: my $normalid=$cdomain.'_'.$cnum;
3995: # need to always cache even if we get errors otherwise we keep
3996: # trying and trying and trying to get the course description.
3997: my %envhash=();
3998: my %returnhash=();
1.731 albertel 3999:
4000: my $expiretime=600;
4001: if ($env{'request.course.id'} eq $normalid) {
4002: $expiretime=120;
4003: }
4004:
4005: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4006: if (!$args->{'freshen_cache'}
4007: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4008: foreach my $key (keys(%env)) {
4009: next if ($key !~ /^\Q$prefix\E(.*)/);
4010: my ($setting) = $1;
4011: $returnhash{$setting} = $env{$key};
4012: }
4013: return %returnhash;
4014: }
4015:
4016: # get the data agin
4017: if (!$args->{'one_time'}) {
4018: $envhash{'course.'.$normalid.'.last_cache'}=time;
4019: }
1.811 albertel 4020:
1.34 www 4021: if ($chome ne 'no_host') {
1.302 albertel 4022: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4023: if (!exists($returnhash{'con_lost'})) {
4024: $returnhash{'home'}= $chome;
4025: $returnhash{'domain'} = $cdomain;
4026: $returnhash{'num'} = $cnum;
1.741 raeburn 4027: if (!defined($returnhash{'type'})) {
4028: $returnhash{'type'} = 'Course';
4029: }
1.130 albertel 4030: while (my ($name,$value) = each %returnhash) {
1.53 www 4031: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4032: }
1.270 www 4033: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4034: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4035: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4036: $envhash{'course.'.$normalid.'.home'}=$chome;
4037: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4038: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4039: }
4040: }
1.731 albertel 4041: if (!$args->{'one_time'}) {
1.949 raeburn 4042: &appenv(\%envhash);
1.731 albertel 4043: }
1.302 albertel 4044: return %returnhash;
1.461 www 4045: }
4046:
1.1080 raeburn 4047: sub update_released_required {
4048: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4049: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4050: $cid = $env{'request.course.id'};
4051: $cdom = $env{'course.'.$cid.'.domain'};
4052: $cnum = $env{'course.'.$cid.'.num'};
4053: $chome = $env{'course.'.$cid.'.home'};
4054: }
4055: if ($needsrelease) {
4056: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4057: my $needsupdate;
4058: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4059: $needsupdate = 1;
4060: } else {
4061: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4062: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4063: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4064: $needsupdate = 1;
4065: }
4066: }
4067: if ($needsupdate) {
4068: my %needshash = (
4069: 'internal.releaserequired' => $needsrelease,
4070: );
4071: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4072: if ($putresult eq 'ok') {
4073: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4074: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4075: if (ref($crsinfo{$cid}) eq 'HASH') {
4076: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4077: &courseidput($cdom,\%crsinfo,$chome,'notime');
4078: }
4079: }
4080: }
4081: }
4082: return;
4083: }
4084:
1.461 www 4085: # -------------------------------------------------See if a user is privileged
4086:
4087: sub privileged {
4088: my ($username,$domain)=@_;
4089: my $rolesdump=&reply("dump:$domain:$username:roles",
4090: &homeserver($username,$domain));
1.1033 raeburn 4091: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4092: ($rolesdump =~ /^error:/)) {
4093: return 0;
4094: }
1.461 www 4095: my $now=time;
4096: if ($rolesdump ne '') {
1.800 albertel 4097: foreach my $entry (split(/&/,$rolesdump)) {
4098: if ($entry!~/^rolesdef_/) {
4099: my ($area,$role)=split(/=/,$entry);
1.461 www 4100: $area=~s/\_\w\w$//;
4101: my ($trole,$tend,$tstart)=split(/_/,$role);
4102: if (($trole eq 'dc') || ($trole eq 'su')) {
4103: my $active=1;
4104: if ($tend) {
4105: if ($tend<$now) { $active=0; }
4106: }
4107: if ($tstart) {
4108: if ($tstart>$now) { $active=0; }
4109: }
4110: if ($active) { return 1; }
4111: }
4112: }
4113: }
4114: }
4115: return 0;
1.9 www 4116: }
1.1 albertel 4117:
1.103 harris41 4118: # -------------------------------------------------------- Get user privileges
1.11 www 4119:
4120: sub rolesinit {
4121: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4122: my $now=time;
4123: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4124: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4125: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4126: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4127: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4128: return \%userroles;
4129: }
1.11 www 4130: my %allroles=();
1.678 raeburn 4131: my %allgroups=();
1.11 www 4132:
4133: if ($rolesdump ne '') {
1.800 albertel 4134: foreach my $entry (split(/&/,$rolesdump)) {
4135: if ($entry!~/^rolesdef_/) {
4136: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4137: $area=~s/\_\w\w$//;
1.678 raeburn 4138: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4139: if ($role=~/^cr/) {
1.807 albertel 4140: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4141: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4142: ($tend,$tstart)=split('_',$trest);
4143: } else {
4144: $trole=$role;
4145: }
1.678 raeburn 4146: } elsif ($role =~ m|^gr/|) {
4147: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4148: next if ($tstart eq '-1');
1.678 raeburn 4149: ($trole,$group_privs) = split(/\//,$trole);
4150: $group_privs = &unescape($group_privs);
1.587 albertel 4151: } else {
4152: ($trole,$tend,$tstart)=split(/_/,$role);
4153: }
1.743 albertel 4154: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4155: $username);
4156: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4157: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4158: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4159: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4160: my $spec=$trole.'.'.$area;
4161: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4162: if ($trole =~ /^cr\//) {
1.567 raeburn 4163: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4164: } elsif ($trole eq 'gr') {
4165: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4166: } else {
1.567 raeburn 4167: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4168: }
1.12 www 4169: }
1.662 raeburn 4170: }
1.191 harris41 4171: }
1.743 albertel 4172: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4173: $userroles{'user.adv'} = $adv;
4174: $userroles{'user.author'} = $author;
1.620 albertel 4175: $env{'user.adv'}=$adv;
1.11 www 4176: }
1.743 albertel 4177: return \%userroles;
1.11 www 4178: }
4179:
1.567 raeburn 4180: sub set_arearole {
4181: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4182: # log the associated role with the area
4183: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4184: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4185: }
4186:
4187: sub custom_roleprivs {
4188: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4189: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4190: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4191: if (&hostname($homsvr) ne '') {
1.567 raeburn 4192: my ($rdummy,$roledef)=
4193: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4194: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4195: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4196: if (defined($syspriv)) {
1.1043 raeburn 4197: if ($trest =~ /^$match_community$/) {
4198: $syspriv =~ s/bre\&S//;
4199: }
1.567 raeburn 4200: $$allroles{'cm./'}.=':'.$syspriv;
4201: $$allroles{$spec.'./'}.=':'.$syspriv;
4202: }
4203: if ($tdomain ne '') {
4204: if (defined($dompriv)) {
4205: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4206: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4207: }
4208: if (($trest ne '') && (defined($coursepriv))) {
4209: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4210: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4211: }
4212: }
4213: }
4214: }
4215: }
4216:
1.678 raeburn 4217: sub group_roleprivs {
4218: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4219: my $access = 1;
4220: my $now = time;
4221: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4222: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4223: if ($access) {
1.811 albertel 4224: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4225: $$allgroups{$course}{$group} .=':'.$group_privs;
4226: }
4227: }
1.567 raeburn 4228:
4229: sub standard_roleprivs {
4230: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4231: if (defined($pr{$trole.':s'})) {
4232: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4233: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4234: }
4235: if ($tdomain ne '') {
4236: if (defined($pr{$trole.':d'})) {
4237: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4238: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4239: }
4240: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4241: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4242: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4243: }
4244: }
4245: }
4246:
4247: sub set_userprivs {
1.1064 raeburn 4248: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4249: my $author=0;
4250: my $adv=0;
1.678 raeburn 4251: my %grouproles = ();
4252: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4253: my @groupkeys;
1.1000 raeburn 4254: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4255: push(@groupkeys,$role);
4256: }
4257: if (ref($groups_roles) eq 'HASH') {
4258: foreach my $key (keys(%{$groups_roles})) {
4259: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4260: push(@groupkeys,$key);
4261: }
4262: }
4263: }
4264: if (@groupkeys > 0) {
4265: foreach my $role (@groupkeys) {
4266: my ($trole,$area,$sec,$extendedarea);
4267: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4268: $trole = $1;
4269: $area = $2;
4270: $sec = $3;
4271: $extendedarea = $area.$sec;
4272: if (exists($$allgroups{$area})) {
4273: foreach my $group (keys(%{$$allgroups{$area}})) {
4274: my $spec = $trole.'.'.$extendedarea;
4275: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4276: $$allgroups{$area}{$group};
1.1064 raeburn 4277: }
1.678 raeburn 4278: }
4279: }
4280: }
4281: }
4282: }
1.800 albertel 4283: foreach my $group (keys(%grouproles)) {
4284: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4285: }
1.800 albertel 4286: foreach my $role (keys(%{$allroles})) {
4287: my %thesepriv;
1.941 raeburn 4288: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4289: foreach my $item (split(/:/,$$allroles{$role})) {
4290: if ($item ne '') {
4291: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4292: if ($restrictions eq '') {
4293: $thesepriv{$privilege}='F';
4294: } elsif ($thesepriv{$privilege} ne 'F') {
4295: $thesepriv{$privilege}.=$restrictions;
4296: }
4297: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4298: }
4299: }
4300: my $thesestr='';
1.1104 raeburn 4301: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4302: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4303: }
4304: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4305: }
4306: return ($author,$adv);
4307: }
4308:
1.994 raeburn 4309: sub role_status {
1.1104 raeburn 4310: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4311: my @pwhere = ();
4312: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4313: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4314: unless (!defined($$role) || $$role eq '') {
4315: $$where=join('.',@pwhere);
4316: $$trolecode=$$role.'.'.$$where;
4317: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4318: $$tstatus='is';
1.1104 raeburn 4319: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4320: $$tstatus='future';
1.1034 raeburn 4321: if ($$tstart<$now) {
4322: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4323: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4324: my (%allroles,%allgroups,$group_privs,
4325: %groups_roles,@rolecodes);
1.1002 raeburn 4326: my %userroles = (
4327: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4328: );
1.1064 raeburn 4329: @rolecodes = ('cm');
1.1002 raeburn 4330: my $spec=$$role.'.'.$$where;
4331: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4332: if ($$role =~ /^cr\//) {
4333: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4334: push(@rolecodes,'cr');
1.1002 raeburn 4335: } elsif ($$role eq 'gr') {
1.1064 raeburn 4336: push(@rolecodes,$$role);
1.1002 raeburn 4337: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4338: $env{'user.name'});
1.1064 raeburn 4339: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4340: (undef,my $group_privs) = split(/\//,$trole);
4341: $group_privs = &unescape($group_privs);
4342: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4343: 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 4344: &get_groups_roles($tdomain,$trest,
4345: \%course_roles,\@rolecodes,
4346: \%groups_roles);
1.1002 raeburn 4347: } else {
1.1064 raeburn 4348: push(@rolecodes,$$role);
1.1002 raeburn 4349: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4350: }
1.1064 raeburn 4351: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4352: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4353: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4354: }
4355: }
1.1034 raeburn 4356: $$tstatus = 'is';
1.1002 raeburn 4357: }
1.994 raeburn 4358: }
4359: if ($$tend) {
1.1104 raeburn 4360: if ($$tend<$update) {
1.994 raeburn 4361: $$tstatus='expired';
4362: } elsif ($$tend<$now) {
4363: $$tstatus='will_not';
4364: }
4365: }
4366: }
4367: }
4368: }
4369:
1.1104 raeburn 4370: sub get_groups_roles {
4371: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4372: return unless((ref($cdom_courseroles) eq 'HASH') &&
4373: (ref($rolecodes) eq 'ARRAY') &&
4374: (ref($groups_roles) eq 'HASH'));
4375: if (keys(%{$cdom_courseroles}) > 0) {
4376: my ($cnum) = ($rest =~ /^($match_courseid)/);
4377: if ($cdom ne '' && $cnum ne '') {
4378: foreach my $key (keys(%{$cdom_courseroles})) {
4379: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4380: my $crsrole = $1;
4381: my $crssec = $2;
4382: if ($crsrole =~ /^cr/) {
4383: unless (grep(/^cr$/,@{$rolecodes})) {
4384: push(@{$rolecodes},'cr');
4385: }
4386: } else {
4387: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4388: push(@{$rolecodes},$crsrole);
4389: }
4390: }
4391: my $rolekey = "$crsrole./$cdom/$cnum";
4392: if ($crssec ne '') {
4393: $rolekey .= "/$crssec";
4394: }
4395: $rolekey .= './';
4396: $groups_roles->{$rolekey} = $rolecodes;
4397: }
4398: }
4399: }
4400: }
4401: return;
4402: }
4403:
4404: sub delete_env_groupprivs {
4405: my ($where,$courseroles,$possroles) = @_;
4406: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4407: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4408: unless (ref($courseroles->{$udom}) eq 'HASH') {
4409: %{$courseroles->{$udom}} =
4410: &get_my_roles('','','userroles',['active'],
4411: $possroles,[$udom],1);
4412: }
4413: if (ref($courseroles->{$udom}) eq 'HASH') {
4414: foreach my $item (keys(%{$courseroles->{$udom}})) {
4415: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4416: my $area = '/'.$cdom.'/'.$cnum;
4417: my $privkey = "user.priv.$crsrole.$area";
4418: if ($crssec ne '') {
4419: $privkey .= '/'.$crssec;
4420: }
4421: $privkey .= ".$area/$group";
4422: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4423: }
4424: }
4425: return;
4426: }
4427:
1.994 raeburn 4428: sub check_adhoc_privs {
1.1104 raeburn 4429: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4430: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4431: if ($env{$cckey}) {
4432: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4433: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4434: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4435: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4436: }
4437: } else {
1.1088 raeburn 4438: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4439: }
4440: }
4441:
4442: sub set_adhoc_privileges {
4443: # role can be cc or ca
1.1088 raeburn 4444: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4445: my $area = '/'.$dcdom.'/'.$pickedcourse;
4446: my $spec = $role.'.'.$area;
4447: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4448: $env{'user.name'});
4449: my %ccrole = ();
4450: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4451: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4452: &appenv(\%userroles,[$role,'cm']);
4453: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4454: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4455: &appenv( {'request.role' => $spec,
4456: 'request.role.domain' => $dcdom,
4457: 'request.course.sec' => ''
4458: }
4459: );
4460: my $tadv=0;
4461: if (&allowed('adv') eq 'F') { $tadv=1; }
4462: &appenv({'request.role.adv' => $tadv});
4463: }
1.994 raeburn 4464: }
4465:
1.12 www 4466: # --------------------------------------------------------------- get interface
4467:
4468: sub get {
1.131 albertel 4469: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4470: my $items='';
1.800 albertel 4471: foreach my $item (@$storearr) {
4472: $items.=&escape($item).'&';
1.191 harris41 4473: }
1.12 www 4474: $items=~s/\&$//;
1.620 albertel 4475: if (!$udomain) { $udomain=$env{'user.domain'}; }
4476: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4477: my $uhome=&homeserver($uname,$udomain);
4478:
1.133 albertel 4479: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4480: my @pairs=split(/\&/,$rep);
1.273 albertel 4481: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4482: return @pairs;
4483: }
1.15 www 4484: my %returnhash=();
1.42 www 4485: my $i=0;
1.800 albertel 4486: foreach my $item (@$storearr) {
4487: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4488: $i++;
1.191 harris41 4489: }
1.15 www 4490: return %returnhash;
1.27 www 4491: }
4492:
4493: # --------------------------------------------------------------- del interface
4494:
4495: sub del {
1.133 albertel 4496: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4497: my $items='';
1.800 albertel 4498: foreach my $item (@$storearr) {
4499: $items.=&escape($item).'&';
1.191 harris41 4500: }
1.984 neumanie 4501:
1.27 www 4502: $items=~s/\&$//;
1.620 albertel 4503: if (!$udomain) { $udomain=$env{'user.domain'}; }
4504: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4505: my $uhome=&homeserver($uname,$udomain);
4506: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4507: }
4508:
4509: # -------------------------------------------------------------- dump interface
4510:
4511: sub dump {
1.1086 raeburn 4512: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4513: if (!$udomain) { $udomain=$env{'user.domain'}; }
4514: if (!$uname) { $uname=$env{'user.name'}; }
4515: my $uhome=&homeserver($uname,$udomain);
4516: if ($regexp) {
4517: $regexp=&escape($regexp);
4518: } else {
4519: $regexp='.';
4520: }
1.1086 raeburn 4521: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4522: my @pairs=split(/\&/,$rep);
4523: my %returnhash=();
1.1098 foxr 4524: if (!($rep =~ /^error/ )) {
4525: foreach my $item (@pairs) {
4526: my ($key,$value)=split(/=/,$item,2);
4527: $key = &unescape($key);
4528: next if ($key =~ /^error: 2 /);
4529: $returnhash{$key}=&thaw_unescape($value);
4530: }
1.755 albertel 4531: }
4532: return %returnhash;
1.407 www 4533: }
4534:
1.1098 foxr 4535:
1.717 albertel 4536: # --------------------------------------------------------- dumpstore interface
4537:
4538: sub dumpstore {
4539: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4540: if (!$udomain) { $udomain=$env{'user.domain'}; }
4541: if (!$uname) { $uname=$env{'user.name'}; }
4542: my $uhome=&homeserver($uname,$udomain);
4543: if ($regexp) {
4544: $regexp=&escape($regexp);
4545: } else {
4546: $regexp='.';
4547: }
4548: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4549: my @pairs=split(/\&/,$rep);
4550: my %returnhash=();
4551: foreach my $item (@pairs) {
4552: my ($key,$value)=split(/=/,$item,2);
4553: next if ($key =~ /^error: 2 /);
4554: $returnhash{$key}=&thaw_unescape($value);
4555: }
4556: return %returnhash;
1.717 albertel 4557: }
4558:
1.407 www 4559: # -------------------------------------------------------------- keys interface
4560:
4561: sub getkeys {
4562: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4563: if (!$udomain) { $udomain=$env{'user.domain'}; }
4564: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4565: my $uhome=&homeserver($uname,$udomain);
4566: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4567: my @keyarray=();
1.800 albertel 4568: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4569: next if ($key =~ /^error: 2 /);
1.800 albertel 4570: push(@keyarray,&unescape($key));
1.407 www 4571: }
4572: return @keyarray;
1.318 matthew 4573: }
4574:
1.319 matthew 4575: # --------------------------------------------------------------- currentdump
4576: sub currentdump {
1.328 matthew 4577: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4578: $courseid = $env{'request.course.id'} if (! defined($courseid));
4579: $sdom = $env{'user.domain'} if (! defined($sdom));
4580: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4581: my $uhome = &homeserver($sname,$sdom);
4582: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4583: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4584: #
1.318 matthew 4585: my %returnhash=();
1.319 matthew 4586: #
4587: if ($rep eq "unknown_cmd") {
4588: # an old lond will not know currentdump
4589: # Do a dump and make it look like a currentdump
1.822 albertel 4590: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4591: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4592: my %hash = @tmp;
4593: @tmp=();
1.424 matthew 4594: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4595: } else {
4596: my @pairs=split(/\&/,$rep);
1.800 albertel 4597: foreach my $pair (@pairs) {
4598: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4599: my ($symb,$param) = split(/:/,$key);
4600: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4601: &thaw_unescape($value);
1.319 matthew 4602: }
1.191 harris41 4603: }
1.12 www 4604: return %returnhash;
1.424 matthew 4605: }
4606:
4607: sub convert_dump_to_currentdump{
4608: my %hash = %{shift()};
4609: my %returnhash;
4610: # Code ripped from lond, essentially. The only difference
4611: # here is the unescaping done by lonnet::dump(). Conceivably
4612: # we might run in to problems with parameter names =~ /^v\./
4613: while (my ($key,$value) = each(%hash)) {
4614: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4615: $symb = &unescape($symb);
4616: $param = &unescape($param);
1.424 matthew 4617: next if ($v eq 'version' || $symb eq 'keys');
4618: next if (exists($returnhash{$symb}) &&
4619: exists($returnhash{$symb}->{$param}) &&
4620: $returnhash{$symb}->{'v.'.$param} > $v);
4621: $returnhash{$symb}->{$param}=$value;
4622: $returnhash{$symb}->{'v.'.$param}=$v;
4623: }
4624: #
4625: # Remove all of the keys in the hashes which keep track of
4626: # the version of the parameter.
4627: while (my ($symb,$param_hash) = each(%returnhash)) {
4628: # use a foreach because we are going to delete from the hash.
4629: foreach my $key (keys(%$param_hash)) {
4630: delete($param_hash->{$key}) if ($key =~ /^v\./);
4631: }
4632: }
4633: return \%returnhash;
1.12 www 4634: }
4635:
1.627 albertel 4636: # ------------------------------------------------------ critical inc interface
4637:
4638: sub cinc {
4639: return &inc(@_,'critical');
4640: }
4641:
1.449 matthew 4642: # --------------------------------------------------------------- inc interface
4643:
4644: sub inc {
1.627 albertel 4645: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4646: if (!$udomain) { $udomain=$env{'user.domain'}; }
4647: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4648: my $uhome=&homeserver($uname,$udomain);
4649: my $items='';
4650: if (! ref($store)) {
4651: # got a single value, so use that instead
4652: $items = &escape($store).'=&';
4653: } elsif (ref($store) eq 'SCALAR') {
4654: $items = &escape($$store).'=&';
4655: } elsif (ref($store) eq 'ARRAY') {
4656: $items = join('=&',map {&escape($_);} @{$store});
4657: } elsif (ref($store) eq 'HASH') {
4658: while (my($key,$value) = each(%{$store})) {
4659: $items.= &escape($key).'='.&escape($value).'&';
4660: }
4661: }
4662: $items=~s/\&$//;
1.627 albertel 4663: if ($critical) {
4664: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4665: } else {
4666: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4667: }
1.449 matthew 4668: }
4669:
1.12 www 4670: # --------------------------------------------------------------- put interface
4671:
4672: sub put {
1.134 albertel 4673: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4674: if (!$udomain) { $udomain=$env{'user.domain'}; }
4675: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4676: my $uhome=&homeserver($uname,$udomain);
1.12 www 4677: my $items='';
1.800 albertel 4678: foreach my $item (keys(%$storehash)) {
4679: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4680: }
1.12 www 4681: $items=~s/\&$//;
1.134 albertel 4682: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4683: }
4684:
1.631 albertel 4685: # ------------------------------------------------------------ newput interface
4686:
4687: sub newput {
4688: my ($namespace,$storehash,$udomain,$uname)=@_;
4689: if (!$udomain) { $udomain=$env{'user.domain'}; }
4690: if (!$uname) { $uname=$env{'user.name'}; }
4691: my $uhome=&homeserver($uname,$udomain);
4692: my $items='';
4693: foreach my $key (keys(%$storehash)) {
4694: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4695: }
4696: $items=~s/\&$//;
4697: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4698: }
4699:
4700: # --------------------------------------------------------- putstore interface
4701:
1.524 raeburn 4702: sub putstore {
1.715 albertel 4703: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4704: if (!$udomain) { $udomain=$env{'user.domain'}; }
4705: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4706: my $uhome=&homeserver($uname,$udomain);
4707: my $items='';
1.715 albertel 4708: foreach my $key (keys(%$storehash)) {
4709: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4710: }
1.715 albertel 4711: $items=~s/\&$//;
1.716 albertel 4712: my $esc_symb=&escape($symb);
4713: my $esc_v=&escape($version);
1.715 albertel 4714: my $reply =
1.716 albertel 4715: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4716: $uhome);
4717: if ($reply eq 'unknown_cmd') {
1.716 albertel 4718: # gfall back to way things use to be done
1.715 albertel 4719: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4720: $uname);
1.524 raeburn 4721: }
1.715 albertel 4722: return $reply;
4723: }
4724:
4725: sub old_putstore {
1.716 albertel 4726: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4727: if (!$udomain) { $udomain=$env{'user.domain'}; }
4728: if (!$uname) { $uname=$env{'user.name'}; }
4729: my $uhome=&homeserver($uname,$udomain);
4730: my %newstorehash;
1.800 albertel 4731: foreach my $item (keys(%$storehash)) {
4732: my $key = $version.':'.&escape($symb).':'.$item;
4733: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4734: }
4735: my $items='';
4736: my %allitems = ();
1.800 albertel 4737: foreach my $item (keys(%newstorehash)) {
4738: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4739: my $key = $1.':keys:'.$2;
4740: $allitems{$key} .= $3.':';
4741: }
1.800 albertel 4742: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4743: }
1.800 albertel 4744: foreach my $item (keys(%allitems)) {
4745: $allitems{$item} =~ s/\:$//;
4746: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4747: }
4748: $items=~s/\&$//;
4749: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4750: }
4751:
1.47 www 4752: # ------------------------------------------------------ critical put interface
4753:
4754: sub cput {
1.134 albertel 4755: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4756: if (!$udomain) { $udomain=$env{'user.domain'}; }
4757: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4758: my $uhome=&homeserver($uname,$udomain);
1.47 www 4759: my $items='';
1.800 albertel 4760: foreach my $item (keys(%$storehash)) {
4761: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4762: }
1.47 www 4763: $items=~s/\&$//;
1.134 albertel 4764: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4765: }
4766:
4767: # -------------------------------------------------------------- eget interface
4768:
4769: sub eget {
1.133 albertel 4770: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4771: my $items='';
1.800 albertel 4772: foreach my $item (@$storearr) {
4773: $items.=&escape($item).'&';
1.191 harris41 4774: }
1.12 www 4775: $items=~s/\&$//;
1.620 albertel 4776: if (!$udomain) { $udomain=$env{'user.domain'}; }
4777: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4778: my $uhome=&homeserver($uname,$udomain);
4779: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4780: my @pairs=split(/\&/,$rep);
4781: my %returnhash=();
1.42 www 4782: my $i=0;
1.800 albertel 4783: foreach my $item (@$storearr) {
4784: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4785: $i++;
1.191 harris41 4786: }
1.12 www 4787: return %returnhash;
4788: }
4789:
1.667 albertel 4790: # ------------------------------------------------------------ tmpput interface
4791: sub tmpput {
1.802 raeburn 4792: my ($storehash,$server,$context)=@_;
1.667 albertel 4793: my $items='';
1.800 albertel 4794: foreach my $item (keys(%$storehash)) {
4795: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4796: }
4797: $items=~s/\&$//;
1.802 raeburn 4798: if (defined($context)) {
4799: $items .= ':'.&escape($context);
4800: }
1.667 albertel 4801: return &reply("tmpput:$items",$server);
4802: }
4803:
4804: # ------------------------------------------------------------ tmpget interface
4805: sub tmpget {
1.688 albertel 4806: my ($token,$server)=@_;
4807: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4808: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4809: my %returnhash;
4810: foreach my $item (split(/\&/,$rep)) {
4811: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4812: next if ($key =~ /^error: 2 /);
1.667 albertel 4813: $returnhash{&unescape($key)}=&thaw_unescape($value);
4814: }
4815: return %returnhash;
4816: }
4817:
1.1113 raeburn 4818: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 4819: sub tmpdel {
4820: my ($token,$server)=@_;
4821: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4822: return &reply("tmpdel:$token",$server);
4823: }
4824:
1.765 albertel 4825: # -------------------------------------------------- portfolio access checking
4826:
4827: sub portfolio_access {
1.766 albertel 4828: my ($requrl) = @_;
1.765 albertel 4829: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4830: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4831: if ($result) {
4832: my %setters;
4833: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4834: my ($startblock,$endblock) =
4835: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4836: if ($startblock && $endblock) {
4837: return 'B';
4838: }
4839: } else {
4840: my ($startblock,$endblock) =
4841: &Apache::loncommon::blockcheck(\%setters,'port');
4842: if ($startblock && $endblock) {
4843: return 'B';
4844: }
4845: }
4846: }
1.765 albertel 4847: if ($result eq 'ok') {
1.766 albertel 4848: return 'F';
1.765 albertel 4849: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4850: return 'A';
1.765 albertel 4851: }
1.766 albertel 4852: return '';
1.765 albertel 4853: }
4854:
4855: sub get_portfolio_access {
1.767 albertel 4856: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4857:
4858: if (!ref($access_hash)) {
4859: my $current_perms = &get_portfile_permissions($udom,$unum);
4860: my %access_controls = &get_access_controls($current_perms,$group,
4861: $file_name);
4862: $access_hash = $access_controls{$file_name};
4863: }
4864:
1.765 albertel 4865: my ($public,$guest,@domains,@users,@courses,@groups);
4866: my $now = time;
4867: if (ref($access_hash) eq 'HASH') {
4868: foreach my $key (keys(%{$access_hash})) {
4869: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4870: if ($start > $now) {
4871: next;
4872: }
4873: if ($end && $end<$now) {
4874: next;
4875: }
4876: if ($scope eq 'public') {
4877: $public = $key;
4878: last;
4879: } elsif ($scope eq 'guest') {
4880: $guest = $key;
4881: } elsif ($scope eq 'domains') {
4882: push(@domains,$key);
4883: } elsif ($scope eq 'users') {
4884: push(@users,$key);
4885: } elsif ($scope eq 'course') {
4886: push(@courses,$key);
4887: } elsif ($scope eq 'group') {
4888: push(@groups,$key);
4889: }
4890: }
4891: if ($public) {
4892: return 'ok';
4893: }
4894: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4895: if ($guest) {
4896: return $guest;
4897: }
4898: } else {
4899: if (@domains > 0) {
4900: foreach my $domkey (@domains) {
4901: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4902: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4903: return 'ok';
4904: }
4905: }
4906: }
4907: }
4908: if (@users > 0) {
4909: foreach my $userkey (@users) {
1.865 raeburn 4910: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4911: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4912: if (ref($item) eq 'HASH') {
4913: if (($item->{'uname'} eq $env{'user.name'}) &&
4914: ($item->{'udom'} eq $env{'user.domain'})) {
4915: return 'ok';
4916: }
4917: }
4918: }
4919: }
1.765 albertel 4920: }
4921: }
4922: my %roleshash;
4923: my @courses_and_groups = @courses;
4924: push(@courses_and_groups,@groups);
4925: if (@courses_and_groups > 0) {
4926: my (%allgroups,%allroles);
4927: my ($start,$end,$role,$sec,$group);
4928: foreach my $envkey (%env) {
1.1060 raeburn 4929: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4930: my $cid = $2.'_'.$3;
4931: if ($1 eq 'gr') {
4932: $group = $4;
4933: $allgroups{$cid}{$group} = $env{$envkey};
4934: } else {
4935: if ($4 eq '') {
4936: $sec = 'none';
4937: } else {
4938: $sec = $4;
4939: }
4940: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4941: }
1.811 albertel 4942: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4943: my $cid = $2.'_'.$3;
4944: if ($4 eq '') {
4945: $sec = 'none';
4946: } else {
4947: $sec = $4;
4948: }
4949: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4950: }
4951: }
4952: if (keys(%allroles) == 0) {
4953: return;
4954: }
4955: foreach my $key (@courses_and_groups) {
4956: my %content = %{$$access_hash{$key}};
4957: my $cnum = $content{'number'};
4958: my $cdom = $content{'domain'};
4959: my $cid = $cdom.'_'.$cnum;
4960: if (!exists($allroles{$cid})) {
4961: next;
4962: }
4963: foreach my $role_id (keys(%{$content{'roles'}})) {
4964: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4965: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4966: my @status = @{$content{'roles'}{$role_id}{'access'}};
4967: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4968: foreach my $role (keys(%{$allroles{$cid}})) {
4969: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4970: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4971: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4972: if (grep/^all$/,@sections) {
4973: return 'ok';
4974: } else {
4975: if (grep/^$sec$/,@sections) {
4976: return 'ok';
4977: }
4978: }
4979: }
4980: }
4981: if (keys(%{$allgroups{$cid}}) == 0) {
4982: if (grep/^none$/,@groups) {
4983: return 'ok';
4984: }
4985: } else {
4986: if (grep/^all$/,@groups) {
4987: return 'ok';
4988: }
4989: foreach my $group (keys(%{$allgroups{$cid}})) {
4990: if (grep/^$group$/,@groups) {
4991: return 'ok';
4992: }
4993: }
4994: }
4995: }
4996: }
4997: }
4998: }
4999: }
5000: if ($guest) {
5001: return $guest;
5002: }
5003: }
5004: }
5005: return;
5006: }
5007:
5008: sub course_group_datechecker {
5009: my ($dates,$now,$status) = @_;
5010: my ($start,$end) = split(/\./,$dates);
5011: if (!$start && !$end) {
5012: return 'ok';
5013: }
5014: if (grep/^active$/,@{$status}) {
5015: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5016: return 'ok';
5017: }
5018: }
5019: if (grep/^previous$/,@{$status}) {
5020: if ($end > $now ) {
5021: return 'ok';
5022: }
5023: }
5024: if (grep/^future$/,@{$status}) {
5025: if ($start > $now) {
5026: return 'ok';
5027: }
5028: }
5029: return;
5030: }
5031:
5032: sub parse_portfolio_url {
5033: my ($url) = @_;
5034:
5035: my ($type,$udom,$unum,$group,$file_name);
5036:
1.823 albertel 5037: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5038: $type = 1;
5039: $udom = $1;
5040: $unum = $2;
5041: $file_name = $3;
1.823 albertel 5042: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5043: $type = 2;
5044: $udom = $1;
5045: $unum = $2;
5046: $group = $3;
5047: $file_name = $3.'/'.$4;
5048: }
5049: if (wantarray) {
5050: return ($type,$udom,$unum,$file_name,$group);
5051: }
5052: return $type;
5053: }
5054:
5055: sub is_portfolio_url {
5056: my ($url) = @_;
5057: return scalar(&parse_portfolio_url($url));
5058: }
5059:
1.798 raeburn 5060: sub is_portfolio_file {
5061: my ($file) = @_;
1.820 raeburn 5062: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5063: return 1;
5064: }
5065: return;
5066: }
5067:
1.976 raeburn 5068: sub usertools_access {
1.1084 raeburn 5069: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5070: my ($access,%tools);
5071: if ($context eq '') {
5072: $context = 'tools';
5073: }
5074: if ($context eq 'requestcourses') {
5075: %tools = (
5076: official => 1,
5077: unofficial => 1,
1.1006 raeburn 5078: community => 1,
1.985 raeburn 5079: );
5080: } else {
5081: %tools = (
5082: aboutme => 1,
5083: blog => 1,
5084: portfolio => 1,
5085: );
5086: }
1.976 raeburn 5087: return if (!defined($tools{$tool}));
5088:
5089: if ((!defined($udom)) || (!defined($uname))) {
5090: $udom = $env{'user.domain'};
5091: $uname = $env{'user.name'};
5092: }
5093:
1.978 raeburn 5094: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5095: if ($action ne 'reload') {
1.985 raeburn 5096: if ($context eq 'requestcourses') {
5097: return $env{'environment.canrequest.'.$tool};
5098: } else {
5099: return $env{'environment.availabletools.'.$tool};
5100: }
5101: }
1.976 raeburn 5102: }
5103:
5104: my ($toolstatus,$inststatus);
5105:
1.985 raeburn 5106: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5107: ($action ne 'reload')) {
5108: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5109: $inststatus = $env{'environment.inststatus'};
5110: } else {
1.1084 raeburn 5111: if (ref($userenvref) eq 'HASH') {
5112: $toolstatus = $userenvref->{$context.'.'.$tool};
5113: $inststatus = $userenvref->{'inststatus'};
5114: } else {
5115: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5116: $toolstatus = $userenv{$context.'.'.$tool};
5117: $inststatus = $userenv{'inststatus'};
5118: }
1.976 raeburn 5119: }
5120:
5121: if ($toolstatus ne '') {
5122: if ($toolstatus) {
5123: $access = 1;
5124: } else {
5125: $access = 0;
5126: }
5127: return $access;
5128: }
5129:
1.1084 raeburn 5130: my ($is_adv,%domdef);
5131: if (ref($is_advref) eq 'HASH') {
5132: $is_adv = $is_advref->{'is_adv'};
5133: } else {
5134: $is_adv = &is_advanced_user($udom,$uname);
5135: }
5136: if (ref($domdefref) eq 'HASH') {
5137: %domdef = %{$domdefref};
5138: } else {
5139: %domdef = &get_domain_defaults($udom);
5140: }
1.976 raeburn 5141: if (ref($domdef{$tool}) eq 'HASH') {
5142: if ($is_adv) {
5143: if ($domdef{$tool}{'_LC_adv'} ne '') {
5144: if ($domdef{$tool}{'_LC_adv'}) {
5145: $access = 1;
5146: } else {
5147: $access = 0;
5148: }
5149: return $access;
5150: }
5151: }
5152: if ($inststatus ne '') {
5153: my ($hasaccess,$hasnoaccess);
5154: foreach my $affiliation (split(/:/,$inststatus)) {
5155: if ($domdef{$tool}{$affiliation} ne '') {
5156: if ($domdef{$tool}{$affiliation}) {
5157: $hasaccess = 1;
5158: } else {
5159: $hasnoaccess = 1;
5160: }
5161: }
5162: }
5163: if ($hasaccess || $hasnoaccess) {
5164: if ($hasaccess) {
5165: $access = 1;
5166: } elsif ($hasnoaccess) {
5167: $access = 0;
5168: }
5169: return $access;
5170: }
5171: } else {
5172: if ($domdef{$tool}{'default'} ne '') {
5173: if ($domdef{$tool}{'default'}) {
5174: $access = 1;
5175: } elsif ($domdef{$tool}{'default'} == 0) {
5176: $access = 0;
5177: }
5178: return $access;
5179: }
5180: }
5181: } else {
1.985 raeburn 5182: if ($context eq 'tools') {
5183: $access = 1;
5184: } else {
5185: $access = 0;
5186: }
1.976 raeburn 5187: return $access;
5188: }
5189: }
5190:
1.1050 raeburn 5191: sub is_course_owner {
5192: my ($cdom,$cnum,$udom,$uname) = @_;
5193: if (($udom eq '') || ($uname eq '')) {
5194: $udom = $env{'user.domain'};
5195: $uname = $env{'user.name'};
5196: }
5197: unless (($udom eq '') || ($uname eq '')) {
5198: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5199: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5200: return 1;
5201: } else {
5202: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5203: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5204: return 1;
5205: }
5206: }
5207: }
5208: }
5209: return;
5210: }
5211:
1.976 raeburn 5212: sub is_advanced_user {
5213: my ($udom,$uname) = @_;
1.1085 raeburn 5214: if ($udom ne '' && $uname ne '') {
5215: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5216: return $env{'user.adv'};
5217: }
5218: }
1.976 raeburn 5219: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5220: my %allroles;
5221: my $is_adv;
5222: foreach my $role (keys(%roleshash)) {
5223: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5224: my $area = '/'.$tdomain.'/'.$trest;
5225: if ($sec ne '') {
5226: $area .= '/'.$sec;
5227: }
5228: if (($area ne '') && ($trole ne '')) {
5229: my $spec=$trole.'.'.$area;
5230: if ($trole =~ /^cr\//) {
5231: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5232: } elsif ($trole ne 'gr') {
5233: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5234: }
5235: }
5236: }
5237: foreach my $role (keys(%allroles)) {
5238: last if ($is_adv);
5239: foreach my $item (split(/:/,$allroles{$role})) {
5240: if ($item ne '') {
5241: my ($privilege,$restrictions)=split(/&/,$item);
5242: if ($privilege eq 'adv') {
5243: $is_adv = 1;
5244: last;
5245: }
5246: }
5247: }
5248: }
5249: return $is_adv;
5250: }
1.798 raeburn 5251:
1.1035 raeburn 5252: sub check_can_request {
1.1036 raeburn 5253: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5254: my $canreq = 0;
5255: my ($types,$typename) = &Apache::loncommon::course_types();
5256: my @options = ('approval','validate','autolimit');
5257: my $optregex = join('|',@options);
5258: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5259: foreach my $type (@{$types}) {
5260: if (&usertools_access($env{'user.name'},
5261: $env{'user.domain'},
5262: $type,undef,'requestcourses')) {
5263: $canreq ++;
1.1036 raeburn 5264: if (ref($request_domains) eq 'HASH') {
5265: push(@{$request_domains->{$type}},$env{'user.domain'});
5266: }
1.1035 raeburn 5267: if ($dom eq $env{'user.domain'}) {
5268: $can_request->{$type} = 1;
5269: }
5270: }
5271: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5272: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5273: if (@curr > 0) {
1.1036 raeburn 5274: foreach my $item (@curr) {
5275: if (ref($request_domains) eq 'HASH') {
5276: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5277: if ($otherdom ne '') {
5278: if (ref($request_domains->{$type}) eq 'ARRAY') {
5279: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5280: push(@{$request_domains->{$type}},$otherdom);
5281: }
5282: } else {
5283: push(@{$request_domains->{$type}},$otherdom);
5284: }
5285: }
5286: }
5287: }
5288: unless($dom eq $env{'user.domain'}) {
5289: $canreq ++;
1.1035 raeburn 5290: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5291: $can_request->{$type} = 1;
5292: }
5293: }
5294: }
5295: }
5296: }
5297: }
5298: return $canreq;
5299: }
5300:
1.341 www 5301: # ---------------------------------------------- Custom access rule evaluation
5302:
5303: sub customaccess {
5304: my ($priv,$uri)=@_;
1.807 albertel 5305: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5306: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5307: $udom = &LONCAPA::clean_domain($udom);
5308: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5309: my $access=0;
1.800 albertel 5310: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5311: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5312: if ($type eq 'user') {
5313: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5314: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5315: if ($tdom) {
5316: if ($tdom ne $env{'user.domain'}) { next; }
5317: }
1.896 albertel 5318: if ($tuname) {
5319: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5320: }
5321: $access=($effect eq 'allow');
5322: last;
5323: }
5324: } else {
5325: if ($role) {
5326: if ($role ne $urole) { next; }
5327: }
5328: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5329: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5330: if ($tdom) {
5331: if ($tdom ne $udom) { next; }
5332: }
5333: if ($tcrs) {
5334: if ($tcrs ne $ucrs) { next; }
5335: }
5336: if ($tsec) {
5337: if ($tsec ne $usec) { next; }
5338: }
5339: $access=($effect eq 'allow');
5340: last;
5341: }
5342: if ($realm eq '' && $role eq '') {
5343: $access=($effect eq 'allow');
5344: }
1.402 bowersj2 5345: }
1.341 www 5346: }
5347: return $access;
5348: }
5349:
1.103 harris41 5350: # ------------------------------------------------- Check for a user privilege
1.12 www 5351:
5352: sub allowed {
1.810 raeburn 5353: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5354: my $ver_orguri=$uri;
1.439 www 5355: $uri=&deversion($uri);
1.152 www 5356: my $orguri=$uri;
1.52 www 5357: $uri=&declutter($uri);
1.809 raeburn 5358:
1.810 raeburn 5359: if ($priv eq 'evb') {
5360: # Evade communication block restrictions for specified role in a course
5361: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5362: return $1;
5363: } else {
5364: return;
5365: }
5366: }
5367:
1.620 albertel 5368: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5369: # Free bre access to adm and meta resources
1.775 albertel 5370: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5371: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5372: && ($priv eq 'bre')) {
1.14 www 5373: return 'F';
1.159 www 5374: }
5375:
1.545 banghart 5376: # Free bre access to user's own portfolio contents
1.714 raeburn 5377: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5378: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5379: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5380: my %setters;
5381: my ($startblock,$endblock) =
5382: &Apache::loncommon::blockcheck(\%setters,'port');
5383: if ($startblock && $endblock) {
5384: return 'B';
5385: } else {
5386: return 'F';
5387: }
1.545 banghart 5388: }
5389:
1.762 raeburn 5390: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5391: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5392: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5393: if (exists($env{'request.course.id'})) {
5394: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5395: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5396: if (($domain eq $cdom) && ($name eq $cnum)) {
5397: my $courseprivid=$env{'request.course.id'};
5398: $courseprivid=~s/\_/\//;
5399: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5400: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5401: return $1;
1.762 raeburn 5402: } else {
5403: if ($env{'request.course.sec'}) {
5404: $courseprivid.='/'.$env{'request.course.sec'};
5405: }
5406: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5407: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5408: return $2;
5409: }
1.714 raeburn 5410: }
5411: }
5412: }
5413: }
5414:
1.159 www 5415: # Free bre to public access
5416:
5417: if ($priv eq 'bre') {
1.238 www 5418: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5419: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5420: return 'F';
5421: }
1.238 www 5422: if ($copyright eq 'priv') {
5423: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5424: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5425: return '';
5426: }
5427: }
5428: if ($copyright eq 'domain') {
5429: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5430: unless (($env{'user.domain'} eq $1) ||
5431: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5432: return '';
5433: }
1.262 matthew 5434: }
1.620 albertel 5435: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5436: # Library role, so allow browsing of resources in this domain.
5437: return 'F';
1.238 www 5438: }
1.341 www 5439: if ($copyright eq 'custom') {
5440: unless (&customaccess($priv,$uri)) { return ''; }
5441: }
1.14 www 5442: }
1.264 matthew 5443: # Domain coordinator is trying to create a course
1.620 albertel 5444: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5445: # uri is the requested domain in this case.
5446: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5447: # a role of dc for the domain in question.
1.620 albertel 5448: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5449: }
1.29 www 5450:
1.52 www 5451: my $thisallowed='';
5452: my $statecond=0;
5453: my $courseprivid='';
5454:
1.1039 raeburn 5455: my $ownaccess;
1.1043 raeburn 5456: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5457: if (($priv eq 'bro') && ($env{'user.author'})) {
5458: if ($uri eq '') {
5459: $ownaccess = 1;
5460: } else {
5461: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5462: my $udom = $env{'user.domain'};
5463: my $uname = $env{'user.name'};
5464: if ($uri =~ m{^\Q$udom\E/?$}) {
5465: $ownaccess = 1;
1.1040 raeburn 5466: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5467: unless ($uri =~ m{\.\./}) {
5468: $ownaccess = 1;
5469: }
5470: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5471: my $now = time;
5472: if ($uri =~ m{^([^/]+)/?$}) {
5473: my $adom = $1;
5474: foreach my $key (keys(%env)) {
1.1042 raeburn 5475: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5476: my ($start,$end) = split('.',$env{$key});
5477: if (($now >= $start) && (!$end || $end < $now)) {
5478: $ownaccess = 1;
5479: last;
5480: }
5481: }
5482: }
5483: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5484: my $adom = $1;
5485: my $aname = $2;
1.1042 raeburn 5486: foreach my $role ('ca','aa') {
5487: if ($env{"user.role.$role./$adom/$aname"}) {
5488: my ($start,$end) =
5489: split('.',$env{"user.role.$role./$adom/$aname"});
5490: if (($now >= $start) && (!$end || $end < $now)) {
5491: $ownaccess = 1;
5492: last;
5493: }
1.1039 raeburn 5494: }
5495: }
5496: }
5497: }
5498: }
5499: }
5500: }
5501:
1.52 www 5502: # Course
5503:
1.620 albertel 5504: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5505: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5506: $thisallowed.=$1;
5507: }
1.52 www 5508: }
1.29 www 5509:
1.52 www 5510: # Domain
5511:
1.620 albertel 5512: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
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.52 www 5518:
5519: # Course: uri itself is a course
1.66 www 5520: my $courseuri=$uri;
5521: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5522: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5523:
1.620 albertel 5524: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5525: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5526: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5527: $thisallowed.=$1;
5528: }
1.12 www 5529: }
1.29 www 5530:
1.665 albertel 5531: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5532: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5533: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5534: $thisallowed='';
1.671 raeburn 5535: my ($match)=&is_on_map($uri);
5536: if ($match) {
5537: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5538: =~/\Q$priv\E\&([^\:]*)/) {
5539: $thisallowed.=$1;
5540: }
5541: } else {
1.705 albertel 5542: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5543: if ($refuri) {
5544: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5545: $thisallowed='F';
1.671 raeburn 5546: } else {
5547: $refuri=&declutter($refuri);
5548: my ($match) = &is_on_map($refuri);
5549: if ($match) {
5550: $thisallowed='F';
5551: }
1.669 raeburn 5552: }
1.671 raeburn 5553: }
5554: }
1.314 www 5555: }
1.492 albertel 5556:
1.766 albertel 5557: if ($priv eq 'bre'
5558: && $thisallowed ne 'F'
5559: && $thisallowed ne '2'
5560: && &is_portfolio_url($uri)) {
5561: $thisallowed = &portfolio_access($uri);
5562: }
5563:
1.52 www 5564: # Full access at system, domain or course-wide level? Exit.
1.29 www 5565: if ($thisallowed=~/F/) {
5566: return 'F';
5567: }
5568:
1.52 www 5569: # If this is generating or modifying users, exit with special codes
1.29 www 5570:
1.643 www 5571: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5572: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5573: my ($audom,$auname)=split('/',$uri);
1.643 www 5574: # no author name given, so this just checks on the general right to make a co-author in this domain
5575: unless ($auname) { return $thisallowed; }
5576: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5577: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5578: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5579: ($audom ne $env{'request.role.domain'}))) { return ''; }
5580: }
1.52 www 5581: return $thisallowed;
5582: }
5583: #
1.103 harris41 5584: # Gathered so far: system, domain and course wide privileges
1.52 www 5585: #
5586: # Course: See if uri or referer is an individual resource that is part of
5587: # the course
5588:
1.620 albertel 5589: if ($env{'request.course.id'}) {
1.232 www 5590:
1.620 albertel 5591: $courseprivid=$env{'request.course.id'};
5592: if ($env{'request.course.sec'}) {
5593: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5594: }
5595: $courseprivid=~s/\_/\//;
5596: my $checkreferer=1;
1.232 www 5597: my ($match,$cond)=&is_on_map($uri);
5598: if ($match) {
5599: $statecond=$cond;
1.620 albertel 5600: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5601: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5602: $thisallowed.=$1;
5603: $checkreferer=0;
5604: }
1.29 www 5605: }
1.83 www 5606:
1.148 www 5607: if ($checkreferer) {
1.620 albertel 5608: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5609: unless ($refuri) {
1.800 albertel 5610: foreach my $key (keys(%env)) {
5611: if ($key=~/^httpref\..*\*/) {
5612: my $pattern=$key;
1.156 www 5613: $pattern=~s/^httpref\.\/res\///;
1.148 www 5614: $pattern=~s/\*/\[\^\/\]\+/g;
5615: $pattern=~s/\//\\\//g;
1.152 www 5616: if ($orguri=~/$pattern/) {
1.800 albertel 5617: $refuri=$env{$key};
1.148 www 5618: }
5619: }
1.191 harris41 5620: }
1.148 www 5621: }
1.232 www 5622:
1.148 www 5623: if ($refuri) {
1.152 www 5624: $refuri=&declutter($refuri);
1.232 www 5625: my ($match,$cond)=&is_on_map($refuri);
5626: if ($match) {
5627: my $refstatecond=$cond;
1.620 albertel 5628: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5629: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5630: $thisallowed.=$1;
1.53 www 5631: $uri=$refuri;
5632: $statecond=$refstatecond;
1.52 www 5633: }
5634: }
1.148 www 5635: }
1.29 www 5636: }
1.52 www 5637: }
1.29 www 5638:
1.52 www 5639: #
1.103 harris41 5640: # Gathered now: all privileges that could apply, and condition number
1.52 www 5641: #
5642: #
5643: # Full or no access?
5644: #
1.29 www 5645:
1.52 www 5646: if ($thisallowed=~/F/) {
5647: return 'F';
5648: }
1.29 www 5649:
1.52 www 5650: unless ($thisallowed) {
5651: return '';
5652: }
1.29 www 5653:
1.52 www 5654: # Restrictions exist, deal with them
5655: #
5656: # C:according to course preferences
5657: # R:according to resource settings
5658: # L:unless locked
5659: # X:according to user session state
5660: #
5661:
5662: # Possibly locked functionality, check all courses
1.54 www 5663: # Locks might take effect only after 10 minutes cache expiration for other
5664: # courses, and 2 minutes for current course
1.52 www 5665:
5666: my $envkey;
5667: if ($thisallowed=~/L/) {
1.1000 raeburn 5668: foreach $envkey (keys(%env)) {
1.54 www 5669: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5670: my $courseid=$2;
5671: my $roleid=$1.'.'.$2;
1.92 www 5672: $courseid=~s/^\///;
1.54 www 5673: my $expiretime=600;
1.620 albertel 5674: if ($env{'request.role'} eq $roleid) {
1.54 www 5675: $expiretime=120;
5676: }
5677: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5678: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5679: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5680: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5681: }
1.620 albertel 5682: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5683: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5684: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5685: &log($env{'user.domain'},$env{'user.name'},
5686: $env{'user.home'},
1.57 www 5687: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5688: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5689: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5690: return '';
5691: }
5692: }
1.620 albertel 5693: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5694: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5695: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5696: &log($env{'user.domain'},$env{'user.name'},
5697: $env{'user.home'},
1.57 www 5698: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5699: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5700: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5701: return '';
5702: }
5703: }
5704: }
1.29 www 5705: }
1.52 www 5706: }
5707:
5708: #
5709: # Rest of the restrictions depend on selected course
5710: #
5711:
1.620 albertel 5712: unless ($env{'request.course.id'}) {
1.766 albertel 5713: if ($thisallowed eq 'A') {
5714: return 'A';
1.814 raeburn 5715: } elsif ($thisallowed eq 'B') {
5716: return 'B';
1.766 albertel 5717: } else {
5718: return '1';
5719: }
1.52 www 5720: }
1.29 www 5721:
1.52 www 5722: #
5723: # Now user is definitely in a course
5724: #
1.53 www 5725:
5726:
5727: # Course preferences
5728:
5729: if ($thisallowed=~/C/) {
1.620 albertel 5730: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5731: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5732: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5733: =~/\Q$rolecode\E/) {
1.1103 raeburn 5734: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5735: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5736: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5737: $env{'request.course.id'});
5738: }
1.237 www 5739: return '';
5740: }
5741:
1.620 albertel 5742: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5743: =~/\Q$unamedom\E/) {
1.1103 raeburn 5744: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5745: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5746: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5747: $env{'request.course.id'});
5748: }
1.54 www 5749: return '';
5750: }
1.53 www 5751: }
5752:
5753: # Resource preferences
5754:
5755: if ($thisallowed=~/R/) {
1.620 albertel 5756: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5757: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 5758: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5759: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5760: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5761: }
5762: return '';
1.54 www 5763: }
1.53 www 5764: }
1.30 www 5765:
1.246 www 5766: # Restricted by state or randomout?
1.30 www 5767:
1.52 www 5768: if ($thisallowed=~/X/) {
1.620 albertel 5769: if ($env{'acc.randomout'}) {
1.579 albertel 5770: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5771: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5772: return '';
5773: }
1.247 www 5774: }
5775: if (&condval($statecond)) {
1.52 www 5776: return '2';
5777: } else {
5778: return '';
5779: }
5780: }
1.30 www 5781:
1.766 albertel 5782: if ($thisallowed eq 'A') {
5783: return 'A';
1.814 raeburn 5784: } elsif ($thisallowed eq 'B') {
5785: return 'B';
1.766 albertel 5786: }
1.52 www 5787: return 'F';
1.232 www 5788: }
5789:
1.710 albertel 5790: sub split_uri_for_cond {
5791: my $uri=&deversion(&declutter(shift));
5792: my @uriparts=split(/\//,$uri);
5793: my $filename=pop(@uriparts);
5794: my $pathname=join('/',@uriparts);
5795: return ($pathname,$filename);
5796: }
1.232 www 5797: # --------------------------------------------------- Is a resource on the map?
5798:
5799: sub is_on_map {
1.710 albertel 5800: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5801: #Trying to find the conditional for the file
1.620 albertel 5802: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5803: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5804: if ($match) {
1.289 bowersj2 5805: return (1,$1);
5806: } else {
1.434 www 5807: return (0,0);
1.289 bowersj2 5808: }
1.12 www 5809: }
5810:
1.427 www 5811: # --------------------------------------------------------- Get symb from alias
5812:
5813: sub get_symb_from_alias {
5814: my $symb=shift;
5815: my ($map,$resid,$url)=&decode_symb($symb);
5816: # Already is a symb
5817: if ($url) { return $symb; }
5818: # Must be an alias
5819: my $aliassymb='';
5820: my %bighash;
1.620 albertel 5821: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5822: &GDBM_READER(),0640)) {
5823: my $rid=$bighash{'mapalias_'.$symb};
5824: if ($rid) {
5825: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5826: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5827: $resid,$bighash{'src_'.$rid});
1.427 www 5828: }
5829: untie %bighash;
5830: }
5831: return $aliassymb;
5832: }
5833:
1.12 www 5834: # ----------------------------------------------------------------- Define Role
5835:
5836: sub definerole {
5837: if (allowed('mcr','/')) {
5838: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5839: foreach my $role (split(':',$sysrole)) {
5840: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5841: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5842: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5843: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5844: return "refused:s:$crole&$cqual";
5845: }
5846: }
1.191 harris41 5847: }
1.800 albertel 5848: foreach my $role (split(':',$domrole)) {
5849: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5850: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5851: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5852: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5853: return "refused:d:$crole&$cqual";
5854: }
5855: }
1.191 harris41 5856: }
1.800 albertel 5857: foreach my $role (split(':',$courole)) {
5858: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5859: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5860: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5861: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5862: return "refused:c:$crole&$cqual";
5863: }
5864: }
1.191 harris41 5865: }
1.620 albertel 5866: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5867: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5868: "rolesdef_$rolename=".
5869: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5870: return reply($command,$env{'user.home'});
1.12 www 5871: } else {
5872: return 'refused';
5873: }
1.105 harris41 5874: }
5875:
5876: # ---------------- Make a metadata query against the network of library servers
5877:
5878: sub metadata_query {
1.244 matthew 5879: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5880: my %rhash;
1.845 albertel 5881: my %libserv = &all_library();
1.244 matthew 5882: my @server_list = (defined($server_array) ? @$server_array
5883: : keys(%libserv) );
5884: for my $server (@server_list) {
1.118 harris41 5885: unless ($custom or $customshow) {
5886: my $reply=&reply("querysend:".&escape($query),$server);
5887: $rhash{$server}=$reply;
5888: }
5889: else {
5890: my $reply=&reply("querysend:".&escape($query).':'.
5891: &escape($custom).':'.&escape($customshow),
5892: $server);
5893: $rhash{$server}=$reply;
5894: }
1.112 harris41 5895: }
1.118 harris41 5896: return \%rhash;
1.240 www 5897: }
5898:
5899: # ----------------------------------------- Send log queries and wait for reply
5900:
5901: sub log_query {
5902: my ($uname,$udom,$query,%filters)=@_;
5903: my $uhome=&homeserver($uname,$udom);
5904: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5905: my $uhost=&hostname($uhome);
1.800 albertel 5906: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5907: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5908: $uhome);
1.479 albertel 5909: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5910: return get_query_reply($queryid);
5911: }
5912:
1.818 raeburn 5913: # -------------------------- Update MySQL table for portfolio file
5914:
5915: sub update_portfolio_table {
1.821 raeburn 5916: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5917: if ($group ne '') {
5918: $file_name =~s /^\Q$group\E//;
5919: }
1.818 raeburn 5920: my $homeserver = &homeserver($uname,$udom);
5921: my $queryid=
1.821 raeburn 5922: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5923: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5924: my $reply = &get_query_reply($queryid);
5925: return $reply;
5926: }
5927:
1.899 raeburn 5928: # -------------------------- Update MySQL allusers table
5929:
5930: sub update_allusers_table {
5931: my ($uname,$udom,$names) = @_;
5932: my $homeserver = &homeserver($uname,$udom);
5933: my $queryid=
5934: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5935: 'lastname='.&escape($names->{'lastname'}).'%%'.
5936: 'firstname='.&escape($names->{'firstname'}).'%%'.
5937: 'middlename='.&escape($names->{'middlename'}).'%%'.
5938: 'generation='.&escape($names->{'generation'}).'%%'.
5939: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5940: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 5941: return;
1.899 raeburn 5942: }
5943:
1.508 raeburn 5944: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5945:
5946: sub fetch_enrollment_query {
1.511 raeburn 5947: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5948: my $homeserver;
1.547 raeburn 5949: my $maxtries = 1;
1.508 raeburn 5950: if ($context eq 'automated') {
5951: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5952: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5953: } else {
5954: $homeserver = &homeserver($cnum,$dom);
5955: }
1.838 albertel 5956: my $host=&hostname($homeserver);
1.506 raeburn 5957: my $cmd = '';
1.1000 raeburn 5958: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5959: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5960: }
5961: $cmd =~ s/%%$//;
5962: $cmd = &escape($cmd);
5963: my $query = 'fetchenrollment';
1.620 albertel 5964: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5965: unless ($queryid=~/^\Q$host\E\_/) {
5966: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5967: return 'error: '.$queryid;
5968: }
1.506 raeburn 5969: my $reply = &get_query_reply($queryid);
1.547 raeburn 5970: my $tries = 1;
5971: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5972: $reply = &get_query_reply($queryid);
5973: $tries ++;
5974: }
1.526 raeburn 5975: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5976: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5977: } else {
1.901 albertel 5978: my @responses = split(/:/,$reply);
1.515 raeburn 5979: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5980: foreach my $line (@responses) {
5981: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5982: $$replyref{$key} = $value;
5983: }
5984: } else {
1.506 raeburn 5985: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5986: foreach my $line (@responses) {
5987: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5988: $$replyref{$key} = $value;
5989: if ($value > 0) {
1.800 albertel 5990: foreach my $item (@{$$affiliatesref{$key}}) {
5991: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5992: my $destname = $pathname.'/'.$filename;
5993: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5994: if ($xml_classlist =~ /^error/) {
5995: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5996: } else {
1.506 raeburn 5997: if ( open(FILE,">$destname") ) {
5998: print FILE &unescape($xml_classlist);
5999: close(FILE);
1.526 raeburn 6000: } else {
6001: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6002: }
6003: }
6004: }
6005: }
6006: }
6007: }
6008: return 'ok';
6009: }
6010: return 'error';
6011: }
6012:
1.242 www 6013: sub get_query_reply {
6014: my $queryid=shift;
1.240 www 6015: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
6016: my $reply='';
6017: for (1..100) {
6018: sleep 2;
6019: if (-e $replyfile.'.end') {
1.448 albertel 6020: if (open(my $fh,$replyfile)) {
1.904 albertel 6021: $reply = join('',<$fh>);
6022: close($fh);
1.240 www 6023: } else { return 'error: reply_file_error'; }
1.242 www 6024: return &unescape($reply);
6025: }
1.240 www 6026: }
1.242 www 6027: return 'timeout:'.$queryid;
1.240 www 6028: }
6029:
6030: sub courselog_query {
1.241 www 6031: #
6032: # possible filters:
6033: # url: url or symb
6034: # username
6035: # domain
6036: # action: view, submit, grade
6037: # start: timestamp
6038: # end: timestamp
6039: #
1.240 www 6040: my (%filters)=@_;
1.620 albertel 6041: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6042: if ($filters{'url'}) {
6043: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6044: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6045: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6046: }
1.620 albertel 6047: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6048: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6049: return &log_query($cname,$cdom,'courselog',%filters);
6050: }
6051:
6052: sub userlog_query {
1.858 raeburn 6053: #
6054: # possible filters:
6055: # action: log check role
6056: # start: timestamp
6057: # end: timestamp
6058: #
1.240 www 6059: my ($uname,$udom,%filters)=@_;
6060: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6061: }
6062:
1.506 raeburn 6063: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6064:
6065: sub auto_run {
1.508 raeburn 6066: my ($cnum,$cdom) = @_;
1.876 raeburn 6067: my $response = 0;
6068: my $settings;
6069: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6070: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6071: $settings = $domconfig{'autoenroll'};
6072: if ($settings->{'run'} eq '1') {
6073: $response = 1;
6074: }
6075: } else {
1.934 raeburn 6076: my $homeserver;
6077: if (&is_course($cdom,$cnum)) {
6078: $homeserver = &homeserver($cnum,$cdom);
6079: } else {
6080: $homeserver = &domain($cdom,'primary');
6081: }
6082: if ($homeserver ne 'no_host') {
6083: $response = &reply('autorun:'.$cdom,$homeserver);
6084: }
1.876 raeburn 6085: }
1.506 raeburn 6086: return $response;
6087: }
1.776 albertel 6088:
1.506 raeburn 6089: sub auto_get_sections {
1.508 raeburn 6090: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6091: my $homeserver;
6092: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6093: $homeserver = &homeserver($cnum,$cdom);
6094: }
6095: if (!defined($homeserver)) {
6096: if ($cdom =~ /^$match_domain$/) {
6097: $homeserver = &domain($cdom,'primary');
6098: }
6099: }
6100: my @secs;
6101: if (defined($homeserver)) {
6102: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6103: unless ($response eq 'refused') {
6104: @secs = split(/:/,$response);
6105: }
1.506 raeburn 6106: }
6107: return @secs;
6108: }
1.776 albertel 6109:
1.506 raeburn 6110: sub auto_new_course {
1.1099 raeburn 6111: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6112: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6113: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6114: return $response;
6115: }
1.776 albertel 6116:
1.506 raeburn 6117: sub auto_validate_courseID {
1.508 raeburn 6118: my ($cnum,$cdom,$inst_course_id) = @_;
6119: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6120: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6121: return $response;
6122: }
1.776 albertel 6123:
1.1007 raeburn 6124: sub auto_validate_instcode {
1.1020 raeburn 6125: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6126: my ($homeserver,$response);
6127: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6128: $homeserver = &homeserver($cnum,$cdom);
6129: }
6130: if (!defined($homeserver)) {
6131: if ($cdom =~ /^$match_domain$/) {
6132: $homeserver = &domain($cdom,'primary');
6133: }
6134: }
1.1065 raeburn 6135: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6136: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6137: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6138: return ($outcome,$description);
1.1007 raeburn 6139: }
6140:
1.506 raeburn 6141: sub auto_create_password {
1.873 raeburn 6142: my ($cnum,$cdom,$authparam,$udom) = @_;
6143: my ($homeserver,$response);
1.506 raeburn 6144: my $create_passwd = 0;
6145: my $authchk = '';
1.873 raeburn 6146: if ($udom =~ /^$match_domain$/) {
6147: $homeserver = &domain($udom,'primary');
6148: }
6149: if ($homeserver eq '') {
6150: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6151: $homeserver = &homeserver($cnum,$cdom);
6152: }
6153: }
6154: if ($homeserver eq '') {
6155: $authchk = 'nodomain';
1.506 raeburn 6156: } else {
1.873 raeburn 6157: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6158: if ($response eq 'refused') {
6159: $authchk = 'refused';
6160: } else {
1.901 albertel 6161: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6162: }
1.506 raeburn 6163: }
6164: return ($authparam,$create_passwd,$authchk);
6165: }
6166:
1.706 raeburn 6167: sub auto_photo_permission {
6168: my ($cnum,$cdom,$students) = @_;
6169: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6170: my ($outcome,$perm_reqd,$conditions) =
6171: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6172: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6173: return (undef,undef);
6174: }
1.706 raeburn 6175: return ($outcome,$perm_reqd,$conditions);
6176: }
6177:
6178: sub auto_checkphotos {
6179: my ($uname,$udom,$pid) = @_;
6180: my $homeserver = &homeserver($uname,$udom);
6181: my ($result,$resulttype);
6182: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6183: &escape($uname).':'.&escape($pid),
6184: $homeserver));
1.709 albertel 6185: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6186: return (undef,undef);
6187: }
1.706 raeburn 6188: if ($outcome) {
6189: ($result,$resulttype) = split(/:/,$outcome);
6190: }
6191: return ($result,$resulttype);
6192: }
6193:
6194: sub auto_photochoice {
6195: my ($cnum,$cdom) = @_;
6196: my $homeserver = &homeserver($cnum,$cdom);
6197: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6198: &escape($cdom),
6199: $homeserver)));
1.709 albertel 6200: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6201: return (undef,undef);
6202: }
1.706 raeburn 6203: return ($update,$comment);
6204: }
6205:
6206: sub auto_photoupdate {
6207: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6208: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6209: my $host=&hostname($homeserver);
1.706 raeburn 6210: my $cmd = '';
6211: my $maxtries = 1;
1.800 albertel 6212: foreach my $affiliate (keys(%{$affiliatesref})) {
6213: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6214: }
6215: $cmd =~ s/%%$//;
6216: $cmd = &escape($cmd);
6217: my $query = 'institutionalphotos';
6218: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6219: unless ($queryid=~/^\Q$host\E\_/) {
6220: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6221: return 'error: '.$queryid;
6222: }
6223: my $reply = &get_query_reply($queryid);
6224: my $tries = 1;
6225: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6226: $reply = &get_query_reply($queryid);
6227: $tries ++;
6228: }
6229: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6230: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6231: } else {
6232: my @responses = split(/:/,$reply);
6233: my $outcome = shift(@responses);
6234: foreach my $item (@responses) {
6235: my ($key,$value) = split(/=/,$item);
6236: $$photo{$key} = $value;
6237: }
6238: return $outcome;
6239: }
6240: return 'error';
6241: }
6242:
1.521 raeburn 6243: sub auto_instcode_format {
1.793 albertel 6244: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6245: $cat_order) = @_;
1.521 raeburn 6246: my $courses = '';
1.772 raeburn 6247: my @homeservers;
1.521 raeburn 6248: if ($caller eq 'global') {
1.841 albertel 6249: my %servers = &get_servers($codedom,'library');
6250: foreach my $tryserver (keys(%servers)) {
6251: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6252: push(@homeservers,$tryserver);
6253: }
1.584 raeburn 6254: }
1.1022 raeburn 6255: } elsif ($caller eq 'requests') {
6256: if ($codedom =~ /^$match_domain$/) {
6257: my $chome = &domain($codedom,'primary');
6258: unless ($chome eq 'no_host') {
6259: push(@homeservers,$chome);
6260: }
6261: }
1.521 raeburn 6262: } else {
1.772 raeburn 6263: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6264: }
1.793 albertel 6265: foreach my $code (keys(%{$instcodes})) {
6266: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6267: }
6268: chop($courses);
1.772 raeburn 6269: my $ok_response = 0;
6270: my $response;
6271: while (@homeservers > 0 && $ok_response == 0) {
6272: my $server = shift(@homeservers);
6273: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6274: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6275: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6276: split(/:/,$response);
1.772 raeburn 6277: %{$codes} = (%{$codes},&str2hash($codes_str));
6278: push(@{$codetitles},&str2array($codetitles_str));
6279: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6280: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6281: $ok_response = 1;
6282: }
6283: }
6284: if ($ok_response) {
1.521 raeburn 6285: return 'ok';
1.772 raeburn 6286: } else {
6287: return $response;
1.521 raeburn 6288: }
6289: }
6290:
1.792 raeburn 6291: sub auto_instcode_defaults {
6292: my ($domain,$returnhash,$code_order) = @_;
6293: my @homeservers;
1.841 albertel 6294:
6295: my %servers = &get_servers($domain,'library');
6296: foreach my $tryserver (keys(%servers)) {
6297: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6298: push(@homeservers,$tryserver);
6299: }
1.792 raeburn 6300: }
1.841 albertel 6301:
1.792 raeburn 6302: my $response;
1.841 albertel 6303: foreach my $server (@homeservers) {
1.792 raeburn 6304: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6305: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6306:
6307: foreach my $pair (split(/\&/,$response)) {
6308: my ($name,$value)=split(/\=/,$pair);
6309: if ($name eq 'code_order') {
6310: @{$code_order} = split(/\&/,&unescape($value));
6311: } else {
6312: $returnhash->{&unescape($name)}=&unescape($value);
6313: }
6314: }
6315: return 'ok';
1.792 raeburn 6316: }
1.841 albertel 6317:
6318: return $response;
1.1003 raeburn 6319: }
6320:
6321: sub auto_possible_instcodes {
1.1007 raeburn 6322: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6323: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6324: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6325: return;
6326: }
1.1003 raeburn 6327: my (@homeservers,$uhome);
6328: if (defined(&domain($domain,'primary'))) {
6329: $uhome=&domain($domain,'primary');
6330: push(@homeservers,&domain($domain,'primary'));
6331: } else {
6332: my %servers = &get_servers($domain,'library');
6333: foreach my $tryserver (keys(%servers)) {
6334: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6335: push(@homeservers,$tryserver);
6336: }
6337: }
6338: }
6339: my $response;
6340: foreach my $server (@homeservers) {
6341: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6342: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6343: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6344: split(':',$response);
6345: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6346: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6347: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6348: my ($name,$value)=split('=',$item);
6349: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6350: }
6351: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6352: my ($name,$value)=split('=',$item);
6353: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6354: }
6355: return 'ok';
6356: }
6357: return $response;
6358: }
1.792 raeburn 6359:
1.1010 raeburn 6360: sub auto_courserequest_checks {
6361: my ($dom) = @_;
1.1020 raeburn 6362: my ($homeserver,%validations);
6363: if ($dom =~ /^$match_domain$/) {
6364: $homeserver = &domain($dom,'primary');
6365: }
6366: unless ($homeserver eq 'no_host') {
6367: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6368: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6369: my @items = split(/&/,$response);
6370: foreach my $item (@items) {
6371: my ($key,$value) = split('=',$item);
6372: $validations{&unescape($key)} = &thaw_unescape($value);
6373: }
6374: }
6375: }
1.1010 raeburn 6376: return %validations;
6377: }
6378:
1.1020 raeburn 6379: sub auto_courserequest_validation {
6380: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6381: my ($homeserver,$response);
6382: if ($dom =~ /^$match_domain$/) {
6383: $homeserver = &domain($dom,'primary');
6384: }
6385: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6386:
1.1020 raeburn 6387: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6388: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6389: ':'.&escape($instcode).':'.&escape($instseclist),
6390: $homeserver));
6391: }
6392: return $response;
6393: }
6394:
1.777 albertel 6395: sub auto_validate_class_sec {
1.918 raeburn 6396: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6397: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6398: my $ownerlist;
6399: if (ref($owners) eq 'ARRAY') {
6400: $ownerlist = join(',',@{$owners});
6401: } else {
6402: $ownerlist = $owners;
6403: }
1.773 raeburn 6404: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6405: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6406: return $response;
6407: }
6408:
1.679 raeburn 6409: # ------------------------------------------------------- Course Group routines
6410:
6411: sub get_coursegroups {
1.809 raeburn 6412: my ($cdom,$cnum,$group,$namespace) = @_;
6413: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6414: }
6415:
1.679 raeburn 6416: sub modify_coursegroup {
6417: my ($cdom,$cnum,$groupsettings) = @_;
6418: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6419: }
6420:
1.809 raeburn 6421: sub toggle_coursegroup_status {
6422: my ($cdom,$cnum,$group,$action) = @_;
6423: my ($from_namespace,$to_namespace);
6424: if ($action eq 'delete') {
6425: $from_namespace = 'coursegroups';
6426: $to_namespace = 'deleted_groups';
6427: } else {
6428: $from_namespace = 'deleted_groups';
6429: $to_namespace = 'coursegroups';
6430: }
6431: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6432: if (my $tmp = &error(%curr_group)) {
6433: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6434: return ('read error',$tmp);
6435: } else {
6436: my %savedsettings = %curr_group;
1.809 raeburn 6437: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6438: my $deloutcome;
6439: if ($result eq 'ok') {
1.809 raeburn 6440: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6441: } else {
6442: return ('write error',$result);
6443: }
6444: if ($deloutcome eq 'ok') {
6445: return 'ok';
6446: } else {
6447: return ('delete error',$deloutcome);
6448: }
6449: }
6450: }
6451:
1.679 raeburn 6452: sub modify_group_roles {
1.957 raeburn 6453: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6454: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6455: my $role = 'gr/'.&escape($userprivs);
6456: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6457: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6458: if ($result eq 'ok') {
6459: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6460: }
1.679 raeburn 6461: return $result;
6462: }
6463:
6464: sub modify_coursegroup_membership {
6465: my ($cdom,$cnum,$membership) = @_;
6466: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6467: return $result;
6468: }
6469:
1.682 raeburn 6470: sub get_active_groups {
6471: my ($udom,$uname,$cdom,$cnum) = @_;
6472: my $now = time;
6473: my %groups = ();
6474: foreach my $key (keys(%env)) {
1.811 albertel 6475: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6476: my ($start,$end) = split(/\./,$env{$key});
6477: if (($end!=0) && ($end<$now)) { next; }
6478: if (($start!=0) && ($start>$now)) { next; }
6479: if ($1 eq $cdom && $2 eq $cnum) {
6480: $groups{$3} = $env{$key} ;
6481: }
6482: }
6483: }
6484: return %groups;
6485: }
6486:
1.683 raeburn 6487: sub get_group_membership {
6488: my ($cdom,$cnum,$group) = @_;
6489: return(&dump('groupmembership',$cdom,$cnum,$group));
6490: }
6491:
6492: sub get_users_groups {
6493: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6494: my @usersgroups;
1.683 raeburn 6495: my $cachetime=1800;
6496:
6497: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6498: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6499: if (defined($cached)) {
1.734 albertel 6500: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6501: } else {
6502: $grouplist = '';
1.816 raeburn 6503: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6504: my $extra = &freeze_escape({'skipcheck' => 1});
6505: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6506: my $access_end = $env{'course.'.$courseid.
6507: '.default_enrollment_end_date'};
6508: my $now = time;
6509: foreach my $key (keys(%roleshash)) {
6510: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6511: my $group = $1;
6512: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6513: my $start = $2;
6514: my $end = $1;
6515: if ($start == -1) { next; } # deleted from group
6516: if (($start!=0) && ($start>$now)) { next; }
6517: if (($end!=0) && ($end<$now)) {
6518: if ($access_end && $access_end < $now) {
6519: if ($access_end - $end < 86400) {
6520: push(@usersgroups,$group);
1.733 raeburn 6521: }
6522: }
1.817 raeburn 6523: next;
1.733 raeburn 6524: }
1.817 raeburn 6525: push(@usersgroups,$group);
1.683 raeburn 6526: }
6527: }
6528: }
1.817 raeburn 6529: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6530: $grouplist = join(':',@usersgroups);
6531: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6532: }
1.733 raeburn 6533: return @usersgroups;
1.683 raeburn 6534: }
6535:
6536: sub devalidate_getgroups_cache {
6537: my ($udom,$uname,$cdom,$cnum)=@_;
6538: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6539:
1.683 raeburn 6540: my $hashid="$udom:$uname:$courseid";
6541: &devalidate_cache_new('getgroups',$hashid);
6542: }
6543:
1.12 www 6544: # ------------------------------------------------------------------ Plain Text
6545:
6546: sub plaintext {
1.988 raeburn 6547: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6548: if ($short =~ m{^cr/}) {
1.758 albertel 6549: return (split('/',$short))[-1];
6550: }
1.742 raeburn 6551: if (!defined($cid)) {
6552: $cid = $env{'request.course.id'};
6553: }
6554: my %rolenames = (
1.1008 raeburn 6555: Course => 'std',
6556: Community => 'alt1',
1.742 raeburn 6557: );
1.1037 raeburn 6558: if ($cid ne '') {
6559: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6560: unless ($forcedefault) {
6561: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6562: &Apache::lonlocal::mt_escape(\$roletext);
6563: return &Apache::lonlocal::mt($roletext);
6564: }
6565: }
6566: }
6567: if ((defined($type)) && (defined($rolenames{$type})) &&
6568: (defined($rolenames{$type})) &&
6569: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6570: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6571: } elsif ($cid ne '') {
6572: my $crstype = $env{'course.'.$cid.'.type'};
6573: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6574: (defined($prp{$short}{$rolenames{$crstype}}))) {
6575: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6576: }
1.742 raeburn 6577: }
1.1037 raeburn 6578: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6579: }
6580:
6581: # ----------------------------------------------------------------- Assign Role
6582:
6583: sub assignrole {
1.957 raeburn 6584: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6585: $context)=@_;
1.21 www 6586: my $mrole;
6587: if ($role =~ /^cr\//) {
1.393 www 6588: my $cwosec=$url;
1.811 albertel 6589: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6590: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6591: my $refused = 1;
6592: if ($context eq 'requestcourses') {
6593: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6594: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6595: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6596: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6597: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6598: if ($crsenv{'internal.courseowner'} eq
6599: $env{'user.name'}.':'.$env{'user.domain'}) {
6600: $refused = '';
6601: }
6602: }
6603: }
6604: }
6605: }
6606: if ($refused) {
6607: &logthis('Refused custom assignrole: '.
6608: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6609: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6610: return 'refused';
6611: }
1.104 www 6612: }
1.21 www 6613: $mrole='cr';
1.678 raeburn 6614: } elsif ($role =~ /^gr\//) {
6615: my $cwogrp=$url;
1.811 albertel 6616: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6617: unless (&allowed('mdg',$cwogrp)) {
6618: &logthis('Refused group assignrole: '.
6619: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6620: $env{'user.name'}.' at '.$env{'user.domain'});
6621: return 'refused';
6622: }
6623: $mrole='gr';
1.21 www 6624: } else {
1.82 www 6625: my $cwosec=$url;
1.811 albertel 6626: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6627: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6628: my $refused;
6629: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6630: if (!(&allowed('c'.$role,$url))) {
6631: $refused = 1;
6632: }
6633: } else {
6634: $refused = 1;
6635: }
1.947 raeburn 6636: if ($refused) {
1.1045 raeburn 6637: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6638: if (!$selfenroll && $context eq 'course') {
6639: my %crsenv;
6640: if ($role eq 'cc' || $role eq 'co') {
6641: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6642: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6643: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6644: if ($crsenv{'internal.courseowner'} eq
6645: $env{'user.name'}.':'.$env{'user.domain'}) {
6646: $refused = '';
6647: }
6648: }
6649: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6650: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6651: if ($crsenv{'internal.courseowner'} eq
6652: $env{'user.name'}.':'.$env{'user.domain'}) {
6653: $refused = '';
6654: }
6655: }
6656: }
6657: }
6658: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6659: $refused = '';
1.1017 raeburn 6660: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6661: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6662: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6663: my $wrongcc;
6664: if ($cnum =~ /^$match_community$/) {
6665: $wrongcc = 1 if ($role eq 'cc');
6666: } else {
6667: $wrongcc = 1 if ($role eq 'co');
6668: }
6669: unless ($wrongcc) {
6670: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6671: if ($crsenv{'internal.courseowner'} eq
6672: $env{'user.name'}.':'.$env{'user.domain'}) {
6673: $refused = '';
6674: }
1.1017 raeburn 6675: }
6676: }
6677: }
6678: if ($refused) {
1.947 raeburn 6679: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6680: ' '.$role.' '.$end.' '.$start.' by '.
6681: $env{'user.name'}.' at '.$env{'user.domain'});
6682: return 'refused';
6683: }
1.932 raeburn 6684: }
1.104 www 6685: }
1.21 www 6686: $mrole=$role;
6687: }
1.620 albertel 6688: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6689: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6690: if ($end) { $command.='_'.$end; }
1.21 www 6691: if ($start) {
6692: if ($end) {
1.81 www 6693: $command.='_'.$start;
1.21 www 6694: } else {
1.81 www 6695: $command.='_0_'.$start;
1.21 www 6696: }
6697: }
1.739 raeburn 6698: my $origstart = $start;
6699: my $origend = $end;
1.957 raeburn 6700: my $delflag;
1.357 www 6701: # actually delete
6702: if ($deleteflag) {
1.373 www 6703: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6704: # modify command to delete the role
1.620 albertel 6705: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6706: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6707: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6708: # set start and finish to negative values for userrolelog
6709: $start=-1;
6710: $end=-1;
1.957 raeburn 6711: $delflag = 1;
1.357 www 6712: }
6713: }
6714: # send command
1.349 www 6715: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6716: # log new user role if status is ok
1.349 www 6717: if ($answer eq 'ok') {
1.663 raeburn 6718: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6719: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6720: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6721: unless ($role =~ /^gr/) {
6722: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6723: $origstart,$selfenroll,$context);
1.739 raeburn 6724: }
1.1053 raeburn 6725: if ($role eq 'cc') {
6726: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6727: }
1.349 www 6728: }
6729: return $answer;
1.169 harris41 6730: }
6731:
1.1053 raeburn 6732: sub autoupdate_coowners {
6733: my ($url,$end,$start,$uname,$udom) = @_;
6734: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6735: if (($cdom ne '') && ($cnum ne '')) {
6736: my $now = time;
6737: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6738: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6739: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6740: my $instcode = $coursehash{'internal.coursecode'};
6741: if ($instcode ne '') {
1.1056 raeburn 6742: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6743: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6744: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6745: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6746: if ($result eq 'valid') {
6747: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6748: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6749: push(@newcoowners,$coowner);
6750: }
6751: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6752: push(@newcoowners,$uname.':'.$udom);
6753: }
6754: @newcoowners = sort(@newcoowners);
6755: } else {
6756: push(@newcoowners,$uname.':'.$udom);
6757: }
6758: } else {
6759: if ($coursehash{'internal.co-owners'}) {
6760: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6761: unless ($coowner eq $uname.':'.$udom) {
6762: push(@newcoowners,$coowner);
6763: }
6764: }
6765: unless (@newcoowners > 0) {
6766: $delcoowners = 1;
6767: $coowners = '';
6768: }
6769: }
6770: }
6771: if (@newcoowners || $delcoowners) {
6772: &store_coowners($cdom,$cnum,$coursehash{'home'},
6773: $delcoowners,@newcoowners);
6774: }
6775: }
6776: }
6777: }
6778: }
6779: }
6780: }
6781:
6782: sub store_coowners {
6783: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6784: my $cid = $cdom.'_'.$cnum;
6785: my ($coowners,$delresult,$putresult);
6786: if (@newcoowners) {
6787: $coowners = join(',',@newcoowners);
6788: my %coownershash = (
6789: 'internal.co-owners' => $coowners,
6790: );
6791: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6792: if ($putresult eq 'ok') {
6793: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6794: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6795: }
6796: }
6797: }
6798: if ($delcoowners) {
6799: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6800: if ($delresult eq 'ok') {
6801: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6802: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6803: }
6804: }
6805: }
6806: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6807: my %crsinfo =
6808: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6809: if (ref($crsinfo{$cid}) eq 'HASH') {
6810: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6811: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6812: }
6813: }
6814: }
6815:
1.169 harris41 6816: # -------------------------------------------------- Modify user authentication
1.197 www 6817: # Overrides without validation
6818:
1.169 harris41 6819: sub modifyuserauth {
6820: my ($udom,$uname,$umode,$upass)=@_;
6821: my $uhome=&homeserver($uname,$udom);
1.197 www 6822: unless (&allowed('mau',$udom)) { return 'refused'; }
6823: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6824: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6825: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6826: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6827: &escape($upass),$uhome);
1.620 albertel 6828: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6829: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6830: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6831: &log($udom,,$uname,$uhome,
1.620 albertel 6832: 'Authentication changed by '.$env{'user.domain'}.', '.
6833: $env{'user.name'}.', '.$umode.
1.197 www 6834: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6835: unless ($reply eq 'ok') {
1.197 www 6836: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6837: return 'error: '.$reply;
6838: }
1.170 harris41 6839: return 'ok';
1.80 www 6840: }
6841:
1.81 www 6842: # --------------------------------------------------------------- Modify a user
1.80 www 6843:
1.81 www 6844: sub modifyuser {
1.206 matthew 6845: my ($udom, $uname, $uid,
6846: $umode, $upass, $first,
6847: $middle, $last, $gene,
1.1058 raeburn 6848: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6849: $udom= &LONCAPA::clean_domain($udom);
6850: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6851: my $showcandelete = 'none';
6852: if (ref($candelete) eq 'ARRAY') {
6853: if (@{$candelete} > 0) {
6854: $showcandelete = join(', ',@{$candelete});
6855: }
6856: }
1.81 www 6857: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6858: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6859: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6860: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6861: ' desiredhome not specified').
1.620 albertel 6862: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6863: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6864: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 6865: my $newuser;
6866: if ($uhome eq 'no_host') {
6867: $newuser = 1;
6868: }
1.80 www 6869: # ----------------------------------------------------------------- Create User
1.406 albertel 6870: if (($uhome eq 'no_host') &&
6871: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6872: my $unhome='';
1.844 albertel 6873: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6874: $unhome = $desiredhome;
1.620 albertel 6875: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6876: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6877: } else { # load balancing routine for determining $unhome
1.81 www 6878: my $loadm=10000000;
1.841 albertel 6879: my %servers = &get_servers($udom,'library');
6880: foreach my $tryserver (keys(%servers)) {
6881: my $answer=reply('load',$tryserver);
6882: if (($answer=~/\d+/) && ($answer<$loadm)) {
6883: $loadm=$answer;
6884: $unhome=$tryserver;
6885: }
1.80 www 6886: }
6887: }
6888: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6889: return 'error: unable to find a home server for '.$uname.
6890: ' in domain '.$udom;
1.80 www 6891: }
6892: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6893: &escape($upass),$unhome);
6894: unless ($reply eq 'ok') {
6895: return 'error: '.$reply;
6896: }
1.230 stredwic 6897: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6898: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6899: return 'error: unable verify users home machine.';
1.80 www 6900: }
1.209 matthew 6901: } # End of creation of new user
1.80 www 6902: # ---------------------------------------------------------------------- Add ID
6903: if ($uid) {
6904: $uid=~tr/A-Z/a-z/;
6905: my %uidhash=&idrget($udom,$uname);
1.196 www 6906: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6907: && (!$forceid)) {
1.80 www 6908: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6909: return 'error: user id "'.$uid.'" does not match '.
6910: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6911: }
6912: } else {
6913: &idput($udom,($uname => $uid));
6914: }
6915: }
6916: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6917: my @tmp=&get('environment',
1.899 raeburn 6918: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6919: 'permanentemail','inststatus'],
1.134 albertel 6920: $udom,$uname);
1.1075 raeburn 6921: my (%names,%oldnames);
1.313 matthew 6922: if ($tmp[0] =~ m/^error:.*/) {
6923: %names=();
6924: } else {
6925: %names = @tmp;
1.1075 raeburn 6926: %oldnames = %names;
1.313 matthew 6927: }
1.388 www 6928: #
1.1058 raeburn 6929: # If name, email and/or uid are blank (e.g., because an uploaded file
6930: # of users did not contain them), do not overwrite existing values
6931: # unless field is in $candelete array ref.
6932: #
6933:
6934: my @fields = ('firstname','middlename','lastname','generation',
6935: 'permanentemail','id');
6936: my %newvalues;
6937: if (ref($candelete) eq 'ARRAY') {
6938: foreach my $field (@fields) {
6939: if (grep(/^\Q$field\E$/,@{$candelete})) {
6940: if ($field eq 'firstname') {
6941: $names{$field} = $first;
6942: } elsif ($field eq 'middlename') {
6943: $names{$field} = $middle;
6944: } elsif ($field eq 'lastname') {
6945: $names{$field} = $last;
6946: } elsif ($field eq 'generation') {
6947: $names{$field} = $gene;
6948: } elsif ($field eq 'permanentemail') {
6949: $names{$field} = $email;
6950: } elsif ($field eq 'id') {
6951: $names{$field} = $uid;
6952: }
6953: }
6954: }
6955: }
1.388 www 6956: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6957: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6958: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6959: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6960: if ($email) {
6961: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6962: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6963: }
1.899 raeburn 6964: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6965: if (defined($inststatus)) {
6966: $names{'inststatus'} = '';
6967: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6968: if (ref($usertypes) eq 'HASH') {
6969: my @okstatuses;
6970: foreach my $item (split(/:/,$inststatus)) {
6971: if (defined($usertypes->{$item})) {
6972: push(@okstatuses,$item);
6973: }
6974: }
6975: if (@okstatuses) {
6976: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6977: }
6978: }
6979: }
1.1075 raeburn 6980: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6981: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 6982: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6983: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6984: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6985: } else {
6986: $logmsg .= ' during self creation';
6987: }
1.1075 raeburn 6988: my $changed;
6989: if ($newuser) {
6990: $changed = 1;
6991: } else {
6992: foreach my $field (@fields) {
6993: if ($names{$field} ne $oldnames{$field}) {
6994: $changed = 1;
6995: last;
6996: }
6997: }
6998: }
6999: unless ($changed) {
7000: $logmsg = 'No changes in user information needed for: '.$logmsg;
7001: &logthis($logmsg);
7002: return 'ok';
7003: }
7004: my $reply = &put('environment', \%names, $udom,$uname);
7005: if ($reply ne 'ok') {
7006: return 'error: '.$reply;
7007: }
1.1087 raeburn 7008: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7009: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7010: }
1.1075 raeburn 7011: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7012: &devalidate_cache_new('namescache',$uname.':'.$udom);
7013: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7014: &logthis($logmsg);
1.134 albertel 7015: return 'ok';
1.80 www 7016: }
7017:
1.81 www 7018: # -------------------------------------------------------------- Modify student
1.80 www 7019:
1.81 www 7020: sub modifystudent {
7021: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7022: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7023: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7024: if (!$cid) {
1.620 albertel 7025: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7026: return 'not_in_class';
7027: }
1.80 www 7028: }
7029: # --------------------------------------------------------------- Make the user
1.81 www 7030: my $reply=&modifyuser
1.209 matthew 7031: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7032: $desiredhome,$email,$inststatus);
1.80 www 7033: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7034: # This will cause &modify_student_enrollment to get the uid from the
7035: # students environment
7036: $uid = undef if (!$forceid);
1.455 albertel 7037: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7038: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7039: return $reply;
7040: }
7041:
7042: sub modify_student_enrollment {
1.957 raeburn 7043: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7044: my ($cdom,$cnum,$chome);
7045: if (!$cid) {
1.620 albertel 7046: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7047: return 'not_in_class';
7048: }
1.620 albertel 7049: $cdom=$env{'course.'.$cid.'.domain'};
7050: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7051: } else {
7052: ($cdom,$cnum)=split(/_/,$cid);
7053: }
1.620 albertel 7054: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7055: if (!$chome) {
1.457 raeburn 7056: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7057: }
1.455 albertel 7058: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7059: # Make sure the user exists
1.81 www 7060: my $uhome=&homeserver($uname,$udom);
7061: if (($uhome eq '') || ($uhome eq 'no_host')) {
7062: return 'error: no such user';
7063: }
1.297 matthew 7064: # Get student data if we were not given enough information
7065: if (!defined($first) || $first eq '' ||
7066: !defined($last) || $last eq '' ||
7067: !defined($uid) || $uid eq '' ||
7068: !defined($middle) || $middle eq '' ||
7069: !defined($gene) || $gene eq '') {
1.294 matthew 7070: # They did not supply us with enough data to enroll the student, so
7071: # we need to pick up more information.
1.297 matthew 7072: my %tmp = &get('environment',
1.294 matthew 7073: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7074: ,$udom,$uname);
7075:
1.800 albertel 7076: #foreach my $key (keys(%tmp)) {
7077: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7078: #}
1.294 matthew 7079: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7080: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7081: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7082: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7083: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7084: }
1.556 albertel 7085: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7086: my $reply=cput('classlist',
7087: {"$uname:$udom" =>
1.515 raeburn 7088: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7089: $cdom,$cnum);
1.81 www 7090: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7091: return 'error: '.$reply;
1.652 albertel 7092: } else {
7093: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7094: }
1.297 matthew 7095: # Add student role to user
1.83 www 7096: my $uurl='/'.$cid;
1.81 www 7097: $uurl=~s/\_/\//g;
7098: if ($usec) {
7099: $uurl.='/'.$usec;
7100: }
1.957 raeburn 7101: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7102: }
7103:
1.556 albertel 7104: sub format_name {
7105: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7106: my $name;
7107: if ($first ne 'lastname') {
7108: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7109: } else {
7110: if ($lastname=~/\S/) {
7111: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7112: $name=~s/\s+,/,/;
7113: } else {
7114: $name.= $firstname.' '.$middlename.' '.$generation;
7115: }
7116: }
7117: $name=~s/^\s+//;
7118: $name=~s/\s+$//;
7119: $name=~s/\s+/ /g;
7120: return $name;
7121: }
7122:
1.84 www 7123: # ------------------------------------------------- Write to course preferences
7124:
7125: sub writecoursepref {
7126: my ($courseid,%prefs)=@_;
7127: $courseid=~s/^\///;
7128: $courseid=~s/\_/\//g;
7129: my ($cdomain,$cnum)=split(/\//,$courseid);
7130: my $chome=homeserver($cnum,$cdomain);
7131: if (($chome eq '') || ($chome eq 'no_host')) {
7132: return 'error: no such course';
7133: }
7134: my $cstring='';
1.800 albertel 7135: foreach my $pref (keys(%prefs)) {
7136: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7137: }
1.84 www 7138: $cstring=~s/\&$//;
7139: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7140: }
7141:
7142: # ---------------------------------------------------------- Make/modify course
7143:
7144: sub createcourse {
1.741 raeburn 7145: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7146: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7147: $url=&declutter($url);
7148: my $cid='';
1.1028 raeburn 7149: if ($context eq 'requestcourses') {
7150: my $can_create = 0;
7151: my ($ownername,$ownerdom) = split(':',$course_owner);
7152: if ($udom eq $ownerdom) {
7153: if (&usertools_access($ownername,$ownerdom,$category,undef,
7154: $context)) {
7155: $can_create = 1;
7156: }
7157: } else {
7158: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7159: $category);
7160: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7161: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7162: if (@curr > 0) {
7163: my @options = qw(approval validate autolimit);
7164: my $optregex = join('|',@options);
7165: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7166: $can_create = 1;
7167: }
7168: }
7169: }
7170: }
7171: if ($can_create) {
7172: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7173: unless (&allowed('ccc',$udom)) {
7174: return 'refused';
7175: }
1.1017 raeburn 7176: }
7177: } else {
7178: return 'refused';
7179: }
1.1028 raeburn 7180: } elsif (!&allowed('ccc',$udom)) {
7181: return 'refused';
1.84 www 7182: }
1.1011 raeburn 7183: # --------------------------------------------------------------- Get Unique ID
7184: my $uname;
7185: if ($cnum =~ /^$match_courseid$/) {
7186: my $chome=&homeserver($cnum,$udom,'true');
7187: if (($chome eq '') || ($chome eq 'no_host')) {
7188: $uname = $cnum;
7189: } else {
1.1038 raeburn 7190: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7191: }
7192: } else {
1.1038 raeburn 7193: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7194: }
7195: return $uname if ($uname =~ /^error/);
7196: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7197: if (!defined($course_server)) {
7198: if (defined(&domain($udom,'primary'))) {
7199: $course_server = &domain($udom,'primary');
7200: } else {
7201: $course_server = $env{'user.home'};
7202: }
7203: }
7204: my %host_servers =
7205: &Apache::lonnet::get_servers($udom,'library');
7206: unless ($host_servers{$course_server}) {
7207: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7208: }
1.84 www 7209: # ------------------------------------------------------------- Make the course
7210: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7211: $course_server);
1.84 www 7212: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7213: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7214: if (($uhome eq '') || ($uhome eq 'no_host')) {
7215: return 'error: no such course';
7216: }
1.271 www 7217: # ----------------------------------------------------------------- Course made
1.516 raeburn 7218: # log existence
1.1029 raeburn 7219: my $now = time;
1.918 raeburn 7220: my $newcourse = {
7221: $udom.'_'.$uname => {
1.921 raeburn 7222: description => $description,
7223: inst_code => $inst_code,
7224: owner => $course_owner,
7225: type => $crstype,
1.1029 raeburn 7226: creator => $env{'user.name'}.':'.
7227: $env{'user.domain'},
7228: created => $now,
7229: context => $context,
1.918 raeburn 7230: },
7231: };
1.921 raeburn 7232: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7233: # set toplevel url
1.271 www 7234: my $topurl=$url;
7235: unless ($nonstandard) {
7236: # ------------------------------------------ For standard courses, make top url
7237: my $mapurl=&clutter($url);
1.278 www 7238: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7239: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7240: <map>
7241: <resource id="1" type="start"></resource>
7242: <resource id="2" src="$mapurl"></resource>
7243: <resource id="3" type="finish"></resource>
7244: <link index="1" from="1" to="2"></link>
7245: <link index="2" from="2" to="3"></link>
7246: </map>
7247: ENDINITMAP
7248: $topurl=&declutter(
1.638 albertel 7249: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7250: );
7251: }
7252: # ----------------------------------------------------------- Write preferences
1.84 www 7253: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7254: ('description' => $description,
7255: 'url' => $topurl,
7256: 'internal.creator' => $env{'user.name'}.':'.
7257: $env{'user.domain'},
7258: 'internal.created' => $now,
7259: 'internal.creationcontext' => $context)
7260: );
1.84 www 7261: return '/'.$udom.'/'.$uname;
7262: }
7263:
1.1011 raeburn 7264: # ------------------------------------------------------------------- Create ID
7265: sub generate_coursenum {
1.1038 raeburn 7266: my ($udom,$crstype) = @_;
1.1011 raeburn 7267: my $domdesc = &domain($udom);
7268: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7269: my $first;
7270: if ($crstype eq 'Community') {
7271: $first = '0';
7272: } else {
7273: $first = int(1+rand(9));
7274: }
7275: my $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: # ----------------------------------------------- Make sure that does not exist
7280: my $uhome=&homeserver($uname,$udom,'true');
7281: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7282: if ($crstype eq 'Community') {
7283: $first = '0';
7284: } else {
7285: $first = int(1+rand(9));
7286: }
7287: $uname=$first.
1.1011 raeburn 7288: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7289: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7290: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7291: $uhome=&homeserver($uname,$udom,'true');
7292: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7293: return 'error: unable to generate unique course-ID';
7294: }
7295: }
7296: return $uname;
7297: }
7298:
1.813 albertel 7299: sub is_course {
7300: my ($cdom,$cnum) = @_;
7301: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7302: undef,'.');
1.813 albertel 7303: if (exists($courses{$cdom.'_'.$cnum})) {
7304: return 1;
7305: }
7306: return 0;
7307: }
7308:
1.1015 raeburn 7309: sub store_userdata {
7310: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7311: my $result;
1.1016 raeburn 7312: if ($datakey ne '') {
1.1013 raeburn 7313: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7314: if ($udom eq '' || $uname eq '') {
7315: $udom = $env{'user.domain'};
7316: $uname = $env{'user.name'};
7317: }
7318: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7319: if (($uhome eq '') || ($uhome eq 'no_host')) {
7320: $result = 'error: no_host';
7321: } else {
7322: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7323: $storehash->{'host'} = $perlvar{'lonHostID'};
7324:
7325: my $namevalue='';
7326: foreach my $key (keys(%{$storehash})) {
7327: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7328: }
7329: $namevalue=~s/\&$//;
1.1105 raeburn 7330: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7331: $namevalue,$uhome);
1.1013 raeburn 7332: }
7333: } else {
7334: $result = 'error: data to store was not a hash reference';
7335: }
7336: } else {
7337: $result= 'error: invalid requestkey';
7338: }
7339: return $result;
7340: }
7341:
1.21 www 7342: # ---------------------------------------------------------- Assign Custom Role
7343:
7344: sub assigncustomrole {
1.957 raeburn 7345: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7346: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7347: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7348: }
7349:
7350: # ----------------------------------------------------------------- Revoke Role
7351:
7352: sub revokerole {
1.957 raeburn 7353: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7354: my $now=time;
1.965 raeburn 7355: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7356: }
7357:
7358: # ---------------------------------------------------------- Revoke Custom Role
7359:
7360: sub revokecustomrole {
1.957 raeburn 7361: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7362: my $now=time;
1.357 www 7363: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7364: $deleteflag,$selfenroll,$context);
1.17 www 7365: }
7366:
1.533 banghart 7367: # ------------------------------------------------------------ Disk usage
1.535 albertel 7368: sub diskusage {
1.955 raeburn 7369: my ($udom,$uname,$directorypath,$getpropath)=@_;
7370: $directorypath =~ s/\/$//;
7371: my $listing=&reply('du2:'.&escape($directorypath).':'
7372: .&escape($getpropath).':'.&escape($uname).':'
7373: .&escape($udom),homeserver($uname,$udom));
7374: if ($listing eq 'unknown_cmd') {
7375: if ($getpropath) {
7376: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7377: }
7378: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7379: }
1.514 albertel 7380: return $listing;
1.512 banghart 7381: }
7382:
1.566 banghart 7383: sub is_locked {
1.1096 raeburn 7384: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7385: my @check;
7386: my $is_locked;
1.1093 raeburn 7387: push (@check,$file_name);
1.613 albertel 7388: my %locked = &get('file_permissions',\@check,
1.620 albertel 7389: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7390: my ($tmp)=keys(%locked);
7391: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7392:
1.566 banghart 7393: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7394: $is_locked = 'false';
7395: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 7396: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7397: $is_locked = 'true';
1.1096 raeburn 7398: if (ref($which) eq 'ARRAY') {
7399: push(@{$which},$entry);
7400: } else {
7401: last;
7402: }
1.745 raeburn 7403: }
7404: }
1.566 banghart 7405: } else {
7406: $is_locked = 'false';
7407: }
1.1093 raeburn 7408: return $is_locked;
1.566 banghart 7409: }
7410:
1.759 albertel 7411: sub declutter_portfile {
7412: my ($file) = @_;
1.833 albertel 7413: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7414: return $file;
7415: }
7416:
1.559 banghart 7417: # ------------------------------------------------------------- Mark as Read Only
7418:
7419: sub mark_as_readonly {
7420: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7421: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7422: my ($tmp)=keys(%current_permissions);
7423: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7424: foreach my $file (@{$files}) {
1.759 albertel 7425: $file = &declutter_portfile($file);
1.561 banghart 7426: push(@{$current_permissions{$file}},$what);
1.559 banghart 7427: }
1.613 albertel 7428: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7429: return;
7430: }
7431:
1.572 banghart 7432: # ------------------------------------------------------------Save Selected Files
7433:
7434: sub save_selected_files {
7435: my ($user, $path, @files) = @_;
7436: my $filename = $user."savedfiles";
1.573 banghart 7437: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7438: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7439: foreach my $file (@files) {
1.620 albertel 7440: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7441: }
7442: foreach my $file (@other_files) {
1.574 banghart 7443: print (OUT $file."\n");
1.572 banghart 7444: }
1.574 banghart 7445: close (OUT);
1.572 banghart 7446: return 'ok';
7447: }
7448:
1.574 banghart 7449: sub clear_selected_files {
7450: my ($user) = @_;
7451: my $filename = $user."savedfiles";
7452: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7453: print (OUT undef);
7454: close (OUT);
7455: return ("ok");
7456: }
7457:
1.572 banghart 7458: sub files_in_path {
7459: my ($user, $path) = @_;
7460: my $filename = $user."savedfiles";
7461: my %return_files;
1.574 banghart 7462: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7463: while (my $line_in = <IN>) {
1.574 banghart 7464: chomp ($line_in);
7465: my @paths_and_file = split (m!/!, $line_in);
7466: my $file_part = pop (@paths_and_file);
7467: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7468: $path_part.='/';
7469: my $path_and_file = $path_part.$file_part;
7470: if ($path_part eq $path) {
7471: $return_files{$file_part}= 'selected';
7472: }
7473: }
1.574 banghart 7474: close (IN);
7475: return (\%return_files);
1.572 banghart 7476: }
7477:
7478: # called in portfolio select mode, to show files selected NOT in current directory
7479: sub files_not_in_path {
7480: my ($user, $path) = @_;
7481: my $filename = $user."savedfiles";
7482: my @return_files;
7483: my $path_part;
1.800 albertel 7484: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7485: while (my $line = <IN>) {
1.572 banghart 7486: #ok, I know it's clunky, but I want it to work
1.800 albertel 7487: my @paths_and_file = split(m|/|, $line);
7488: my $file_part = pop(@paths_and_file);
7489: chomp($file_part);
7490: my $path_part = join('/', @paths_and_file);
1.572 banghart 7491: $path_part .= '/';
7492: my $path_and_file = $path_part.$file_part;
7493: if ($path_part ne $path) {
1.800 albertel 7494: push(@return_files, ($path_and_file));
1.572 banghart 7495: }
7496: }
1.800 albertel 7497: close(OUT);
1.574 banghart 7498: return (@return_files);
1.572 banghart 7499: }
7500:
1.745 raeburn 7501: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7502:
1.745 raeburn 7503: sub get_portfile_permissions {
7504: my ($domain,$user) = @_;
1.613 albertel 7505: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7506: my ($tmp)=keys(%current_permissions);
7507: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7508: return \%current_permissions;
7509: }
7510:
7511: #---------------------------------------------Get portfolio file access controls
7512:
1.749 raeburn 7513: sub get_access_controls {
1.745 raeburn 7514: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7515: my %access;
7516: my $real_file = $file;
7517: $file =~ s/\.meta$//;
1.745 raeburn 7518: if (defined($file)) {
1.749 raeburn 7519: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7520: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7521: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7522: }
7523: }
1.745 raeburn 7524: } else {
1.749 raeburn 7525: foreach my $key (keys(%{$current_permissions})) {
7526: if ($key =~ /\0accesscontrol$/) {
7527: if (defined($group)) {
7528: if ($key !~ m-^\Q$group\E/-) {
7529: next;
7530: }
7531: }
7532: my ($fullpath) = split(/\0/,$key);
7533: if (ref($$current_permissions{$key}) eq 'HASH') {
7534: foreach my $control (keys(%{$$current_permissions{$key}})) {
7535: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7536: }
7537: }
7538: }
7539: }
7540: }
7541: return %access;
7542: }
7543:
7544: sub modify_access_controls {
7545: my ($file_name,$changes,$domain,$user)=@_;
7546: my ($outcome,$deloutcome);
7547: my %store_permissions;
7548: my %new_values;
7549: my %new_control;
7550: my %translation;
7551: my @deletions = ();
7552: my $now = time;
7553: if (exists($$changes{'activate'})) {
7554: if (ref($$changes{'activate'}) eq 'HASH') {
7555: my @newitems = sort(keys(%{$$changes{'activate'}}));
7556: my $numnew = scalar(@newitems);
7557: for (my $i=0; $i<$numnew; $i++) {
7558: my $newkey = $newitems[$i];
7559: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7560: if ($newkey =~ /^\d+:/) {
7561: $newkey =~ s/^(\d+)/$newid/;
7562: $translation{$1} = $newid;
7563: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7564: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7565: $translation{$1} = $newid;
7566: }
1.749 raeburn 7567: $new_values{$file_name."\0".$newkey} =
7568: $$changes{'activate'}{$newitems[$i]};
7569: $new_control{$newkey} = $now;
7570: }
7571: }
7572: }
7573: my %todelete;
7574: my %changed_items;
7575: foreach my $action ('delete','update') {
7576: if (exists($$changes{$action})) {
7577: if (ref($$changes{$action}) eq 'HASH') {
7578: foreach my $key (keys(%{$$changes{$action}})) {
7579: my ($itemnum) = ($key =~ /^([^:]+):/);
7580: if ($action eq 'delete') {
7581: $todelete{$itemnum} = 1;
7582: } else {
7583: $changed_items{$itemnum} = $key;
7584: }
7585: }
1.745 raeburn 7586: }
7587: }
1.749 raeburn 7588: }
7589: # get lock on access controls for file.
7590: my $lockhash = {
7591: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7592: ':'.$env{'user.domain'},
7593: };
7594: my $tries = 0;
7595: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7596:
7597: while (($gotlock ne 'ok') && $tries <3) {
7598: $tries ++;
7599: sleep 1;
7600: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7601: }
7602: if ($gotlock eq 'ok') {
7603: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7604: my ($tmp)=keys(%curr_permissions);
7605: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7606: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7607: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7608: if (ref($curr_controls) eq 'HASH') {
7609: foreach my $control_item (keys(%{$curr_controls})) {
7610: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7611: if (defined($todelete{$itemnum})) {
7612: push(@deletions,$file_name."\0".$control_item);
7613: } else {
7614: if (defined($changed_items{$itemnum})) {
7615: $new_control{$changed_items{$itemnum}} = $now;
7616: push(@deletions,$file_name."\0".$control_item);
7617: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7618: } else {
7619: $new_control{$control_item} = $$curr_controls{$control_item};
7620: }
7621: }
1.745 raeburn 7622: }
7623: }
7624: }
1.970 raeburn 7625: my ($group);
7626: if (&is_course($domain,$user)) {
7627: ($group,my $file) = split(/\//,$file_name,2);
7628: }
1.749 raeburn 7629: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7630: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7631: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7632: # remove lock
7633: my @del_lock = ($file_name."\0".'locked_access_records');
7634: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7635: my $sqlresult =
1.970 raeburn 7636: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7637: $group);
1.749 raeburn 7638: } else {
7639: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7640: }
1.749 raeburn 7641: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7642: }
7643:
1.827 raeburn 7644: sub make_public_indefinitely {
7645: my ($requrl) = @_;
7646: my $now = time;
7647: my $action = 'activate';
7648: my $aclnum = 0;
7649: if (&is_portfolio_url($requrl)) {
7650: my (undef,$udom,$unum,$file_name,$group) =
7651: &parse_portfolio_url($requrl);
7652: my $current_perms = &get_portfile_permissions($udom,$unum);
7653: my %access_controls = &get_access_controls($current_perms,
7654: $group,$file_name);
7655: foreach my $key (keys(%{$access_controls{$file_name}})) {
7656: my ($num,$scope,$end,$start) =
7657: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7658: if ($scope eq 'public') {
7659: if ($start <= $now && $end == 0) {
7660: $action = 'none';
7661: } else {
7662: $action = 'update';
7663: $aclnum = $num;
7664: }
7665: last;
7666: }
7667: }
7668: if ($action eq 'none') {
7669: return 'ok';
7670: } else {
7671: my %changes;
7672: my $newend = 0;
7673: my $newstart = $now;
7674: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7675: $changes{$action}{$newkey} = {
7676: type => 'public',
7677: time => {
7678: start => $newstart,
7679: end => $newend,
7680: },
7681: };
7682: my ($outcome,$deloutcome,$new_values,$translation) =
7683: &modify_access_controls($file_name,\%changes,$udom,$unum);
7684: return $outcome;
7685: }
7686: } else {
7687: return 'invalid';
7688: }
7689: }
7690:
1.745 raeburn 7691: #------------------------------------------------------Get Marked as Read Only
7692:
7693: sub get_marked_as_readonly {
7694: my ($domain,$user,$what,$group) = @_;
7695: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7696: my @readonly_files;
1.629 banghart 7697: my $cmp1=$what;
7698: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7699: while (my ($file_name,$value) = each(%{$current_permissions})) {
7700: if (defined($group)) {
7701: if ($file_name !~ m-^\Q$group\E/-) {
7702: next;
7703: }
7704: }
1.561 banghart 7705: if (ref($value) eq "ARRAY"){
7706: foreach my $stored_what (@{$value}) {
1.629 banghart 7707: my $cmp2=$stored_what;
1.759 albertel 7708: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7709: $cmp2=join('',@{$stored_what});
1.745 raeburn 7710: }
1.629 banghart 7711: if ($cmp1 eq $cmp2) {
1.561 banghart 7712: push(@readonly_files, $file_name);
1.745 raeburn 7713: last;
1.563 banghart 7714: } elsif (!defined($what)) {
7715: push(@readonly_files, $file_name);
1.745 raeburn 7716: last;
1.561 banghart 7717: }
7718: }
1.745 raeburn 7719: }
1.561 banghart 7720: }
7721: return @readonly_files;
7722: }
1.577 banghart 7723: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7724:
1.577 banghart 7725: sub get_marked_as_readonly_hash {
1.745 raeburn 7726: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7727: my %readonly_files;
1.745 raeburn 7728: while (my ($file_name,$value) = each(%{$current_permissions})) {
7729: if (defined($group)) {
7730: if ($file_name !~ m-^\Q$group\E/-) {
7731: next;
7732: }
7733: }
1.577 banghart 7734: if (ref($value) eq "ARRAY"){
7735: foreach my $stored_what (@{$value}) {
1.745 raeburn 7736: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7737: foreach my $lock_descriptor(@{$stored_what}) {
7738: if ($lock_descriptor eq 'graded') {
7739: $readonly_files{$file_name} = 'graded';
7740: } elsif ($lock_descriptor eq 'handback') {
7741: $readonly_files{$file_name} = 'handback';
7742: } else {
7743: if (!exists($readonly_files{$file_name})) {
7744: $readonly_files{$file_name} = 'locked';
7745: }
7746: }
1.745 raeburn 7747: }
1.750 banghart 7748: }
1.577 banghart 7749: }
7750: }
7751: }
7752: return %readonly_files;
7753: }
1.559 banghart 7754: # ------------------------------------------------------------ Unmark as Read Only
7755:
7756: sub unmark_as_readonly {
1.629 banghart 7757: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7758: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7759: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7760: $file_name = &declutter_portfile($file_name);
1.634 albertel 7761: my $symb_crs = $what;
7762: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7763: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7764: my ($tmp)=keys(%current_permissions);
7765: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7766: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7767: foreach my $file (@readonly_files) {
1.759 albertel 7768: my $clean_file = &declutter_portfile($file);
7769: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7770: my $current_locks = $current_permissions{$file};
1.563 banghart 7771: my @new_locks;
7772: my @del_keys;
7773: if (ref($current_locks) eq "ARRAY"){
7774: foreach my $locker (@{$current_locks}) {
1.632 albertel 7775: my $compare=$locker;
1.749 raeburn 7776: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7777: $compare=join('',@{$locker});
1.746 raeburn 7778: if ($compare ne $symb_crs) {
7779: push(@new_locks, $locker);
7780: }
1.563 banghart 7781: }
7782: }
1.650 albertel 7783: if (scalar(@new_locks) > 0) {
1.563 banghart 7784: $current_permissions{$file} = \@new_locks;
7785: } else {
7786: push(@del_keys, $file);
1.613 albertel 7787: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7788: delete($current_permissions{$file});
1.563 banghart 7789: }
7790: }
1.561 banghart 7791: }
1.613 albertel 7792: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7793: return;
7794: }
1.512 banghart 7795:
1.17 www 7796: # ------------------------------------------------------------ Directory lister
7797:
7798: sub dirlist {
1.955 raeburn 7799: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7800: $uri=~s/^\///;
7801: $uri=~s/\/$//;
1.253 stredwic 7802: my ($udom, $uname);
1.955 raeburn 7803: if ($getuserdir) {
1.253 stredwic 7804: $udom = $userdomain;
7805: $uname = $username;
1.955 raeburn 7806: } else {
7807: (undef,$udom,$uname)=split(/\//,$uri);
7808: if(defined($userdomain)) {
7809: $udom = $userdomain;
7810: }
7811: if(defined($username)) {
7812: $uname = $username;
7813: }
1.253 stredwic 7814: }
1.955 raeburn 7815: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7816:
1.955 raeburn 7817: $dirRoot = $perlvar{'lonDocRoot'};
7818: if (defined($getpropath)) {
7819: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7820: $dirRoot =~ s/\/$//;
1.955 raeburn 7821: } elsif (defined($getuserdir)) {
7822: my $subdir=$uname.'__';
7823: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7824: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7825: ."/$udom/$subdir/$uname";
7826: } elsif (defined($alternateRoot)) {
7827: $dirRoot = $alternateRoot;
1.751 banghart 7828: }
1.253 stredwic 7829:
7830: if($udom) {
7831: if($uname) {
1.955 raeburn 7832: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7833: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7834: .':'.&escape($uname).':'.&escape($udom),
7835: &homeserver($uname,$udom));
7836: if ($listing eq 'unknown_cmd') {
7837: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7838: &homeserver($uname,$udom));
7839: } else {
7840: @listing_results = map { &unescape($_); } split(/:/,$listing);
7841: }
1.605 matthew 7842: if ($listing eq 'unknown_cmd') {
1.800 albertel 7843: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7844: &homeserver($uname,$udom));
1.605 matthew 7845: @listing_results = split(/:/,$listing);
7846: } else {
7847: @listing_results = map { &unescape($_); } split(/:/,$listing);
7848: }
7849: return @listing_results;
1.955 raeburn 7850: } elsif(!$alternateRoot) {
1.800 albertel 7851: my %allusers;
1.841 albertel 7852: my %servers = &get_servers($udom,'library');
1.955 raeburn 7853: foreach my $tryserver (keys(%servers)) {
7854: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7855: &escape($udom),$tryserver);
7856: if ($listing eq 'unknown_cmd') {
7857: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7858: $udom, $tryserver);
7859: } else {
7860: @listing_results = map { &unescape($_); } split(/:/,$listing);
7861: }
1.841 albertel 7862: if ($listing eq 'unknown_cmd') {
7863: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7864: $udom, $tryserver);
7865: @listing_results = split(/:/,$listing);
7866: } else {
7867: @listing_results =
7868: map { &unescape($_); } split(/:/,$listing);
7869: }
7870: if ($listing_results[0] ne 'no_such_dir' &&
7871: $listing_results[0] ne 'empty' &&
7872: $listing_results[0] ne 'con_lost') {
7873: foreach my $line (@listing_results) {
7874: my ($entry) = split(/&/,$line,2);
7875: $allusers{$entry} = 1;
7876: }
7877: }
1.253 stredwic 7878: }
7879: my $alluserstr='';
1.800 albertel 7880: foreach my $user (sort(keys(%allusers))) {
7881: $alluserstr.=$user.'&user:';
1.253 stredwic 7882: }
7883: $alluserstr=~s/:$//;
7884: return split(/:/,$alluserstr);
7885: } else {
1.800 albertel 7886: return ('missing user name');
1.253 stredwic 7887: }
1.955 raeburn 7888: } elsif(!defined($getpropath)) {
1.841 albertel 7889: my @all_domains = sort(&all_domains());
1.955 raeburn 7890: foreach my $domain (@all_domains) {
7891: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7892: }
7893: return @all_domains;
7894: } else {
1.800 albertel 7895: return ('missing domain');
1.275 stredwic 7896: }
7897: }
7898:
7899: # --------------------------------------------- GetFileTimestamp
7900: # This function utilizes dirlist and returns the date stamp for
7901: # when it was last modified. It will also return an error of -1
7902: # if an error occurs
7903:
7904: sub GetFileTimestamp {
1.955 raeburn 7905: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7906: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7907: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7908: my ($fileStat) =
7909: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7910: undef,$getuserdir);
1.275 stredwic 7911: my @stats = split('&', $fileStat);
7912: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7913: # @stats contains first the filename, then the stat output
7914: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7915: } else {
7916: return -1;
1.253 stredwic 7917: }
1.26 www 7918: }
7919:
1.712 albertel 7920: sub stat_file {
7921: my ($uri) = @_;
1.787 albertel 7922: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7923:
1.955 raeburn 7924: my ($udom,$uname,$file);
1.712 albertel 7925: if ($uri =~ m-^/(uploaded|editupload)/-) {
7926: ($udom,$uname,$file) =
1.811 albertel 7927: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7928: $file = 'userfiles/'.$file;
7929: }
7930: if ($uri =~ m-^/res/-) {
7931: ($udom,$uname) =
1.807 albertel 7932: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7933: $file = $uri;
7934: }
7935:
7936: if (!$udom || !$uname || !$file) {
7937: # unable to handle the uri
7938: return ();
7939: }
1.956 raeburn 7940: my $getpropath;
7941: if ($file =~ /^userfiles\//) {
7942: $getpropath = 1;
7943: }
1.955 raeburn 7944: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7945: my @stats = split('&', $result);
1.721 banghart 7946:
1.712 albertel 7947: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7948: shift(@stats); #filename is first
7949: return @stats;
7950: }
7951: return ();
7952: }
7953:
1.26 www 7954: # -------------------------------------------------------- Value of a Condition
7955:
1.713 albertel 7956: # gets the value of a specific preevaluated condition
7957: # stored in the string $env{user.state.<cid>}
7958: # or looks up a condition reference in the bighash and if if hasn't
7959: # already been evaluated recurses into docondval to get the value of
7960: # the condition, then memoizing it to
7961: # $env{user.state.<cid>.<condition>}
1.40 www 7962: sub directcondval {
7963: my $number=shift;
1.620 albertel 7964: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7965: &Apache::lonuserstate::evalstate();
7966: }
1.713 albertel 7967: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7968: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7969: } elsif ($number =~ /^_/) {
7970: my $sub_condition;
7971: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7972: &GDBM_READER(),0640)) {
7973: $sub_condition=$bighash{'conditions'.$number};
7974: untie(%bighash);
7975: }
7976: my $value = &docondval($sub_condition);
1.949 raeburn 7977: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7978: return $value;
7979: }
1.620 albertel 7980: if ($env{'user.state.'.$env{'request.course.id'}}) {
7981: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7982: } else {
7983: return 2;
7984: }
7985: }
7986:
1.713 albertel 7987: # get the collection of conditions for this resource
1.26 www 7988: sub condval {
7989: my $condidx=shift;
1.54 www 7990: my $allpathcond='';
1.713 albertel 7991: foreach my $cond (split(/\|/,$condidx)) {
7992: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7993: $allpathcond.=
7994: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7995: }
1.191 harris41 7996: }
1.54 www 7997: $allpathcond=~s/\|$//;
1.713 albertel 7998: return &docondval($allpathcond);
7999: }
8000:
8001: #evaluates an expression of conditions
8002: sub docondval {
8003: my ($allpathcond) = @_;
8004: my $result=0;
8005: if ($env{'request.course.id'}
8006: && defined($allpathcond)) {
8007: my $operand='|';
8008: my @stack;
8009: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8010: if ($chunk eq '(') {
8011: push @stack,($operand,$result);
8012: } elsif ($chunk eq ')') {
8013: my $before=pop @stack;
8014: if (pop @stack eq '&') {
8015: $result=$result>$before?$before:$result;
8016: } else {
8017: $result=$result>$before?$result:$before;
8018: }
8019: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8020: $operand=$chunk;
8021: } else {
8022: my $new=directcondval($chunk);
8023: if ($operand eq '&') {
8024: $result=$result>$new?$new:$result;
8025: } else {
8026: $result=$result>$new?$result:$new;
8027: }
8028: }
8029: }
1.26 www 8030: }
8031: return $result;
1.421 albertel 8032: }
8033:
8034: # ---------------------------------------------------- Devalidate courseresdata
8035:
8036: sub devalidatecourseresdata {
8037: my ($coursenum,$coursedomain)=@_;
8038: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8039: &devalidate_cache_new('courseres',$hashid);
1.28 www 8040: }
8041:
1.763 www 8042:
1.200 www 8043: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8044: #
8045: # Parameters:
8046: # $coursenum - Number of the course.
8047: # $coursedomain - Domain at which the course was created.
8048: # Returns:
8049: # A hash of the course parameters along (I think) with timestamps
8050: # and version info.
1.877 foxr 8051:
1.624 albertel 8052: sub get_courseresdata {
8053: my ($coursenum,$coursedomain)=@_;
1.200 www 8054: my $coursehom=&homeserver($coursenum,$coursedomain);
8055: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8056: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8057: my %dumpreply;
1.417 albertel 8058: unless (defined($cached)) {
1.624 albertel 8059: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8060: $result=\%dumpreply;
1.251 albertel 8061: my ($tmp) = keys(%dumpreply);
8062: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8063: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8064: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8065: return $tmp;
1.416 albertel 8066: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8067: $result=undef;
1.599 albertel 8068: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8069: }
8070: }
1.624 albertel 8071: return $result;
8072: }
8073:
1.633 albertel 8074: sub devalidateuserresdata {
8075: my ($uname,$udom)=@_;
8076: my $hashid="$udom:$uname";
8077: &devalidate_cache_new('userres',$hashid);
8078: }
8079:
1.624 albertel 8080: sub get_userresdata {
8081: my ($uname,$udom)=@_;
8082: #most student don\'t have any data set, check if there is some data
8083: if (&EXT_cache_status($udom,$uname)) { return undef; }
8084:
8085: my $hashid="$udom:$uname";
8086: my ($result,$cached)=&is_cached_new('userres',$hashid);
8087: if (!defined($cached)) {
8088: my %resourcedata=&dump('resourcedata',$udom,$uname);
8089: $result=\%resourcedata;
8090: &do_cache_new('userres',$hashid,$result,600);
8091: }
8092: my ($tmp)=keys(%$result);
8093: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8094: return $result;
8095: }
8096: #error 2 occurs when the .db doesn't exist
8097: if ($tmp!~/error: 2 /) {
1.672 albertel 8098: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8099: " Trying to get resource data for ".
8100: $uname." at ".$udom.": ".
8101: $tmp."</font>");
8102: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8103: #&EXT_cache_set($udom,$uname);
8104: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8105: undef($tmp); # not really an error so don't send it back
1.624 albertel 8106: }
8107: return $tmp;
8108: }
1.879 foxr 8109: #----------------------------------------------- resdata - return resource data
8110: # Purpose:
8111: # Return resource data for either users or for a course.
8112: # Parameters:
8113: # $name - Course/user name.
8114: # $domain - Name of the domain the user/course is registered on.
8115: # $type - Type of thing $name is (must be 'course' or 'user'
8116: # @which - Array of names of resources desired.
8117: # Returns:
8118: # The value of the first reasource in @which that is found in the
8119: # resource hash.
8120: # Exceptional Conditions:
8121: # If the $type passed in is not valid (not the string 'course' or
8122: # 'user', an undefined reference is returned.
8123: # If none of the resources are found, an undef is returned
1.624 albertel 8124: sub resdata {
8125: my ($name,$domain,$type,@which)=@_;
8126: my $result;
8127: if ($type eq 'course') {
8128: $result=&get_courseresdata($name,$domain);
8129: } elsif ($type eq 'user') {
8130: $result=&get_userresdata($name,$domain);
8131: }
8132: if (!ref($result)) { return $result; }
1.251 albertel 8133: foreach my $item (@which) {
1.927 albertel 8134: if (defined($result->{$item->[0]})) {
8135: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8136: }
1.250 albertel 8137: }
1.291 albertel 8138: return undef;
1.200 www 8139: }
8140:
1.379 matthew 8141: #
8142: # EXT resource caching routines
8143: #
8144:
8145: sub clear_EXT_cache_status {
1.383 albertel 8146: &delenv('cache.EXT.');
1.379 matthew 8147: }
8148:
8149: sub EXT_cache_status {
8150: my ($target_domain,$target_user) = @_;
1.383 albertel 8151: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8152: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8153: # We know already the user has no data
8154: return 1;
8155: } else {
8156: return 0;
8157: }
8158: }
8159:
8160: sub EXT_cache_set {
8161: my ($target_domain,$target_user) = @_;
1.383 albertel 8162: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8163: #&appenv({$cachename => time});
1.379 matthew 8164: }
8165:
1.28 www 8166: # --------------------------------------------------------- Value of a Variable
1.58 www 8167: sub EXT {
1.715 albertel 8168:
1.395 albertel 8169: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8170: unless ($varname) { return ''; }
1.218 albertel 8171: #get real user name/domain, courseid and symb
8172: my $courseid;
1.359 albertel 8173: my $publicuser;
1.427 www 8174: if ($symbparm) {
8175: $symbparm=&get_symb_from_alias($symbparm);
8176: }
1.218 albertel 8177: if (!($uname && $udom)) {
1.790 albertel 8178: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8179: if (!$symbparm) { $symbparm=$cursymb; }
8180: } else {
1.620 albertel 8181: $courseid=$env{'request.course.id'};
1.218 albertel 8182: }
1.48 www 8183: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8184: my $rest;
1.320 albertel 8185: if (defined($therest[0])) {
1.48 www 8186: $rest=join('.',@therest);
8187: } else {
8188: $rest='';
8189: }
1.320 albertel 8190:
1.57 www 8191: my $qualifierrest=$qualifier;
8192: if ($rest) { $qualifierrest.='.'.$rest; }
8193: my $spacequalifierrest=$space;
8194: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8195: if ($realm eq 'user') {
1.48 www 8196: # --------------------------------------------------------------- user.resource
8197: if ($space eq 'resource') {
1.651 albertel 8198: if ( (defined($Apache::lonhomework::parsing_a_problem)
8199: || defined($Apache::lonhomework::parsing_a_task))
8200: &&
1.744 albertel 8201: ($symbparm eq &symbread()) ) {
8202: # if we are in the middle of processing the resource the
8203: # get the value we are planning on committing
8204: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8205: return $Apache::lonhomework::results{$qualifierrest};
8206: } else {
8207: return $Apache::lonhomework::history{$qualifierrest};
8208: }
1.335 albertel 8209: } else {
1.359 albertel 8210: my %restored;
1.620 albertel 8211: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8212: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8213: } else {
8214: %restored=&restore($symbparm,$courseid,$udom,$uname);
8215: }
1.335 albertel 8216: return $restored{$qualifierrest};
8217: }
1.48 www 8218: # ----------------------------------------------------------------- user.access
8219: } elsif ($space eq 'access') {
1.218 albertel 8220: # FIXME - not supporting calls for a specific user
1.48 www 8221: return &allowed($qualifier,$rest);
8222: # ------------------------------------------ user.preferences, user.environment
8223: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8224: if (($uname eq $env{'user.name'}) &&
8225: ($udom eq $env{'user.domain'})) {
8226: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8227: } else {
1.359 albertel 8228: my %returnhash;
8229: if (!$publicuser) {
8230: %returnhash=&userenvironment($udom,$uname,
8231: $qualifierrest);
8232: }
1.218 albertel 8233: return $returnhash{$qualifierrest};
8234: }
1.48 www 8235: # ----------------------------------------------------------------- user.course
8236: } elsif ($space eq 'course') {
1.218 albertel 8237: # FIXME - not supporting calls for a specific user
1.620 albertel 8238: return $env{join('.',('request.course',$qualifier))};
1.48 www 8239: # ------------------------------------------------------------------- user.role
8240: } elsif ($space eq 'role') {
1.218 albertel 8241: # FIXME - not supporting calls for a specific user
1.620 albertel 8242: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8243: if ($qualifier eq 'value') {
8244: return $role;
8245: } elsif ($qualifier eq 'extent') {
8246: return $where;
8247: }
8248: # ----------------------------------------------------------------- user.domain
8249: } elsif ($space eq 'domain') {
1.218 albertel 8250: return $udom;
1.48 www 8251: # ------------------------------------------------------------------- user.name
8252: } elsif ($space eq 'name') {
1.218 albertel 8253: return $uname;
1.48 www 8254: # ---------------------------------------------------- Any other user namespace
1.29 www 8255: } else {
1.359 albertel 8256: my %reply;
8257: if (!$publicuser) {
8258: %reply=&get($space,[$qualifierrest],$udom,$uname);
8259: }
8260: return $reply{$qualifierrest};
1.48 www 8261: }
1.236 www 8262: } elsif ($realm eq 'query') {
8263: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8264: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8265: [$spacequalifierrest]);
1.620 albertel 8266: return $env{'form.'.$spacequalifierrest};
1.236 www 8267: } elsif ($realm eq 'request') {
1.48 www 8268: # ------------------------------------------------------------- request.browser
8269: if ($space eq 'browser') {
1.430 www 8270: if ($qualifier eq 'textremote') {
1.676 albertel 8271: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8272: return 1;
8273: } else {
8274: return 0;
8275: }
8276: } else {
1.620 albertel 8277: return $env{'browser.'.$qualifier};
1.430 www 8278: }
1.57 www 8279: # ------------------------------------------------------------ request.filename
8280: } else {
1.620 albertel 8281: return $env{'request.'.$spacequalifierrest};
1.29 www 8282: }
1.28 www 8283: } elsif ($realm eq 'course') {
1.48 www 8284: # ---------------------------------------------------------- course.description
1.620 albertel 8285: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8286: } elsif ($realm eq 'resource') {
1.165 www 8287:
1.620 albertel 8288: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8289: if (!$symbparm) { $symbparm=&symbread(); }
8290: }
1.693 albertel 8291:
8292: if ($space eq 'title') {
8293: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8294: return &gettitle($symbparm);
8295: }
8296:
8297: if ($space eq 'map') {
8298: my ($map) = &decode_symb($symbparm);
8299: return &symbread($map);
8300: }
1.905 albertel 8301: if ($space eq 'filename') {
8302: if ($symbparm) {
8303: return &clutter((&decode_symb($symbparm))[2]);
8304: }
8305: return &hreflocation('',$env{'request.filename'});
8306: }
1.693 albertel 8307:
8308: my ($section, $group, @groups);
1.593 albertel 8309: my ($courselevelm,$courselevel);
1.539 albertel 8310: if ($symbparm && defined($courseid) &&
1.620 albertel 8311: $courseid eq $env{'request.course.id'}) {
1.165 www 8312:
1.218 albertel 8313: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8314:
1.60 www 8315: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8316: my $symbp=$symbparm;
1.735 albertel 8317: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8318:
8319: my $symbparm=$symbp.'.'.$spacequalifierrest;
8320: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8321:
1.620 albertel 8322: if (($env{'user.name'} eq $uname) &&
8323: ($env{'user.domain'} eq $udom)) {
8324: $section=$env{'request.course.sec'};
1.733 raeburn 8325: @groups = split(/:/,$env{'request.course.groups'});
8326: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8327: } else {
1.539 albertel 8328: if (! defined($usection)) {
1.551 albertel 8329: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8330: } else {
8331: $section = $usection;
8332: }
1.733 raeburn 8333: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8334: }
8335:
8336: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8337: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8338: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8339:
1.593 albertel 8340: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8341: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8342: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8343:
1.60 www 8344: # ----------------------------------------------------------- first, check user
1.624 albertel 8345:
8346: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8347: ([$courselevelr,'resource'],
8348: [$courselevelm,'map' ],
8349: [$courselevel, 'course' ]));
1.931 albertel 8350: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8351:
1.594 albertel 8352: # ------------------------------------------------ second, check some of course
1.684 raeburn 8353: my $coursereply;
1.691 raeburn 8354: if (@groups > 0) {
8355: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8356: $mapparm,$spacequalifierrest);
1.927 albertel 8357: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8358: }
1.96 www 8359:
1.684 raeburn 8360: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8361: $env{'course.'.$courseid.'.domain'},
8362: 'course',
8363: ([$seclevelr, 'resource'],
8364: [$seclevelm, 'map' ],
8365: [$seclevel, 'course' ],
8366: [$courselevelr,'resource']));
8367: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8368:
1.60 www 8369: # ------------------------------------------------------ third, check map parms
1.218 albertel 8370: my %parmhash=();
8371: my $thisparm='';
8372: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8373: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8374: &GDBM_READER(),0640)) {
1.218 albertel 8375: $thisparm=$parmhash{$symbparm};
8376: untie(%parmhash);
8377: }
1.927 albertel 8378: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8379: }
1.594 albertel 8380: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8381:
1.218 albertel 8382: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8383: my $filename;
8384: if (!$symbparm) { $symbparm=&symbread(); }
8385: if ($symbparm) {
1.409 www 8386: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8387: } else {
1.620 albertel 8388: $filename=$env{'request.filename'};
1.282 albertel 8389: }
8390: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8391: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8392: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8393: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8394:
1.927 albertel 8395: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8396: if ($symbparm && defined($courseid) &&
1.620 albertel 8397: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8398: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8399: $env{'course.'.$courseid.'.domain'},
8400: 'course',
1.927 albertel 8401: ([$courselevelm,'map' ],
8402: [$courselevel, 'course']));
8403: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8404: }
1.145 www 8405: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8406: unless ($space eq '0') {
1.336 albertel 8407: my @parts=split(/_/,$space);
8408: my $id=pop(@parts);
8409: my $part=join('_',@parts);
8410: if ($part eq '') { $part='0'; }
1.927 albertel 8411: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8412: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8413: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8414: }
1.395 albertel 8415: if ($recurse) { return undef; }
8416: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8417: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8418: # ---------------------------------------------------- Any other user namespace
8419: } elsif ($realm eq 'environment') {
8420: # ----------------------------------------------------------------- environment
1.620 albertel 8421: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8422: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8423: } else {
1.770 albertel 8424: if ($uname eq 'anonymous' && $udom eq '') {
8425: return '';
8426: }
1.219 albertel 8427: my %returnhash=&userenvironment($udom,$uname,
8428: $spacequalifierrest);
8429: return $returnhash{$spacequalifierrest};
8430: }
1.28 www 8431: } elsif ($realm eq 'system') {
1.48 www 8432: # ----------------------------------------------------------------- system.time
8433: if ($space eq 'time') {
8434: return time;
8435: }
1.696 albertel 8436: } elsif ($realm eq 'server') {
8437: # ----------------------------------------------------------------- system.time
8438: if ($space eq 'name') {
8439: return $ENV{'SERVER_NAME'};
8440: }
1.28 www 8441: }
1.48 www 8442: return '';
1.61 www 8443: }
8444:
1.927 albertel 8445: sub get_reply {
8446: my ($reply_value) = @_;
1.940 raeburn 8447: if (ref($reply_value) eq 'ARRAY') {
8448: if (wantarray) {
8449: return @$reply_value;
8450: }
8451: return $reply_value->[0];
8452: } else {
8453: return $reply_value;
1.927 albertel 8454: }
8455: }
8456:
1.691 raeburn 8457: sub check_group_parms {
8458: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8459: my @groupitems = ();
8460: my $resultitem;
1.927 albertel 8461: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8462: foreach my $group (@{$groups}) {
8463: foreach my $level (@levels) {
1.927 albertel 8464: my $item = $courseid.'.['.$group.'].'.$level->[0];
8465: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8466: }
8467: }
8468: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8469: $env{'course.'.$courseid.'.domain'},
8470: 'course',@groupitems);
8471: return $coursereply;
8472: }
8473:
8474: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8475: my ($courseid,@groups) = @_;
8476: @groups = sort(@groups);
1.691 raeburn 8477: return @groups;
8478: }
8479:
1.395 albertel 8480: sub packages_tab_default {
8481: my ($uri,$varname)=@_;
8482: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8483:
8484: my (@extension,@specifics,$do_default);
8485: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8486: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8487: if ($pack_type eq 'default') {
8488: $do_default=1;
8489: } elsif ($pack_type eq 'extension') {
8490: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8491: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8492: # only look at packages defaults for packages that this id is
1.738 albertel 8493: push(@specifics,[$package,$pack_type,$pack_part]);
8494: }
8495: }
8496: # first look for a package that matches the requested part id
8497: foreach my $package (@specifics) {
8498: my (undef,$pack_type,$pack_part)=@{$package};
8499: next if ($pack_part ne $part);
8500: if (defined($packagetab{"$pack_type&$name&default"})) {
8501: return $packagetab{"$pack_type&$name&default"};
8502: }
8503: }
8504: # look for any possible matching non extension_ package
8505: foreach my $package (@specifics) {
8506: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8507: if (defined($packagetab{"$pack_type&$name&default"})) {
8508: return $packagetab{"$pack_type&$name&default"};
8509: }
1.585 albertel 8510: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8511: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8512: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8513: }
8514: }
1.738 albertel 8515: # look for any posible extension_ match
8516: foreach my $package (@extension) {
8517: my ($package,$pack_type)=@{$package};
8518: if (defined($packagetab{"$pack_type&$name&default"})) {
8519: return $packagetab{"$pack_type&$name&default"};
8520: }
8521: if (defined($packagetab{$package."&$name&default"})) {
8522: return $packagetab{$package."&$name&default"};
8523: }
8524: }
8525: # look for a global default setting
8526: if ($do_default && defined($packagetab{"default&$name&default"})) {
8527: return $packagetab{"default&$name&default"};
8528: }
1.395 albertel 8529: return undef;
8530: }
8531:
1.334 albertel 8532: sub add_prefix_and_part {
8533: my ($prefix,$part)=@_;
8534: my $keyroot;
8535: if (defined($prefix) && $prefix !~ /^__/) {
8536: # prefix that has a part already
8537: $keyroot=$prefix;
8538: } elsif (defined($prefix)) {
8539: # prefix that is missing a part
8540: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8541: } else {
8542: # no prefix at all
8543: if (defined($part)) { $keyroot='_'.$part; }
8544: }
8545: return $keyroot;
8546: }
8547:
1.71 www 8548: # ---------------------------------------------------------------- Get metadata
8549:
1.599 albertel 8550: my %metaentry;
1.1070 www 8551: my %importedpartids;
1.71 www 8552: sub metadata {
1.176 www 8553: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8554: $uri=&declutter($uri);
1.288 albertel 8555: # if it is a non metadata possible uri return quickly
1.529 albertel 8556: if (($uri eq '') ||
8557: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8558: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 8559: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 8560: return undef;
8561: }
8562: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8563: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8564: return undef;
1.288 albertel 8565: }
1.73 www 8566: my $filename=$uri;
8567: $uri=~s/\.meta$//;
1.172 www 8568: #
8569: # Is the metadata already cached?
1.177 www 8570: # Look at timestamp of caching
1.172 www 8571: # Everything is cached by the main uri, libraries are never directly cached
8572: #
1.428 albertel 8573: if (!defined($liburi)) {
1.599 albertel 8574: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8575: if (defined($cached)) { return $result->{':'.$what}; }
8576: }
8577: {
1.1069 www 8578: # Imported parts would go here
1.1070 www 8579: my %importedids=();
8580: my @origfileimportpartids=();
1.1069 www 8581: my $importedparts=0;
1.172 www 8582: #
8583: # Is this a recursive call for a library?
8584: #
1.599 albertel 8585: # if (! exists($metacache{$uri})) {
8586: # $metacache{$uri}={};
8587: # }
1.924 albertel 8588: my $cachetime = 60*60;
1.171 www 8589: if ($liburi) {
8590: $liburi=&declutter($liburi);
8591: $filename=$liburi;
1.401 bowersj2 8592: } else {
1.599 albertel 8593: &devalidate_cache_new('meta',$uri);
8594: undef(%metaentry);
1.401 bowersj2 8595: }
1.140 www 8596: my %metathesekeys=();
1.73 www 8597: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8598: my $metastring;
1.924 albertel 8599: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8600: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8601: $metastring =
1.929 albertel 8602: &Apache::lonnet::ssi_body($which,
1.924 albertel 8603: ('grade_target' => 'meta'));
8604: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 8605: } elsif (($uri !~ m -^(editupload)/-) &&
8606: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 8607: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8608: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8609: $metastring=&getfile($file);
1.489 albertel 8610: }
1.208 albertel 8611: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8612: my $token;
1.140 www 8613: undef %metathesekeys;
1.71 www 8614: while ($token=$parser->get_token) {
1.339 albertel 8615: if ($token->[0] eq 'S') {
8616: if (defined($token->[2]->{'package'})) {
1.172 www 8617: #
8618: # This is a package - get package info
8619: #
1.339 albertel 8620: my $package=$token->[2]->{'package'};
8621: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8622: if (defined($token->[2]->{'id'})) {
8623: $keyroot.='_'.$token->[2]->{'id'};
8624: }
1.599 albertel 8625: if ($metaentry{':packages'}) {
8626: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8627: } else {
1.599 albertel 8628: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8629: }
1.736 albertel 8630: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8631: my $part=$keyroot;
8632: $part=~s/^\_//;
1.736 albertel 8633: if ($pack_entry=~/^\Q$package\E\&/ ||
8634: $pack_entry=~/^\Q$package\E_0\&/) {
8635: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8636: # ignore package.tab specified default values
8637: # here &package_tab_default() will fetch those
8638: if ($subp eq 'default') { next; }
1.736 albertel 8639: my $value=$packagetab{$pack_entry};
1.432 albertel 8640: my $unikey;
8641: if ($pack =~ /_0$/) {
8642: $unikey='parameter_0_'.$name;
8643: $part=0;
8644: } else {
8645: $unikey='parameter'.$keyroot.'_'.$name;
8646: }
1.339 albertel 8647: if ($subp eq 'display') {
8648: $value.=' [Part: '.$part.']';
8649: }
1.599 albertel 8650: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8651: $metathesekeys{$unikey}=1;
1.599 albertel 8652: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8653: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8654: }
1.599 albertel 8655: if (defined($metaentry{':'.$unikey.'.default'})) {
8656: $metaentry{':'.$unikey}=
8657: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8658: }
1.339 albertel 8659: }
8660: }
8661: } else {
1.172 www 8662: #
8663: # This is not a package - some other kind of start tag
1.339 albertel 8664: #
8665: my $entry=$token->[1];
1.1068 www 8666: my $unikey='';
1.175 www 8667:
1.339 albertel 8668: if ($entry eq 'import') {
1.175 www 8669: #
8670: # Importing a library here
1.339 albertel 8671: #
1.1067 www 8672: my $location=$parser->get_text('/import');
8673: my $dir=$filename;
8674: $dir=~s|[^/]*$||;
8675: $location=&filelocation($dir,$location);
1.1069 www 8676:
1.1068 www 8677: my $importmode=$token->[2]->{'importmode'};
8678: if ($importmode eq 'problem') {
1.1069 www 8679: # Import as problem/response
1.1068 www 8680: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8681: } elsif ($importmode eq 'part') {
8682: # Import as part(s)
1.1069 www 8683: $importedparts=1;
8684: # We need to get the original file and the imported file to get the part order correct
8685: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8686: # Load and inspect original file
1.1070 www 8687: if ($#origfileimportpartids<0) {
8688: undef(%importedpartids);
8689: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8690: my $origfile=&getfile($origfilelocation);
8691: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8692: }
8693:
1.1069 www 8694: # Load and inspect imported file
8695: my $impfile=&getfile($location);
8696: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8697: if ($#impfilepartids>=0) {
8698: # This problem had parts
1.1070 www 8699: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8700: } else {
8701: # Importing by turning a single problem into a problem part
8702: # It gets the import-tags ID as part-ID
8703: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8704: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8705: }
1.1068 www 8706: } else {
8707: # Normal import
8708: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8709: if (defined($token->[2]->{'id'})) {
8710: $unikey.='_'.$token->[2]->{'id'};
8711: }
1.1067 www 8712: }
8713:
1.339 albertel 8714: if ($depthcount<20) {
1.736 albertel 8715: my $metadata =
8716: &metadata($uri,'keys', $location,$unikey,
8717: $depthcount+1);
8718: foreach my $meta (split(',',$metadata)) {
8719: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8720: $metathesekeys{$meta}=1;
1.339 albertel 8721: }
1.1068 www 8722:
8723: }
1.1067 www 8724: } else {
8725: #
8726: # Not importing, some other kind of non-package, non-library start tag
8727: #
8728: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8729: if (defined($token->[2]->{'id'})) {
8730: $unikey.='_'.$token->[2]->{'id'};
8731: }
1.339 albertel 8732: if (defined($token->[2]->{'name'})) {
8733: $unikey.='_'.$token->[2]->{'name'};
8734: }
8735: $metathesekeys{$unikey}=1;
1.736 albertel 8736: foreach my $param (@{$token->[3]}) {
8737: $metaentry{':'.$unikey.'.'.$param} =
8738: $token->[2]->{$param};
1.339 albertel 8739: }
8740: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8741: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8742: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8743: # only ws inside the tag, and not in default, so use default
8744: # as value
1.599 albertel 8745: $metaentry{':'.$unikey}=$default;
1.908 albertel 8746: } elsif ( $internaltext =~ /\S/ ) {
8747: # something interesting inside the tag
8748: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8749: } else {
1.908 albertel 8750: # no interesting values, don't set a default
1.339 albertel 8751: }
1.172 www 8752: # end of not-a-package not-a-library import
1.339 albertel 8753: }
1.172 www 8754: # end of not-a-package start tag
1.339 albertel 8755: }
1.172 www 8756: # the next is the end of "start tag"
1.339 albertel 8757: }
8758: }
1.483 albertel 8759: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8760: $extension = lc($extension);
8761: if ($extension eq 'htm') { $extension='html'; }
8762:
1.737 albertel 8763: foreach my $key (keys(%packagetab)) {
1.483 albertel 8764: #no specific packages #how's our extension
8765: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8766: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8767: \%metathesekeys);
8768: }
1.883 albertel 8769:
8770: if (!exists($metaentry{':packages'})
8771: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8772: foreach my $key (keys(%packagetab)) {
1.483 albertel 8773: #no specific packages well let's get default then
8774: if ($key!~/^default&/) { next; }
1.488 albertel 8775: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8776: \%metathesekeys);
8777: }
8778: }
1.338 www 8779: # are there custom rights to evaluate
1.599 albertel 8780: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8781:
1.338 www 8782: #
8783: # Importing a rights file here
1.339 albertel 8784: #
8785: unless ($depthcount) {
1.599 albertel 8786: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8787: my $dir=$filename;
8788: $dir=~s|[^/]*$||;
8789: $location=&filelocation($dir,$location);
1.736 albertel 8790: my $rights_metadata =
8791: &metadata($uri,'keys',$location,'_rights',
8792: $depthcount+1);
8793: foreach my $rights (split(',',$rights_metadata)) {
8794: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8795: $metathesekeys{$rights}=1;
1.339 albertel 8796: }
8797: }
8798: }
1.737 albertel 8799: # uniqifiy package listing
8800: my %seen;
8801: my @uniq_packages =
8802: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8803: $metaentry{':packages'} = join(',',@uniq_packages);
8804:
1.1070 www 8805: if ($importedparts) {
8806: # We had imported parts and need to rebuild partorder
8807: $metaentry{':partorder'}='';
8808: $metathesekeys{'partorder'}=1;
8809: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8810: if ($origfileimportpartids[$index] eq 'part') {
8811: # original part, part of the problem
8812: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8813: } else {
8814: # we have imported parts at this position
8815: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8816: }
8817: }
8818: $metaentry{':partorder'}=~s/^\,//;
8819: }
8820:
1.737 albertel 8821: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8822: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8823: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8824: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8825: # this is the end of "was not already recently cached
1.71 www 8826: }
1.599 albertel 8827: return $metaentry{':'.$what};
1.261 albertel 8828: }
8829:
1.488 albertel 8830: sub metadata_create_package_def {
1.483 albertel 8831: my ($uri,$key,$package,$metathesekeys)=@_;
8832: my ($pack,$name,$subp)=split(/\&/,$key);
8833: if ($subp eq 'default') { next; }
8834:
1.599 albertel 8835: if (defined($metaentry{':packages'})) {
8836: $metaentry{':packages'}.=','.$package;
1.483 albertel 8837: } else {
1.599 albertel 8838: $metaentry{':packages'}=$package;
1.483 albertel 8839: }
8840: my $value=$packagetab{$key};
8841: my $unikey;
8842: $unikey='parameter_0_'.$name;
1.599 albertel 8843: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8844: $$metathesekeys{$unikey}=1;
1.599 albertel 8845: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8846: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8847: }
1.599 albertel 8848: if (defined($metaentry{':'.$unikey.'.default'})) {
8849: $metaentry{':'.$unikey}=
8850: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8851: }
8852: }
8853:
1.261 albertel 8854: sub metadata_generate_part0 {
8855: my ($metadata,$metacache,$uri) = @_;
8856: my %allnames;
1.737 albertel 8857: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8858: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8859: my $part=$$metacache{':'.$metakey.'.part'};
8860: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8861: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8862: $allnames{$name}=$part;
8863: }
8864: }
8865: }
8866: foreach my $name (keys(%allnames)) {
8867: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8868: my $key=":parameter_0_$name";
1.261 albertel 8869: $$metacache{"$key.part"}='0';
8870: $$metacache{"$key.name"}=$name;
1.428 albertel 8871: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8872: $allnames{$name}.'_'.$name.
8873: '.type'};
1.428 albertel 8874: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8875: '.display'};
1.644 www 8876: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8877: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8878: $$metacache{"$key.display"}=$olddis;
8879: }
1.71 www 8880: }
8881:
1.764 albertel 8882: # ------------------------------------------------------ Devalidate title cache
8883:
8884: sub devalidate_title_cache {
8885: my ($url)=@_;
8886: if (!$env{'request.course.id'}) { return; }
8887: my $symb=&symbread($url);
8888: if (!$symb) { return; }
8889: my $key=$env{'request.course.id'}."\0".$symb;
8890: &devalidate_cache_new('title',$key);
8891: }
8892:
1.1014 droeschl 8893: # ------------------------------------------------- Get the title of a course
8894:
8895: sub current_course_title {
8896: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8897: }
1.301 www 8898: # ------------------------------------------------- Get the title of a resource
8899:
8900: sub gettitle {
8901: my $urlsymb=shift;
8902: my $symb=&symbread($urlsymb);
1.534 albertel 8903: if ($symb) {
1.620 albertel 8904: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8905: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8906: if (defined($cached)) {
8907: return $result;
8908: }
1.534 albertel 8909: my ($map,$resid,$url)=&decode_symb($symb);
8910: my $title='';
1.907 albertel 8911: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8912: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8913: } else {
8914: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8915: &GDBM_READER(),0640)) {
8916: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8917: $title=$bighash{'title_'.$mapid.'.'.$resid};
8918: untie(%bighash);
8919: }
1.534 albertel 8920: }
8921: $title=~s/\&colon\;/\:/gs;
8922: if ($title) {
1.599 albertel 8923: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8924: }
8925: $urlsymb=$url;
8926: }
8927: my $title=&metadata($urlsymb,'title');
8928: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8929: return $title;
1.301 www 8930: }
1.613 albertel 8931:
1.614 albertel 8932: sub get_slot {
8933: my ($which,$cnum,$cdom)=@_;
8934: if (!$cnum || !$cdom) {
1.790 albertel 8935: (undef,my $courseid)=&whichuser();
1.620 albertel 8936: $cdom=$env{'course.'.$courseid.'.domain'};
8937: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8938: }
1.703 albertel 8939: my $key=join("\0",'slots',$cdom,$cnum,$which);
8940: my %slotinfo;
8941: if (exists($remembered{$key})) {
8942: $slotinfo{$which} = $remembered{$key};
8943: } else {
8944: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8945: &Apache::lonhomework::showhash(%slotinfo);
8946: my ($tmp)=keys(%slotinfo);
8947: if ($tmp=~/^error:/) { return (); }
8948: $remembered{$key} = $slotinfo{$which};
8949: }
1.616 albertel 8950: if (ref($slotinfo{$which}) eq 'HASH') {
8951: return %{$slotinfo{$which}};
8952: }
8953: return $slotinfo{$which};
1.614 albertel 8954: }
1.31 www 8955: # ------------------------------------------------- Update symbolic store links
8956:
8957: sub symblist {
8958: my ($mapname,%newhash)=@_;
1.438 www 8959: $mapname=&deversion(&declutter($mapname));
1.31 www 8960: my %hash;
1.620 albertel 8961: if (($env{'request.course.fn'}) && (%newhash)) {
8962: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8963: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8964: foreach my $url (keys(%newhash)) {
1.711 albertel 8965: next if ($url eq 'last_known'
8966: && $env{'form.no_update_last_known'});
8967: $hash{declutter($url)}=&encode_symb($mapname,
8968: $newhash{$url}->[1],
8969: $newhash{$url}->[0]);
1.191 harris41 8970: }
1.31 www 8971: if (untie(%hash)) {
8972: return 'ok';
8973: }
8974: }
8975: }
8976: return 'error';
1.212 www 8977: }
8978:
8979: # --------------------------------------------------------------- Verify a symb
8980:
8981: sub symbverify {
1.510 www 8982: my ($symb,$thisurl)=@_;
8983: my $thisfn=$thisurl;
1.439 www 8984: $thisfn=&declutter($thisfn);
1.215 www 8985: # direct jump to resource in page or to a sequence - will construct own symbs
8986: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8987: # check URL part
1.409 www 8988: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8989:
1.431 www 8990: unless ($url eq $thisfn) { return 0; }
1.213 www 8991:
1.216 www 8992: $symb=&symbclean($symb);
1.510 www 8993: $thisurl=&deversion($thisurl);
1.439 www 8994: $thisfn=&deversion($thisfn);
1.213 www 8995:
8996: my %bighash;
8997: my $okay=0;
1.431 www 8998:
1.620 albertel 8999: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9000: &GDBM_READER(),0640)) {
1.1032 raeburn 9001: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9002: $thisurl =~ s/\?.+$//;
9003: }
1.510 www 9004: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9005: unless ($ids) {
9006: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9007: $ids=$bighash{$idkey};
1.216 www 9008: }
9009: if ($ids) {
9010: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9011: foreach my $id (split(/\,/,$ids)) {
9012: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9013: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9014: $symb =~ s/\?.+$//;
9015: }
1.216 www 9016: if (
9017: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9018: eq $symb) {
1.620 albertel 9019: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9020: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9021: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9022: $okay=1;
9023: }
9024: }
1.216 www 9025: }
9026: }
1.213 www 9027: untie(%bighash);
9028: }
9029: return $okay;
1.31 www 9030: }
9031:
1.210 www 9032: # --------------------------------------------------------------- Clean-up symb
9033:
9034: sub symbclean {
9035: my $symb=shift;
1.568 albertel 9036: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9037: # remove version from map
9038: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9039:
1.210 www 9040: # remove version from URL
9041: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9042:
1.507 www 9043: # remove wrapper
9044:
1.510 www 9045: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9046: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9047: return $symb;
1.409 www 9048: }
9049:
9050: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9051:
9052: sub encode_symb {
9053: my ($map,$resid,$url)=@_;
9054: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9055: }
1.409 www 9056:
9057: sub decode_symb {
1.568 albertel 9058: my $symb=shift;
9059: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9060: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9061: return (&fixversion($map),$resid,&fixversion($url));
9062: }
9063:
9064: sub fixversion {
9065: my $fn=shift;
1.609 banghart 9066: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9067: my %bighash;
9068: my $uri=&clutter($fn);
1.620 albertel 9069: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9070: # is this cached?
1.599 albertel 9071: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9072: if (defined($cached)) { return $result; }
9073: # unfortunately not cached, or expired
1.620 albertel 9074: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9075: &GDBM_READER(),0640)) {
9076: if ($bighash{'version_'.$uri}) {
9077: my $version=$bighash{'version_'.$uri};
1.444 www 9078: unless (($version eq 'mostrecent') ||
9079: ($version==&getversion($uri))) {
1.440 www 9080: $uri=~s/\.(\w+)$/\.$version\.$1/;
9081: }
9082: }
9083: untie %bighash;
1.413 www 9084: }
1.599 albertel 9085: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9086: }
9087:
9088: sub deversion {
9089: my $url=shift;
9090: $url=~s/\.\d+\.(\w+)$/\.$1/;
9091: return $url;
1.210 www 9092: }
9093:
1.31 www 9094: # ------------------------------------------------------ Return symb list entry
9095:
9096: sub symbread {
1.249 www 9097: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9098: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9099: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9100: # no filename provided? try from environment
1.44 www 9101: unless ($thisfn) {
1.620 albertel 9102: if ($env{'request.symb'}) {
9103: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9104: }
1.620 albertel 9105: $thisfn=$env{'request.filename'};
1.44 www 9106: }
1.569 albertel 9107: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9108: # is that filename actually a symb? Verify, clean, and return
9109: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9110: if (&symbverify($thisfn,$1)) {
1.620 albertel 9111: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9112: }
1.242 www 9113: }
1.44 www 9114: $thisfn=declutter($thisfn);
1.31 www 9115: my %hash;
1.37 www 9116: my %bighash;
9117: my $syval='';
1.620 albertel 9118: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9119: my $targetfn = $thisfn;
1.609 banghart 9120: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9121: $targetfn = 'adm/wrapper/'.$thisfn;
9122: }
1.687 albertel 9123: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9124: $targetfn=$1;
9125: }
1.620 albertel 9126: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9127: &GDBM_READER(),0640)) {
1.481 raeburn 9128: $syval=$hash{$targetfn};
1.37 www 9129: untie(%hash);
9130: }
9131: # ---------------------------------------------------------- There was an entry
9132: if ($syval) {
1.601 albertel 9133: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9134: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9135: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9136: #return $env{$cache_str}='';
1.601 albertel 9137: #}
9138: #$syval.=$1;
9139: #}
1.37 www 9140: } else {
9141: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9142: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9143: &GDBM_READER(),0640)) {
1.37 www 9144: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9145: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9146: unless ($ids) {
9147: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9148: }
9149: unless ($ids) {
9150: # alias?
9151: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9152: }
1.37 www 9153: if ($ids) {
9154: # ------------------------------------------------------------------- Has ID(s)
9155: my @possibilities=split(/\,/,$ids);
1.39 www 9156: if ($#possibilities==0) {
9157: # ----------------------------------------------- There is only one possibility
1.37 www 9158: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9159: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9160: $resid,$thisfn);
1.249 www 9161: } elsif (!$donotrecurse) {
1.39 www 9162: # ------------------------------------------ There is more than one possibility
9163: my $realpossible=0;
1.800 albertel 9164: foreach my $id (@possibilities) {
9165: my $file=$bighash{'src_'.$id};
1.39 www 9166: if (&allowed('bre',$file)) {
1.800 albertel 9167: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9168: if ($bighash{'map_type_'.$mapid} ne 'page') {
9169: $realpossible++;
1.626 albertel 9170: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9171: $resid,$thisfn);
1.39 www 9172: }
9173: }
1.191 harris41 9174: }
1.39 www 9175: if ($realpossible!=1) { $syval=''; }
1.249 www 9176: } else {
9177: $syval='';
1.37 www 9178: }
9179: }
9180: untie(%bighash)
1.481 raeburn 9181: }
1.31 www 9182: }
1.62 www 9183: if ($syval) {
1.620 albertel 9184: return $env{$cache_str}=$syval;
1.62 www 9185: }
1.31 www 9186: }
1.949 raeburn 9187: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9188: return $env{$cache_str}='';
1.31 www 9189: }
9190:
9191: # ---------------------------------------------------------- Return random seed
9192:
1.32 www 9193: sub numval {
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;
1.564 albertel 9202: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9203: return int($txt);
1.368 albertel 9204: }
9205:
1.484 albertel 9206: sub numval2 {
9207: my $txt=shift;
9208: $txt=~tr/A-J/0-9/;
9209: $txt=~tr/a-j/0-9/;
9210: $txt=~tr/K-T/0-9/;
9211: $txt=~tr/k-t/0-9/;
9212: $txt=~tr/U-Z/0-5/;
9213: $txt=~tr/u-z/0-5/;
9214: $txt=~s/\D//g;
9215: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9216: my $total;
9217: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9218: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9219: return int($total);
9220: }
9221:
1.575 albertel 9222: sub numval3 {
9223: use integer;
9224: my $txt=shift;
9225: $txt=~tr/A-J/0-9/;
9226: $txt=~tr/a-j/0-9/;
9227: $txt=~tr/K-T/0-9/;
9228: $txt=~tr/k-t/0-9/;
9229: $txt=~tr/U-Z/0-5/;
9230: $txt=~tr/u-z/0-5/;
9231: $txt=~s/\D//g;
9232: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9233: my $total;
9234: foreach my $val (@txts) { $total+=$val; }
9235: if ($_64bit) { $total=(($total<<32)>>32); }
9236: return $total;
9237: }
9238:
1.675 albertel 9239: sub digest {
9240: my ($data)=@_;
9241: my $digest=&Digest::MD5::md5($data);
9242: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9243: my ($e,$f);
9244: {
9245: use integer;
9246: $e=($a+$b);
9247: $f=($c+$d);
9248: if ($_64bit) {
9249: $e=(($e<<32)>>32);
9250: $f=(($f<<32)>>32);
9251: }
9252: }
9253: if (wantarray) {
9254: return ($e,$f);
9255: } else {
9256: my $g;
9257: {
9258: use integer;
9259: $g=($e+$f);
9260: if ($_64bit) {
9261: $g=(($g<<32)>>32);
9262: }
9263: }
9264: return $g;
9265: }
9266: }
9267:
1.368 albertel 9268: sub latest_rnd_algorithm_id {
1.675 albertel 9269: return '64bit5';
1.366 albertel 9270: }
1.32 www 9271:
1.503 albertel 9272: sub get_rand_alg {
9273: my ($courseid)=@_;
1.790 albertel 9274: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9275: if ($courseid) {
1.620 albertel 9276: return $env{"course.$courseid.rndseed"};
1.503 albertel 9277: }
9278: return &latest_rnd_algorithm_id();
9279: }
9280:
1.562 albertel 9281: sub validCODE {
9282: my ($CODE)=@_;
9283: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9284: return 0;
9285: }
9286:
1.491 albertel 9287: sub getCODE {
1.620 albertel 9288: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9289: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9290: defined($Apache::lonhomework::parsing_a_task) ) &&
9291: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9292: return $Apache::lonhomework::history{'resource.CODE'};
9293: }
9294: return undef;
9295: }
9296:
1.31 www 9297: sub rndseed {
1.155 albertel 9298: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9299: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9300: if (!defined($symb)) {
1.366 albertel 9301: unless ($symb=$wsymb) { return time; }
9302: }
9303: if (!$courseid) { $courseid=$wcourseid; }
9304: if (!$domain) { $domain=$wdomain; }
9305: if (!$username) { $username=$wusername }
1.503 albertel 9306: my $which=&get_rand_alg();
1.1110 www 9307:
1.491 albertel 9308: if (defined(&getCODE())) {
1.675 albertel 9309: if ($which eq '64bit5') {
9310: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9311: } elsif ($which eq '64bit4') {
1.575 albertel 9312: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9313: } else {
9314: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9315: }
1.675 albertel 9316: } elsif ($which eq '64bit5') {
9317: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9318: } elsif ($which eq '64bit4') {
9319: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9320: } elsif ($which eq '64bit3') {
9321: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9322: } elsif ($which eq '64bit2') {
9323: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9324: } elsif ($which eq '64bit') {
9325: return &rndseed_64bit($symb,$courseid,$domain,$username);
9326: }
9327: return &rndseed_32bit($symb,$courseid,$domain,$username);
9328: }
9329:
9330: sub rndseed_32bit {
9331: my ($symb,$courseid,$domain,$username)=@_;
9332: {
9333: use integer;
9334: my $symbchck=unpack("%32C*",$symb) << 27;
9335: my $symbseed=numval($symb) << 22;
9336: my $namechck=unpack("%32C*",$username) << 17;
9337: my $nameseed=numval($username) << 12;
9338: my $domainseed=unpack("%32C*",$domain) << 7;
9339: my $courseseed=unpack("%32C*",$courseid);
9340: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9341: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9342: #&logthis("rndseed :$num:$symb");
1.564 albertel 9343: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9344: return $num;
9345: }
9346: }
9347:
9348: sub rndseed_64bit {
9349: my ($symb,$courseid,$domain,$username)=@_;
9350: {
9351: use integer;
9352: my $symbchck=unpack("%32S*",$symb) << 21;
9353: my $symbseed=numval($symb) << 10;
9354: my $namechck=unpack("%32S*",$username);
9355:
9356: my $nameseed=numval($username) << 21;
9357: my $domainseed=unpack("%32S*",$domain) << 10;
9358: my $courseseed=unpack("%32S*",$courseid);
9359:
9360: my $num1=$symbchck+$symbseed+$namechck;
9361: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9362: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9363: #&logthis("rndseed :$num:$symb");
1.564 albertel 9364: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9365: return "$num1,$num2";
1.155 albertel 9366: }
1.366 albertel 9367: }
9368:
1.443 albertel 9369: sub rndseed_64bit2 {
9370: my ($symb,$courseid,$domain,$username)=@_;
9371: {
9372: use integer;
9373: # strings need to be an even # of cahracters long, it it is odd the
9374: # last characters gets thrown away
9375: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9376: my $symbseed=numval($symb) << 10;
9377: my $namechck=unpack("%32S*",$username.' ');
9378:
9379: my $nameseed=numval($username) << 21;
1.501 albertel 9380: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9381: my $courseseed=unpack("%32S*",$courseid.' ');
9382:
9383: my $num1=$symbchck+$symbseed+$namechck;
9384: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9385: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9386: #&logthis("rndseed :$num:$symb");
1.803 albertel 9387: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9388: return "$num1,$num2";
9389: }
9390: }
9391:
9392: sub rndseed_64bit3 {
9393: my ($symb,$courseid,$domain,$username)=@_;
9394: {
9395: use integer;
9396: # strings need to be an even # of cahracters long, it it is odd the
9397: # last characters gets thrown away
9398: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9399: my $symbseed=numval2($symb) << 10;
9400: my $namechck=unpack("%32S*",$username.' ');
9401:
9402: my $nameseed=numval2($username) << 21;
1.443 albertel 9403: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9404: my $courseseed=unpack("%32S*",$courseid.' ');
9405:
9406: my $num1=$symbchck+$symbseed+$namechck;
9407: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9408: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9409: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9410: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9411:
1.503 albertel 9412: return "$num1:$num2";
1.443 albertel 9413: }
9414: }
9415:
1.575 albertel 9416: sub rndseed_64bit4 {
9417: my ($symb,$courseid,$domain,$username)=@_;
9418: {
9419: use integer;
9420: # strings need to be an even # of cahracters long, it it is odd the
9421: # last characters gets thrown away
9422: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9423: my $symbseed=numval3($symb) << 10;
9424: my $namechck=unpack("%32S*",$username.' ');
9425:
9426: my $nameseed=numval3($username) << 21;
9427: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9428: my $courseseed=unpack("%32S*",$courseid.' ');
9429:
9430: my $num1=$symbchck+$symbseed+$namechck;
9431: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9432: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9433: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9434: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9435:
1.575 albertel 9436: return "$num1:$num2";
9437: }
9438: }
9439:
1.675 albertel 9440: sub rndseed_64bit5 {
9441: my ($symb,$courseid,$domain,$username)=@_;
9442: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9443: return "$num1:$num2";
9444: }
9445:
1.366 albertel 9446: sub rndseed_CODE_64bit {
9447: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9448: {
1.366 albertel 9449: use integer;
1.443 albertel 9450: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9451: my $symbseed=numval2($symb);
1.491 albertel 9452: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9453: my $CODEseed=numval(&getCODE());
1.443 albertel 9454: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9455: my $num1=$symbseed+$CODEchck;
9456: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9457: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9458: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9459: if ($_64bit) { $num1=(($num1<<32)>>32); }
9460: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9461: return "$num1:$num2";
1.366 albertel 9462: }
9463: }
9464:
1.575 albertel 9465: sub rndseed_CODE_64bit4 {
9466: my ($symb,$courseid,$domain,$username)=@_;
9467: {
9468: use integer;
9469: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9470: my $symbseed=numval3($symb);
9471: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9472: my $CODEseed=numval3(&getCODE());
9473: my $courseseed=unpack("%32S*",$courseid.' ');
9474: my $num1=$symbseed+$CODEchck;
9475: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9476: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9477: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9478: if ($_64bit) { $num1=(($num1<<32)>>32); }
9479: if ($_64bit) { $num2=(($num2<<32)>>32); }
9480: return "$num1:$num2";
9481: }
9482: }
9483:
1.675 albertel 9484: sub rndseed_CODE_64bit5 {
9485: my ($symb,$courseid,$domain,$username)=@_;
9486: my $code = &getCODE();
9487: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9488: return "$num1:$num2";
9489: }
9490:
1.366 albertel 9491: sub setup_random_from_rndseed {
9492: my ($rndseed)=@_;
1.503 albertel 9493: if ($rndseed =~/([,:])/) {
9494: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9495: &Math::Random::random_set_seed(abs($num1),abs($num2));
9496: } else {
9497: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9498: }
1.36 albertel 9499: }
9500:
1.474 albertel 9501: sub latest_receipt_algorithm_id {
1.835 albertel 9502: return 'receipt3';
1.474 albertel 9503: }
9504:
1.480 www 9505: sub recunique {
9506: my $fucourseid=shift;
9507: my $unique;
1.835 albertel 9508: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9509: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9510: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9511: } else {
9512: $unique=$perlvar{'lonReceipt'};
9513: }
9514: return unpack("%32C*",$unique);
9515: }
9516:
9517: sub recprefix {
9518: my $fucourseid=shift;
9519: my $prefix;
1.835 albertel 9520: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9521: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9522: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9523: } else {
9524: $prefix=$perlvar{'lonHostID'};
9525: }
9526: return unpack("%32C*",$prefix);
9527: }
9528:
1.76 www 9529: sub ireceipt {
1.474 albertel 9530: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9531:
9532: my $return =&recprefix($fucourseid).'-';
9533:
9534: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9535: $env{'request.state'} eq 'construct') {
9536: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9537: return $return;
9538: }
9539:
1.76 www 9540: my $cuname=unpack("%32C*",$funame);
9541: my $cudom=unpack("%32C*",$fudom);
9542: my $cucourseid=unpack("%32C*",$fucourseid);
9543: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9544: my $cunique=&recunique($fucourseid);
1.474 albertel 9545: my $cpart=unpack("%32S*",$part);
1.835 albertel 9546: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9547:
1.790 albertel 9548: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9549:
9550: $return.= ($cunique%$cuname+
9551: $cunique%$cudom+
9552: $cusymb%$cuname+
9553: $cusymb%$cudom+
9554: $cucourseid%$cuname+
9555: $cucourseid%$cudom+
9556: $cpart%$cuname+
9557: $cpart%$cudom);
9558: } else {
9559: $return.= ($cunique%$cuname+
9560: $cunique%$cudom+
9561: $cusymb%$cuname+
9562: $cusymb%$cudom+
9563: $cucourseid%$cuname+
9564: $cucourseid%$cudom);
9565: }
9566: return $return;
1.76 www 9567: }
9568:
9569: sub receipt {
1.474 albertel 9570: my ($part)=@_;
1.790 albertel 9571: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9572: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9573: }
1.260 ng 9574:
1.790 albertel 9575: sub whichuser {
9576: my ($passedsymb)=@_;
9577: my ($symb,$courseid,$domain,$name,$publicuser);
9578: if (defined($env{'form.grade_symb'})) {
9579: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9580: my $allowed=&allowed('vgr',$tmp_courseid);
9581: if (!$allowed &&
9582: exists($env{'request.course.sec'}) &&
9583: $env{'request.course.sec'} !~ /^\s*$/) {
9584: $allowed=&allowed('vgr',$tmp_courseid.
9585: '/'.$env{'request.course.sec'});
9586: }
9587: if ($allowed) {
9588: ($symb)=&get_env_multiple('form.grade_symb');
9589: $courseid=$tmp_courseid;
9590: ($domain)=&get_env_multiple('form.grade_domain');
9591: ($name)=&get_env_multiple('form.grade_username');
9592: return ($symb,$courseid,$domain,$name,$publicuser);
9593: }
9594: }
9595: if (!$passedsymb) {
9596: $symb=&symbread();
9597: } else {
9598: $symb=$passedsymb;
9599: }
9600: $courseid=$env{'request.course.id'};
9601: $domain=$env{'user.domain'};
9602: $name=$env{'user.name'};
9603: if ($name eq 'public' && $domain eq 'public') {
9604: if (!defined($env{'form.username'})) {
9605: $env{'form.username'}.=time.rand(10000000);
9606: }
9607: $name.=$env{'form.username'};
9608: }
9609: return ($symb,$courseid,$domain,$name,$publicuser);
9610:
9611: }
9612:
1.36 albertel 9613: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9614: # returns either the contents of the file or
9615: # -1 if the file doesn't exist
1.481 raeburn 9616: #
9617: # if the target is a file that was uploaded via DOCS,
9618: # a check will be made to see if a current copy exists on the local server,
9619: # if it does this will be served, otherwise a copy will be retrieved from
9620: # the home server for the course and stored in /home/httpd/html/userfiles on
9621: # the local server.
1.472 albertel 9622:
1.36 albertel 9623: sub getfile {
1.538 albertel 9624: my ($file) = @_;
1.609 banghart 9625: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9626: &repcopy($file);
9627: return &readfile($file);
9628: }
9629:
9630: sub repcopy_userfile {
9631: my ($file)=@_;
1.609 banghart 9632: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9633: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9634: my ($cdom,$cnum,$filename) =
1.811 albertel 9635: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9636: my $uri="/uploaded/$cdom/$cnum/$filename";
9637: if (-e "$file") {
1.828 www 9638: # we already have a local copy, check it out
1.538 albertel 9639: my @fileinfo = stat($file);
1.828 www 9640: my $rtncode;
9641: my $info;
1.538 albertel 9642: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9643: if ($lwpresp ne 'ok') {
1.828 www 9644: # there is no such file anymore, even though we had a local copy
1.482 albertel 9645: if ($rtncode eq '404') {
1.538 albertel 9646: unlink($file);
1.482 albertel 9647: }
9648: return -1;
9649: }
9650: if ($info < $fileinfo[9]) {
1.828 www 9651: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9652: return 'ok';
1.828 www 9653: } else {
9654: # the file is outdated, get rid of it
9655: unlink($file);
1.482 albertel 9656: }
1.828 www 9657: }
9658: # one way or the other, at this point, we don't have the file
9659: # construct the correct path for the file
9660: my @parts = ($cdom,$cnum);
9661: if ($filename =~ m|^(.+)/[^/]+$|) {
9662: push @parts, split(/\//,$1);
9663: }
9664: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9665: foreach my $part (@parts) {
9666: $path .= '/'.$part;
9667: if (!-e $path) {
9668: mkdir($path,0770);
1.482 albertel 9669: }
9670: }
1.828 www 9671: # now the path exists for sure
9672: # get a user agent
9673: my $ua=new LWP::UserAgent;
9674: my $transferfile=$file.'.in.transfer';
9675: # FIXME: this should flock
9676: if (-e $transferfile) { return 'ok'; }
9677: my $request;
9678: $uri=~s/^\///;
1.980 raeburn 9679: my $homeserver = &homeserver($cnum,$cdom);
9680: my $protocol = $protocol{$homeserver};
9681: $protocol = 'http' if ($protocol ne 'https');
9682: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9683: my $response=$ua->request($request,$transferfile);
9684: # did it work?
9685: if ($response->is_error()) {
9686: unlink($transferfile);
9687: &logthis("Userfile repcopy failed for $uri");
9688: return -1;
9689: }
9690: # worked, rename the transfer file
9691: rename($transferfile,$file);
1.607 raeburn 9692: return 'ok';
1.481 raeburn 9693: }
9694:
1.517 albertel 9695: sub tokenwrapper {
9696: my $uri=shift;
1.980 raeburn 9697: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9698: $uri=~s|^/||;
1.620 albertel 9699: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9700: my $token=$1;
1.552 albertel 9701: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9702: if ($udom && $uname && $file) {
9703: $file=~s|(\?\.*)*$||;
1.949 raeburn 9704: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9705: my $homeserver = &homeserver($uname,$udom);
9706: my $protocol = $protocol{$homeserver};
9707: $protocol = 'http' if ($protocol ne 'https');
9708: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9709: (($uri=~/\?/)?'&':'?').'token='.$token.
9710: '&tokenissued='.$perlvar{'lonHostID'};
9711: } else {
9712: return '/adm/notfound.html';
9713: }
9714: }
9715:
1.828 www 9716: # call with reqtype HEAD: get last modification time
9717: # call with reqtype GET: get the file contents
9718: # Do not call this with reqtype GET for large files! It loads everything into memory
9719: #
1.481 raeburn 9720: sub getuploaded {
9721: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9722: $uri=~s/^\///;
1.980 raeburn 9723: my $homeserver = &homeserver($cnum,$cdom);
9724: my $protocol = $protocol{$homeserver};
9725: $protocol = 'http' if ($protocol ne 'https');
9726: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9727: my $ua=new LWP::UserAgent;
9728: my $request=new HTTP::Request($reqtype,$uri);
9729: my $response=$ua->request($request);
9730: $$rtncode = $response->code;
1.482 albertel 9731: if (! $response->is_success()) {
9732: return 'failed';
9733: }
9734: if ($reqtype eq 'HEAD') {
1.486 www 9735: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9736: } elsif ($reqtype eq 'GET') {
9737: $$info = $response->content;
1.472 albertel 9738: }
1.482 albertel 9739: return 'ok';
1.36 albertel 9740: }
9741:
1.481 raeburn 9742: sub readfile {
9743: my $file = shift;
9744: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9745: my $fh;
9746: open($fh,"<$file");
9747: my $a='';
1.800 albertel 9748: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9749: return $a;
9750: }
9751:
1.36 albertel 9752: sub filelocation {
1.590 banghart 9753: my ($dir,$file) = @_;
9754: my $location;
9755: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9756:
9757: if ($file =~ m-^/adm/-) {
9758: $file=~s-^/adm/wrapper/-/-;
9759: $file=~s-^/adm/coursedocs/showdoc/-/-;
9760: }
1.882 albertel 9761:
1.590 banghart 9762: if ($file=~m:^/~:) { # is a contruction space reference
9763: $location = $file;
9764: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9765: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9766: # is a correct contruction space reference
9767: $location = $file;
1.956 raeburn 9768: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9769: $location = $file;
1.609 banghart 9770: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9771: my ($udom,$uname,$filename)=
1.811 albertel 9772: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9773: my $home=&homeserver($uname,$udom);
9774: my $is_me=0;
9775: my @ids=¤t_machine_ids();
9776: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9777: if ($is_me) {
1.955 raeburn 9778: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9779: } else {
9780: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9781: $udom.'/'.$uname.'/'.$filename;
9782: }
1.882 albertel 9783: } elsif ($file =~ m-^/adm/-) {
9784: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9785: } else {
9786: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9787: $file=~s:^/res/:/:;
9788: if ( !( $file =~ m:^/:) ) {
9789: $location = $dir. '/'.$file;
9790: } else {
9791: $location = '/home/httpd/html/res'.$file;
9792: }
1.59 albertel 9793: }
1.590 banghart 9794: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9795: while ($location=~m{/\.\./}) {
9796: if ($location =~ m{/[^/]+/\.\./}) {
9797: $location=~ s{/[^/]+/\.\./}{/}g;
9798: } else {
9799: $location=~ s{/\.\./}{/}g;
9800: }
9801: } #remove dir/..
1.590 banghart 9802: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9803: return $location;
1.46 www 9804: }
1.36 albertel 9805:
1.46 www 9806: sub hreflocation {
9807: my ($dir,$file)=@_;
1.980 raeburn 9808: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9809: $file=filelocation($dir,$file);
1.700 albertel 9810: } elsif ($file=~m-^/adm/-) {
9811: $file=~s-^/adm/wrapper/-/-;
9812: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9813: }
9814: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9815: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9816: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9817: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9818: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9819: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9820: -/uploaded/$1/$2/-x;
1.46 www 9821: }
1.913 albertel 9822: if ($file=~ m{^/userfiles/}) {
9823: $file =~ s{^/userfiles/}{/uploaded/};
9824: }
1.462 albertel 9825: return $file;
1.465 albertel 9826: }
9827:
9828: sub current_machine_domains {
1.853 albertel 9829: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9830: }
9831:
9832: sub machine_domains {
9833: my ($hostname) = @_;
1.465 albertel 9834: my @domains;
1.838 albertel 9835: my %hostname = &all_hostnames();
1.465 albertel 9836: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9837: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9838: if ($hostname eq $name) {
1.844 albertel 9839: push(@domains,&host_domain($id));
1.465 albertel 9840: }
9841: }
9842: return @domains;
9843: }
9844:
9845: sub current_machine_ids {
1.853 albertel 9846: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9847: }
9848:
9849: sub machine_ids {
9850: my ($hostname) = @_;
9851: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9852: my @ids;
1.888 albertel 9853: my %name_to_host = &all_names();
1.889 albertel 9854: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9855: return @{ $name_to_host{$hostname} };
9856: }
9857: return;
1.31 www 9858: }
9859:
1.824 raeburn 9860: sub additional_machine_domains {
9861: my @domains;
9862: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9863: while( my $line = <$fh>) {
9864: $line =~ s/\s//g;
9865: push(@domains,$line);
9866: }
9867: return @domains;
9868: }
9869:
9870: sub default_login_domain {
9871: my $domain = $perlvar{'lonDefDomain'};
9872: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9873: foreach my $posdom (¤t_machine_domains(),
9874: &additional_machine_domains()) {
9875: if (lc($posdom) eq lc($testdomain)) {
9876: $domain=$posdom;
9877: last;
9878: }
9879: }
9880: return $domain;
9881: }
9882:
1.31 www 9883: # ------------------------------------------------------------- Declutters URLs
9884:
9885: sub declutter {
9886: my $thisfn=shift;
1.569 albertel 9887: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9888: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9889: $thisfn=~s/^\///;
1.697 albertel 9890: $thisfn=~s|^adm/wrapper/||;
9891: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9892: $thisfn=~s/^res\///;
1.1032 raeburn 9893: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9894: $thisfn=~s/\?.+$//;
9895: }
1.268 www 9896: return $thisfn;
9897: }
9898:
9899: # ------------------------------------------------------------- Clutter up URLs
9900:
9901: sub clutter {
9902: my $thisfn='/'.&declutter(shift);
1.887 albertel 9903: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9904: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9905: $thisfn='/res'.$thisfn;
9906: }
1.1031 raeburn 9907: if ($thisfn !~m|^/adm|) {
9908: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9909: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9910: } else {
9911: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9912: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9913: if ($embstyle eq 'ssi'
9914: || ($embstyle eq 'hdn')
9915: || ($embstyle eq 'rat')
9916: || ($embstyle eq 'prv')
9917: || ($embstyle eq 'ign')) {
9918: #do nothing with these
9919: } elsif (($embstyle eq 'img')
1.695 albertel 9920: || ($embstyle eq 'emb')
9921: || ($embstyle eq 'wrp')) {
9922: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9923: } elsif ($embstyle eq 'unk'
9924: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9925: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9926: } else {
1.718 www 9927: # &logthis("Got a blank emb style");
1.695 albertel 9928: }
1.694 albertel 9929: }
9930: }
1.31 www 9931: return $thisfn;
1.12 www 9932: }
9933:
1.787 albertel 9934: sub clutter_with_no_wrapper {
9935: my $uri = &clutter(shift);
9936: if ($uri =~ m-^/adm/-) {
9937: $uri =~ s-^/adm/wrapper/-/-;
9938: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9939: }
9940: return $uri;
9941: }
9942:
1.557 albertel 9943: sub freeze_escape {
9944: my ($value)=@_;
9945: if (ref($value)) {
9946: $value=&nfreeze($value);
9947: return '__FROZEN__'.&escape($value);
9948: }
9949: return &escape($value);
9950: }
9951:
1.11 www 9952:
1.557 albertel 9953: sub thaw_unescape {
9954: my ($value)=@_;
9955: if ($value =~ /^__FROZEN__/) {
9956: substr($value,0,10,undef);
9957: $value=&unescape($value);
9958: return &thaw($value);
9959: }
9960: return &unescape($value);
9961: }
9962:
1.436 albertel 9963: sub correct_line_ends {
9964: my ($result)=@_;
9965: $$result =~s/\r\n/\n/mg;
9966: $$result =~s/\r/\n/mg;
1.415 albertel 9967: }
1.1 albertel 9968: # ================================================================ Main Program
9969:
1.184 www 9970: sub goodbye {
1.204 albertel 9971: &logthis("Starting Shut down");
1.443 albertel 9972: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9973: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9974: #converted
1.599 albertel 9975: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9976: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9977: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9978: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9979: #1.1 only
1.870 albertel 9980: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9981: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9982: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9983: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9984: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9985: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9986: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9987: &flushcourselogs();
9988: &logthis("Shutting down");
9989: }
9990:
1.852 albertel 9991: sub get_dns {
1.869 albertel 9992: my ($url,$func,$ignore_cache) = @_;
9993: if (!$ignore_cache) {
9994: my ($content,$cached)=
9995: &Apache::lonnet::is_cached_new('dns',$url);
9996: if ($cached) {
9997: &$func($content);
9998: return;
9999: }
10000: }
10001:
10002: my %alldns;
1.852 albertel 10003: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10004: foreach my $dns (<$config>) {
10005: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10006: my $line = $1;
10007: my ($host,$protocol) = split(/:/,$line);
10008: if ($protocol ne 'https') {
10009: $protocol = 'http';
10010: }
10011: $alldns{$host} = $protocol;
1.869 albertel 10012: }
10013: while (%alldns) {
10014: my ($dns) = keys(%alldns);
1.852 albertel 10015: my $ua=new LWP::UserAgent;
1.979 raeburn 10016: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10017: my $response=$ua->request($request);
1.979 raeburn 10018: delete($alldns{$dns});
1.852 albertel 10019: next if ($response->is_error());
10020: my @content = split("\n",$response->content);
1.869 albertel 10021: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10022: &$func(\@content);
1.869 albertel 10023: return;
1.852 albertel 10024: }
10025: close($config);
1.871 albertel 10026: my $which = (split('/',$url))[3];
10027: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10028: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10029: my @content = <$config>;
10030: &$func(\@content);
10031: return;
1.852 albertel 10032: }
1.327 albertel 10033: # ------------------------------------------------------------ Read domain file
10034: {
1.852 albertel 10035: my $loaded;
1.846 albertel 10036: my %domain;
10037:
1.852 albertel 10038: sub parse_domain_tab {
10039: my ($lines) = @_;
10040: foreach my $line (@$lines) {
10041: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10042:
1.846 albertel 10043: chomp($line);
1.852 albertel 10044: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10045: my %this_domain;
10046: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10047: 'lang_def', 'city', 'longi', 'lati',
10048: 'primary') {
10049: $this_domain{$field} = shift(@elements);
10050: }
10051: $domain{$name} = \%this_domain;
1.852 albertel 10052: }
10053: }
1.864 albertel 10054:
10055: sub reset_domain_info {
10056: undef($loaded);
10057: undef(%domain);
10058: }
10059:
1.852 albertel 10060: sub load_domain_tab {
1.869 albertel 10061: my ($ignore_cache) = @_;
10062: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10063: my $fh;
10064: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10065: my @lines = <$fh>;
10066: &parse_domain_tab(\@lines);
1.448 albertel 10067: }
1.852 albertel 10068: close($fh);
10069: $loaded = 1;
1.327 albertel 10070: }
1.846 albertel 10071:
10072: sub domain {
1.852 albertel 10073: &load_domain_tab() if (!$loaded);
10074:
1.846 albertel 10075: my ($name,$what) = @_;
10076: return if ( !exists($domain{$name}) );
10077:
10078: if (!$what) {
10079: return $domain{$name}{'description'};
10080: }
10081: return $domain{$name}{$what};
10082: }
1.974 raeburn 10083:
10084: sub domain_info {
10085: &load_domain_tab() if (!$loaded);
10086: return %domain;
10087: }
10088:
1.327 albertel 10089: }
10090:
10091:
1.1 albertel 10092: # ------------------------------------------------------------- Read hosts file
10093: {
1.838 albertel 10094: my %hostname;
1.844 albertel 10095: my %hostdom;
1.845 albertel 10096: my %libserv;
1.852 albertel 10097: my $loaded;
1.888 albertel 10098: my %name_to_host;
1.1074 raeburn 10099: my %internetdom;
1.1107 raeburn 10100: my %LC_dns_serv;
1.852 albertel 10101:
10102: sub parse_hosts_tab {
10103: my ($file) = @_;
10104: foreach my $configline (@$file) {
10105: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10106: chomp($configline);
10107: if ($configline =~ /^\^/) {
10108: if ($configline =~ /^\^([\w.\-]+)/) {
10109: $LC_dns_serv{$1} = 1;
10110: }
10111: next;
10112: }
1.1074 raeburn 10113: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10114: $name=~s/\s//g;
10115: if ($id && $domain && $role && $name) {
10116: $hostname{$id}=$name;
1.888 albertel 10117: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10118: $hostdom{$id}=$domain;
10119: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10120: if (defined($protocol)) {
10121: if ($protocol eq 'https') {
10122: $protocol{$id} = $protocol;
10123: } else {
10124: $protocol{$id} = 'http';
10125: }
1.968 raeburn 10126: } else {
1.969 raeburn 10127: $protocol{$id} = 'http';
1.968 raeburn 10128: }
1.1074 raeburn 10129: if (defined($intdom)) {
10130: $internetdom{$id} = $intdom;
10131: }
1.852 albertel 10132: }
10133: }
10134: }
1.864 albertel 10135:
10136: sub reset_hosts_info {
1.897 albertel 10137: &purge_remembered();
1.864 albertel 10138: &reset_domain_info();
10139: &reset_hosts_ip_info();
1.892 albertel 10140: undef(%name_to_host);
1.864 albertel 10141: undef(%hostname);
10142: undef(%hostdom);
10143: undef(%libserv);
10144: undef($loaded);
10145: }
1.1 albertel 10146:
1.852 albertel 10147: sub load_hosts_tab {
1.869 albertel 10148: my ($ignore_cache) = @_;
10149: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10150: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10151: my @config = <$config>;
10152: &parse_hosts_tab(\@config);
10153: close($config);
10154: $loaded=1;
1.1 albertel 10155: }
1.852 albertel 10156:
1.838 albertel 10157: sub hostname {
1.852 albertel 10158: &load_hosts_tab() if (!$loaded);
10159:
1.838 albertel 10160: my ($lonid) = @_;
10161: return $hostname{$lonid};
10162: }
1.845 albertel 10163:
1.838 albertel 10164: sub all_hostnames {
1.852 albertel 10165: &load_hosts_tab() if (!$loaded);
10166:
1.838 albertel 10167: return %hostname;
10168: }
1.845 albertel 10169:
1.888 albertel 10170: sub all_names {
10171: &load_hosts_tab() if (!$loaded);
10172:
10173: return %name_to_host;
10174: }
10175:
1.974 raeburn 10176: sub all_host_domain {
10177: &load_hosts_tab() if (!$loaded);
10178: return %hostdom;
10179: }
10180:
1.845 albertel 10181: sub is_library {
1.852 albertel 10182: &load_hosts_tab() if (!$loaded);
10183:
1.845 albertel 10184: return exists($libserv{$_[0]});
10185: }
10186:
10187: sub all_library {
1.852 albertel 10188: &load_hosts_tab() if (!$loaded);
10189:
1.845 albertel 10190: return %libserv;
10191: }
10192:
1.1062 droeschl 10193: sub unique_library {
10194: #2x reverse removes all hostnames that appear more than once
10195: my %unique = reverse &all_library();
10196: return reverse %unique;
10197: }
10198:
1.841 albertel 10199: sub get_servers {
1.852 albertel 10200: &load_hosts_tab() if (!$loaded);
10201:
1.841 albertel 10202: my ($domain,$type) = @_;
10203: my %possible_hosts = ($type eq 'library') ? %libserv
10204: : %hostname;
10205: my %result;
1.842 albertel 10206: if (ref($domain) eq 'ARRAY') {
10207: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10208: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10209: $result{$host} = $hostname;
10210: }
10211: }
10212: } else {
10213: while ( my ($host,$hostname) = each(%possible_hosts)) {
10214: if ($hostdom{$host} eq $domain) {
10215: $result{$host} = $hostname;
10216: }
1.841 albertel 10217: }
10218: }
10219: return %result;
10220: }
1.845 albertel 10221:
1.1062 droeschl 10222: sub get_unique_servers {
10223: my %unique = reverse &get_servers(@_);
10224: return reverse %unique;
10225: }
10226:
1.844 albertel 10227: sub host_domain {
1.852 albertel 10228: &load_hosts_tab() if (!$loaded);
10229:
1.844 albertel 10230: my ($lonid) = @_;
10231: return $hostdom{$lonid};
10232: }
10233:
1.841 albertel 10234: sub all_domains {
1.852 albertel 10235: &load_hosts_tab() if (!$loaded);
10236:
1.841 albertel 10237: my %seen;
10238: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10239: return @uniq;
10240: }
1.1074 raeburn 10241:
10242: sub internet_dom {
10243: &load_hosts_tab() if (!$loaded);
10244:
10245: my ($lonid) = @_;
10246: return $internetdom{$lonid};
10247: }
1.1107 raeburn 10248:
10249: sub is_LC_dns {
10250: &load_hosts_tab() if (!$loaded);
10251:
10252: my ($hostname) = @_;
10253: return exists($LC_dns_serv{$hostname});
10254: }
10255:
1.1 albertel 10256: }
10257:
1.847 albertel 10258: {
10259: my %iphost;
1.856 albertel 10260: my %name_to_ip;
10261: my %lonid_to_ip;
1.869 albertel 10262:
1.847 albertel 10263: sub get_hosts_from_ip {
10264: my ($ip) = @_;
10265: my %iphosts = &get_iphost();
10266: if (ref($iphosts{$ip})) {
10267: return @{$iphosts{$ip}};
10268: }
10269: return;
1.839 albertel 10270: }
1.864 albertel 10271:
10272: sub reset_hosts_ip_info {
10273: undef(%iphost);
10274: undef(%name_to_ip);
10275: undef(%lonid_to_ip);
10276: }
1.856 albertel 10277:
10278: sub get_host_ip {
10279: my ($lonid) = @_;
10280: if (exists($lonid_to_ip{$lonid})) {
10281: return $lonid_to_ip{$lonid};
10282: }
10283: my $name=&hostname($lonid);
10284: my $ip = gethostbyname($name);
10285: return if (!$ip || length($ip) ne 4);
10286: $ip=inet_ntoa($ip);
10287: $name_to_ip{$name} = $ip;
10288: $lonid_to_ip{$lonid} = $ip;
10289: return $ip;
10290: }
1.847 albertel 10291:
10292: sub get_iphost {
1.869 albertel 10293: my ($ignore_cache) = @_;
1.894 albertel 10294:
1.869 albertel 10295: if (!$ignore_cache) {
10296: if (%iphost) {
10297: return %iphost;
10298: }
10299: my ($ip_info,$cached)=
10300: &Apache::lonnet::is_cached_new('iphost','iphost');
10301: if ($cached) {
10302: %iphost = %{$ip_info->[0]};
10303: %name_to_ip = %{$ip_info->[1]};
10304: %lonid_to_ip = %{$ip_info->[2]};
10305: return %iphost;
10306: }
10307: }
1.894 albertel 10308:
10309: # get yesterday's info for fallback
10310: my %old_name_to_ip;
10311: my ($ip_info,$cached)=
10312: &Apache::lonnet::is_cached_new('iphost','iphost');
10313: if ($cached) {
10314: %old_name_to_ip = %{$ip_info->[1]};
10315: }
10316:
1.888 albertel 10317: my %name_to_host = &all_names();
10318: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10319: my $ip;
10320: if (!exists($name_to_ip{$name})) {
10321: $ip = gethostbyname($name);
10322: if (!$ip || length($ip) ne 4) {
1.894 albertel 10323: if (defined($old_name_to_ip{$name})) {
10324: $ip = $old_name_to_ip{$name};
10325: &logthis("Can't find $name defaulting to old $ip");
10326: } else {
10327: &logthis("Name $name no IP found");
10328: next;
10329: }
10330: } else {
10331: $ip=inet_ntoa($ip);
1.847 albertel 10332: }
10333: $name_to_ip{$name} = $ip;
10334: } else {
10335: $ip = $name_to_ip{$name};
1.653 albertel 10336: }
1.888 albertel 10337: foreach my $id (@{ $name_to_host{$name} }) {
10338: $lonid_to_ip{$id} = $ip;
10339: }
10340: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10341: }
1.869 albertel 10342: &Apache::lonnet::do_cache_new('iphost','iphost',
10343: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10344: 48*60*60);
1.869 albertel 10345:
1.847 albertel 10346: return %iphost;
1.598 albertel 10347: }
10348:
1.992 raeburn 10349: #
10350: # Given a DNS returns the loncapa host name for that DNS
10351: #
10352: sub host_from_dns {
10353: my ($dns) = @_;
10354: my @hosts;
10355: my $ip;
10356:
1.993 raeburn 10357: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10358: $ip = $name_to_ip{$dns};
10359: }
10360: if (!$ip) {
10361: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10362: if (length($ip) == 4) {
10363: $ip = &IO::Socket::inet_ntoa($ip);
10364: }
10365: }
10366: if ($ip) {
10367: @hosts = get_hosts_from_ip($ip);
10368: return $hosts[0];
10369: }
10370: return undef;
1.986 foxr 10371: }
1.992 raeburn 10372:
1.1074 raeburn 10373: sub get_internet_names {
10374: my ($lonid) = @_;
10375: return if ($lonid eq '');
10376: my ($idnref,$cached)=
10377: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10378: if ($cached) {
10379: return $idnref;
10380: }
10381: my $ip = &get_host_ip($lonid);
10382: my @hosts = &get_hosts_from_ip($ip);
10383: my %iphost = &get_iphost();
10384: my (@idns,%seen);
10385: foreach my $id (@hosts) {
10386: my $dom = &host_domain($id);
10387: my $prim_id = &domain($dom,'primary');
10388: my $prim_ip = &get_host_ip($prim_id);
10389: next if ($seen{$prim_ip});
10390: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10391: foreach my $id (@{$iphost{$prim_ip}}) {
10392: my $intdom = &internet_dom($id);
10393: unless (grep(/^\Q$intdom\E$/,@idns)) {
10394: push(@idns,$intdom);
10395: }
10396: }
10397: }
10398: $seen{$prim_ip} = 1;
10399: }
10400: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10401: }
10402:
1.986 foxr 10403: }
10404:
1.1079 raeburn 10405: sub all_loncaparevs {
10406: 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);
10407: }
10408:
1.862 albertel 10409: BEGIN {
10410:
10411: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10412: unless ($readit) {
10413: {
10414: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10415: %perlvar = (%perlvar,%{$configvars});
10416: }
10417:
10418:
1.1 albertel 10419: # ------------------------------------------------------ Read spare server file
10420: {
1.448 albertel 10421: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10422:
10423: while (my $configline=<$config>) {
10424: chomp($configline);
1.284 matthew 10425: if ($configline) {
1.784 albertel 10426: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10427: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10428: push(@{ $spareid{$type} }, $host);
1.1 albertel 10429: }
10430: }
1.448 albertel 10431: close($config);
1.1 albertel 10432: }
1.11 www 10433: # ------------------------------------------------------------ Read permissions
10434: {
1.448 albertel 10435: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10436:
10437: while (my $configline=<$config>) {
1.448 albertel 10438: chomp($configline);
10439: if ($configline) {
10440: my ($role,$perm)=split(/ /,$configline);
10441: if ($perm ne '') { $pr{$role}=$perm; }
10442: }
1.11 www 10443: }
1.448 albertel 10444: close($config);
1.11 www 10445: }
10446:
10447: # -------------------------------------------- Read plain texts for permissions
10448: {
1.448 albertel 10449: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10450:
10451: while (my $configline=<$config>) {
1.448 albertel 10452: chomp($configline);
10453: if ($configline) {
1.742 raeburn 10454: my ($short,@plain)=split(/:/,$configline);
10455: %{$prp{$short}} = ();
10456: if (@plain > 0) {
10457: $prp{$short}{'std'} = $plain[0];
10458: for (my $i=1; $i<@plain; $i++) {
10459: $prp{$short}{'alt'.$i} = $plain[$i];
10460: }
10461: }
1.448 albertel 10462: }
1.135 www 10463: }
1.448 albertel 10464: close($config);
1.135 www 10465: }
10466:
10467: # ---------------------------------------------------------- Read package table
10468: {
1.448 albertel 10469: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10470:
10471: while (my $configline=<$config>) {
1.483 albertel 10472: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10473: chomp($configline);
10474: my ($short,$plain)=split(/:/,$configline);
10475: my ($pack,$name)=split(/\&/,$short);
10476: if ($plain ne '') {
10477: $packagetab{$pack.'&'.$name.'&name'}=$name;
10478: $packagetab{$short}=$plain;
10479: }
1.11 www 10480: }
1.448 albertel 10481: close($config);
1.329 matthew 10482: }
10483:
1.1073 raeburn 10484: # ---------------------------------------------------------- Read loncaparev table
10485: {
10486: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10487: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10488: while (my $configline=<$config>) {
10489: chomp($configline);
10490: my ($hostid,$loncaparev)=split(/:/,$configline);
10491: $loncaparevs{$hostid}=$loncaparev;
10492: }
10493: close($config);
10494: }
10495: }
10496: }
10497:
1.1074 raeburn 10498: # ---------------------------------------------------------- Read serverhostID table
10499: {
10500: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10501: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10502: while (my $configline=<$config>) {
10503: chomp($configline);
10504: my ($name,$id)=split(/:/,$configline);
10505: $serverhomeIDs{$name}=$id;
10506: }
10507: close($config);
10508: }
10509: }
10510: }
10511:
1.1079 raeburn 10512: {
10513: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10514: if (-e $file) {
10515: my $parser = HTML::LCParser->new($file);
10516: while (my $token = $parser->get_token()) {
10517: if ($token->[0] eq 'S') {
10518: my $item = $token->[1];
10519: my $name = $token->[2]{'name'};
10520: my $value = $token->[2]{'value'};
10521: if ($item ne '' && $name ne '' && $value ne '') {
10522: my $release = $parser->get_text();
10523: $release =~ s/(^\s*|\s*$ )//gx;
10524: $needsrelease{$item.':'.$name.':'.$value} = $release;
10525: }
10526: }
10527: }
10528: }
1.1073 raeburn 10529: }
10530:
1.329 matthew 10531: # ------------- set up temporary directory
10532: {
10533: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10534:
1.11 www 10535: }
10536:
1.794 albertel 10537: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10538: 'compress_threshold'=> 20_000,
10539: });
1.185 www 10540:
1.281 www 10541: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10542: $dumpcount=0;
1.958 www 10543: $locknum=0;
1.22 www 10544:
1.163 harris41 10545: &logtouch();
1.672 albertel 10546: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10547: $readit=1;
1.564 albertel 10548: {
10549: use integer;
10550: my $test=(2**32)+1;
1.568 albertel 10551: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10552: &logthis(" Detected 64bit platform ($_64bit)");
10553: }
1.195 www 10554: }
1.1 albertel 10555: }
1.179 www 10556:
1.1 albertel 10557: 1;
1.191 harris41 10558: __END__
10559:
1.243 albertel 10560: =pod
10561:
1.191 harris41 10562: =head1 NAME
10563:
1.243 albertel 10564: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10565:
10566: =head1 SYNOPSIS
10567:
1.243 albertel 10568: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10569:
10570: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10571:
1.243 albertel 10572: Common parameters:
10573:
10574: =over 4
10575:
10576: =item *
10577:
10578: $uname : an internal username (if $cname expecting a course Id specifically)
10579:
10580: =item *
10581:
10582: $udom : a domain (if $cdom expecting a course's domain specifically)
10583:
10584: =item *
10585:
10586: $symb : a resource instance identifier
10587:
10588: =item *
10589:
10590: $namespace : the name of a .db file that contains the data needed or
10591: being set.
10592:
10593: =back
10594:
1.394 bowersj2 10595: =head1 OVERVIEW
1.191 harris41 10596:
1.394 bowersj2 10597: lonnet provides subroutines which interact with the
10598: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10599: about classes, users, and resources.
1.243 albertel 10600:
10601: For many of these objects you can also use this to store data about
10602: them or modify them in various ways.
1.191 harris41 10603:
1.394 bowersj2 10604: =head2 Symbs
1.191 harris41 10605:
1.394 bowersj2 10606: To identify a specific instance of a resource, LON-CAPA uses symbols
10607: or "symbs"X<symb>. These identifiers are built from the URL of the
10608: map, the resource number of the resource in the map, and the URL of
10609: the resource itself. The latter is somewhat redundant, but might help
10610: if maps change.
10611:
10612: An example is
10613:
10614: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10615:
10616: The respective map entry is
10617:
10618: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10619: title="Problem 2">
10620: </resource>
10621:
10622: Symbs are used by the random number generator, as well as to store and
10623: restore data specific to a certain instance of for example a problem.
10624:
10625: =head2 Storing And Retrieving Data
10626:
10627: X<store()>X<cstore()>X<restore()>Three of the most important functions
10628: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10629: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10630: is is the non-critical message twin of cstore. These functions are for
10631: handlers to store a perl hash to a user's permanent data space in an
10632: easy manner, and to retrieve it again on another call. It is expected
10633: that a handler would use this once at the beginning to retrieve data,
10634: and then again once at the end to send only the new data back.
10635:
10636: The data is stored in the user's data directory on the user's
10637: homeserver under the ID of the course.
10638:
10639: The hash that is returned by restore will have all of the previous
10640: value for all of the elements of the hash.
10641:
10642: Example:
10643:
10644: #creating a hash
10645: my %hash;
10646: $hash{'foo'}='bar';
10647:
10648: #storing it
10649: &Apache::lonnet::cstore(\%hash);
10650:
10651: #changing a value
10652: $hash{'foo'}='notbar';
10653:
10654: #adding a new value
10655: $hash{'bar'}='foo';
10656: &Apache::lonnet::cstore(\%hash);
10657:
10658: #retrieving the hash
10659: my %history=&Apache::lonnet::restore();
10660:
10661: #print the hash
10662: foreach my $key (sort(keys(%history))) {
10663: print("\%history{$key} = $history{$key}");
10664: }
10665:
10666: Will print out:
1.191 harris41 10667:
1.394 bowersj2 10668: %history{1:foo} = bar
10669: %history{1:keys} = foo:timestamp
10670: %history{1:timestamp} = 990455579
10671: %history{2:bar} = foo
10672: %history{2:foo} = notbar
10673: %history{2:keys} = foo:bar:timestamp
10674: %history{2:timestamp} = 990455580
10675: %history{bar} = foo
10676: %history{foo} = notbar
10677: %history{timestamp} = 990455580
10678: %history{version} = 2
10679:
10680: Note that the special hash entries C<keys>, C<version> and
10681: C<timestamp> were added to the hash. C<version> will be equal to the
10682: total number of versions of the data that have been stored. The
10683: C<timestamp> attribute will be the UNIX time the hash was
10684: stored. C<keys> is available in every historical section to list which
10685: keys were added or changed at a specific historical revision of a
10686: hash.
10687:
10688: B<Warning>: do not store the hash that restore returns directly. This
10689: will cause a mess since it will restore the historical keys as if the
10690: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10691:
1.394 bowersj2 10692: Calling convention:
1.191 harris41 10693:
1.394 bowersj2 10694: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10695: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10696:
1.394 bowersj2 10697: For more detailed information, see lonnet specific documentation.
1.191 harris41 10698:
1.394 bowersj2 10699: =head1 RETURN MESSAGES
1.191 harris41 10700:
1.394 bowersj2 10701: =over 4
1.191 harris41 10702:
1.394 bowersj2 10703: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10704:
1.394 bowersj2 10705: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10706: when the connection is brought back up
1.191 harris41 10707:
1.394 bowersj2 10708: =item * B<con_failed>: unable to contact remote host and unable to save message
10709: for later delivery
1.191 harris41 10710:
1.967 bisitz 10711: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10712:
1.394 bowersj2 10713: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10714: that was requested
1.191 harris41 10715:
1.243 albertel 10716: =back
1.191 harris41 10717:
1.243 albertel 10718: =head1 PUBLIC SUBROUTINES
1.191 harris41 10719:
1.243 albertel 10720: =head2 Session Environment Functions
1.191 harris41 10721:
1.243 albertel 10722: =over 4
1.191 harris41 10723:
1.394 bowersj2 10724: =item *
10725: X<appenv()>
1.949 raeburn 10726: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10727: the user envirnoment file, and will be restored for each access this
1.620 albertel 10728: user makes during this session, also modifies the %env for the current
1.949 raeburn 10729: process. Optional rolesarrayref - if defined contains a reference to an array
10730: of roles which are exempt from the restriction on modifying user.role entries
10731: in the user's environment.db and in %env.
1.191 harris41 10732:
10733: =item *
1.394 bowersj2 10734: X<delenv()>
1.987 raeburn 10735: B<delenv($delthis,$regexp)>: removes all items from the session
10736: environment file that begin with $delthis. If the
10737: optional second arg - $regexp - is true, $delthis is treated as a
10738: regular expression, otherwise \Q$delthis\E is used.
10739: The values are also deleted from the current processes %env.
1.191 harris41 10740:
1.795 albertel 10741: =item * get_env_multiple($name)
10742:
10743: gets $name from the %env hash, it seemlessly handles the cases where multiple
10744: values may be defined and end up as an array ref.
10745:
10746: returns an array of values
10747:
1.243 albertel 10748: =back
10749:
10750: =head2 User Information
1.191 harris41 10751:
1.243 albertel 10752: =over 4
1.191 harris41 10753:
10754: =item *
1.394 bowersj2 10755: X<queryauthenticate()>
10756: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10757: authentication scheme
10758:
10759: =item *
1.394 bowersj2 10760: X<authenticate()>
1.1073 raeburn 10761: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10762: authenticate user from domain's lib servers (first use the current
10763: one). C<$upass> should be the users password.
1.1073 raeburn 10764: $checkdefauth is optional (value is 1 if a check should be made to
10765: authenticate user using default authentication method, and allow
10766: account creation if username does not have account in the domain).
10767: $clientcancheckhost is optional (value is 1 if checking whether the
10768: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10769:
10770: =item *
1.394 bowersj2 10771: X<homeserver()>
10772: B<homeserver($uname,$udom)>: find the server which has
10773: the user's directory and files (there must be only one), this caches
10774: the answer, and also caches if there is a borken connection.
1.191 harris41 10775:
10776: =item *
1.394 bowersj2 10777: X<idget()>
10778: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10779: (IDs are a unique resource in a domain, there must be only 1 ID per
10780: username, and only 1 username per ID in a specific domain) (returns
10781: hash: id=>name,id=>name)
1.191 harris41 10782:
10783: =item *
1.394 bowersj2 10784: X<idrget()>
10785: B<idrget($udom,@unames)>: find the IDs behind a list of
10786: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10787:
10788: =item *
1.394 bowersj2 10789: X<idput()>
10790: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10791:
10792: =item *
1.394 bowersj2 10793: X<rolesinit()>
10794: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10795:
10796: =item *
1.551 albertel 10797: X<getsection()>
10798: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10799: course $cname, return section name/number or '' for "not in course"
10800: and '-1' for "no section"
10801:
10802: =item *
1.394 bowersj2 10803: X<userenvironment()>
10804: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10805: passed in @what from the requested user's environment, returns a hash
10806:
1.858 raeburn 10807: =item *
10808: X<userlog_query()>
1.859 albertel 10809: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10810: activity.log file. %filters defines filters applied when parsing the
10811: log file. These can be start or end timestamps, or the type of action
10812: - log to look for Login or Logout events, check for Checkin or
10813: Checkout, role for role selection. The response is in the form
10814: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10815: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10816:
1.243 albertel 10817: =back
10818:
10819: =head2 User Roles
10820:
10821: =over 4
10822:
10823: =item *
10824:
1.810 raeburn 10825: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10826: F: full access
10827: U,I,K: authentication modes (cxx only)
10828: '': forbidden
10829: 1: user needs to choose course
10830: 2: browse allowed
1.766 albertel 10831: A: passphrase authentication needed
1.243 albertel 10832:
10833: =item *
10834:
10835: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10836: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10837: and course level
10838:
10839: =item *
10840:
1.988 raeburn 10841: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10842: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10843: $type is Course (default) or Community.
1.988 raeburn 10844: If $forcedefault evaluates to true, text returned will be default
10845: text for $type. Otherwise, if this is a course, the text returned
10846: will be a custom name for the role (if defined in the course's
10847: environment). If no custom name is defined the default is returned.
10848:
1.832 raeburn 10849: =item *
10850:
1.935 raeburn 10851: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10852: All arguments are optional. Returns a hash of a roles, either for
10853: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10854: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10855: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10856: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10857: For each key, value is set to colon-separated start and end times for
10858: the role. If no username and domain are specified, will default to
1.934 raeburn 10859: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10860: of role statuses (active, future or previous), roles
10861: (e.g., cc,in, st etc.) and domains of the roles which can be used
10862: to restrict the list of roles reported. If no array ref is
10863: provided for types, will default to return only active roles.
1.834 albertel 10864:
1.243 albertel 10865: =back
10866:
10867: =head2 User Modification
10868:
10869: =over 4
10870:
10871: =item *
10872:
1.957 raeburn 10873: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10874: user for the level given by URL. Optional start and end dates (leave empty
10875: string or zero for "no date")
1.191 harris41 10876:
10877: =item *
10878:
1.243 albertel 10879: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10880: change a users, password, possible return values are: ok,
10881: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10882: refused
1.191 harris41 10883:
10884: =item *
10885:
1.243 albertel 10886: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10887:
10888: =item *
10889:
1.1058 raeburn 10890: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10891: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10892:
10893: will update user information (firstname,middlename,lastname,generation,
10894: permanentemail), and if forceid is true, student/employee ID also.
10895: A user's institutional affiliation(s) can also be updated.
10896: User information fields will not be overwritten with empty entries
10897: unless the field is included in the $candelete array reference.
10898: This array is included when a single user is modified via "Manage Users",
10899: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10900:
10901: =item *
10902:
1.286 matthew 10903: modifystudent
10904:
1.957 raeburn 10905: modify a student's enrollment and identification information.
1.286 matthew 10906: The course id is resolved based on the current users environment.
10907: This means the envoking user must be a course coordinator or otherwise
10908: associated with a course.
10909:
1.297 matthew 10910: This call is essentially a wrapper for lonnet::modifyuser and
10911: lonnet::modify_student_enrollment
1.286 matthew 10912:
10913: Inputs:
10914:
10915: =over 4
10916:
1.957 raeburn 10917: =item B<$udom> Student's loncapa domain
1.286 matthew 10918:
1.957 raeburn 10919: =item B<$uname> Student's loncapa login name
1.286 matthew 10920:
1.964 bisitz 10921: =item B<$uid> Student/Employee ID
1.286 matthew 10922:
1.957 raeburn 10923: =item B<$umode> Student's authentication mode
1.286 matthew 10924:
1.957 raeburn 10925: =item B<$upass> Student's password
1.286 matthew 10926:
1.957 raeburn 10927: =item B<$first> Student's first name
1.286 matthew 10928:
1.957 raeburn 10929: =item B<$middle> Student's middle name
1.286 matthew 10930:
1.957 raeburn 10931: =item B<$last> Student's last name
1.286 matthew 10932:
1.957 raeburn 10933: =item B<$gene> Student's generation
1.286 matthew 10934:
1.957 raeburn 10935: =item B<$usec> Student's section in course
1.286 matthew 10936:
10937: =item B<$end> Unix time of the roles expiration
10938:
10939: =item B<$start> Unix time of the roles start date
10940:
10941: =item B<$forceid> If defined, allow $uid to be changed
10942:
10943: =item B<$desiredhome> server to use as home server for student
10944:
1.957 raeburn 10945: =item B<$email> Student's permanent e-mail address
10946:
10947: =item B<$type> Type of enrollment (auto or manual)
10948:
1.963 raeburn 10949: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10950:
10951: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10952:
1.963 raeburn 10953: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10954:
1.963 raeburn 10955: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10956:
1.963 raeburn 10957: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10958:
1.286 matthew 10959: =back
1.297 matthew 10960:
10961: =item *
10962:
10963: modify_student_enrollment
10964:
10965: Change a students enrollment status in a class. The environment variable
10966: 'role.request.course' must be defined for this function to proceed.
10967:
10968: Inputs:
10969:
10970: =over 4
10971:
10972: =item $udom, students domain
10973:
10974: =item $uname, students name
10975:
10976: =item $uid, students user id
10977:
10978: =item $first, students first name
10979:
10980: =item $middle
10981:
10982: =item $last
10983:
10984: =item $gene
10985:
10986: =item $usec
10987:
10988: =item $end
10989:
10990: =item $start
10991:
1.957 raeburn 10992: =item $type
10993:
10994: =item $locktype
10995:
10996: =item $cid
10997:
10998: =item $selfenroll
10999:
11000: =item $context
11001:
1.297 matthew 11002: =back
11003:
1.191 harris41 11004:
11005: =item *
11006:
1.243 albertel 11007: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11008: custom role; give a custom role to a user for the level given by URL. Specify
11009: name and domain of role author, and role name
1.191 harris41 11010:
11011: =item *
11012:
1.243 albertel 11013: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11014:
11015: =item *
11016:
1.243 albertel 11017: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11018:
11019: =back
11020:
11021: =head2 Course Infomation
11022:
11023: =over 4
1.191 harris41 11024:
11025: =item *
11026:
1.631 albertel 11027: coursedescription($courseid) : returns a hash of information about the
11028: specified course id, including all environment settings for the
11029: course, the description of the course will be in the hash under the
11030: key 'description'
1.191 harris41 11031:
11032: =item *
11033:
1.624 albertel 11034: resdata($name,$domain,$type,@which) : request for current parameter
11035: setting for a specific $type, where $type is either 'course' or 'user',
11036: @what should be a list of parameters to ask about. This routine caches
11037: answers for 5 minutes.
1.243 albertel 11038:
1.877 foxr 11039: =item *
11040:
11041: get_courseresdata($courseid, $domain) : dump the entire course resource
11042: data base, returning a hash that is keyed by the resource name and has
11043: values that are the resource value. I believe that the timestamps and
11044: versions are also returned.
11045:
11046:
1.243 albertel 11047: =back
11048:
11049: =head2 Course Modification
11050:
11051: =over 4
1.191 harris41 11052:
11053: =item *
11054:
1.243 albertel 11055: writecoursepref($courseid,%prefs) : write preferences (environment
11056: database) for a course
1.191 harris41 11057:
11058: =item *
11059:
1.1011 raeburn 11060: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11061:
11062: =item *
11063:
1.1038 raeburn 11064: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11065:
11066: =back
11067:
11068: =head2 Resource Subroutines
11069:
11070: =over 4
1.191 harris41 11071:
11072: =item *
11073:
1.243 albertel 11074: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11075:
11076: =item *
11077:
1.243 albertel 11078: repcopy($filename) : subscribes to the requested file, and attempts to
11079: replicate from the owning library server, Might return
1.607 raeburn 11080: 'unavailable', 'not_found', 'forbidden', 'ok', or
11081: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11082: resource. Expects the local filesystem pathname
11083: (/home/httpd/html/res/....)
11084:
11085: =back
11086:
11087: =head2 Resource Information
11088:
11089: =over 4
1.191 harris41 11090:
11091: =item *
11092:
1.243 albertel 11093: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11094: a vairety of different possible values, $varname should be a request
11095: string, and the other parameters can be used to specify who and what
11096: one is asking about.
11097:
11098: Possible values for $varname are environment.lastname (or other item
11099: from the envirnment hash), user.name (or someother aspect about the
11100: user), resource.0.maxtries (or some other part and parameter of a
11101: resource)
1.204 albertel 11102:
11103: =item *
11104:
1.243 albertel 11105: directcondval($number) : get current value of a condition; reads from a state
11106: string
1.204 albertel 11107:
11108: =item *
11109:
1.243 albertel 11110: condval($condidx) : value of condition index based on state
1.204 albertel 11111:
11112: =item *
11113:
1.243 albertel 11114: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11115: resource's metadata, $what should be either a specific key, or either
11116: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11117: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11118:
11119: this function automatically caches all requests
1.191 harris41 11120:
11121: =item *
11122:
1.243 albertel 11123: metadata_query($query,$custom,$customshow) : make a metadata query against the
11124: network of library servers; returns file handle of where SQL and regex results
11125: will be stored for query
1.191 harris41 11126:
11127: =item *
11128:
1.243 albertel 11129: symbread($filename) : return symbolic list entry (filename argument optional);
11130: returns the data handle
1.191 harris41 11131:
11132: =item *
11133:
1.243 albertel 11134: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11135: a possible symb for the URL in $thisfn, and if is an encryypted
11136: resource that the user accessed using /enc/ returns a 1 on success, 0
11137: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11138: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11139:
1.191 harris41 11140:
11141: =item *
11142:
1.243 albertel 11143: symbclean($symb) : removes versions numbers from a symb, returns the
11144: cleaned symb
1.191 harris41 11145:
11146: =item *
11147:
1.243 albertel 11148: is_on_map($uri) : checks if the $uri is somewhere on the current
11149: course map, user must be in a course for it to work.
1.191 harris41 11150:
11151: =item *
11152:
1.243 albertel 11153: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11154:
11155: =item *
11156:
1.243 albertel 11157: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11158: a random seed, all arguments are optional, if they aren't sent it uses the
11159: environment to derive them. Note: if symb isn't sent and it can't get one
11160: from &symbread it will use the current time as its return value
1.191 harris41 11161:
11162: =item *
11163:
1.243 albertel 11164: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11165: unfakeable, receipt
1.191 harris41 11166:
11167: =item *
11168:
1.620 albertel 11169: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11170:
11171: =item *
11172:
1.243 albertel 11173: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11174:
11175: =item *
11176:
1.243 albertel 11177: 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 11178:
11179: =item *
11180:
1.243 albertel 11181: 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 11182:
11183: =item *
11184:
1.243 albertel 11185: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11186:
11187: =item *
11188:
1.243 albertel 11189: devalidate($symb) : devalidate temporary spreadsheet calculations,
11190: forcing spreadsheet to reevaluate the resource scores next time.
11191:
11192: =back
11193:
11194: =head2 Storing/Retreiving Data
11195:
11196: =over 4
1.191 harris41 11197:
11198: =item *
11199:
1.243 albertel 11200: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11201: for this url; hashref needs to be given and should be a \%hashname; the
11202: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11203: be derived from the env
1.191 harris41 11204:
11205: =item *
11206:
1.243 albertel 11207: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11208: uses critical subroutine
1.191 harris41 11209:
11210: =item *
11211:
1.243 albertel 11212: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11213: all args are optional
1.191 harris41 11214:
11215: =item *
11216:
1.717 albertel 11217: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11218: dumps the complete (or key matching regexp) namespace into a hash
11219: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11220: normally &store()ed into
11221:
11222: $range should be either an integer '100' (give me the first 100
11223: matching records)
11224: or be two integers sperated by a - with no spaces
11225: '30-50' (give me the 30th through the 50th matching
11226: records)
11227:
11228:
11229: =item *
11230:
11231: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11232: replaces a &store() version of data with a replacement set of data
11233: for a particular resource in a namespace passed in the $storehash hash
11234: reference
11235:
11236: =item *
11237:
1.243 albertel 11238: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11239: works very similar to store/cstore, but all data is stored in a
11240: temporary location and can be reset using tmpreset, $storehash should
11241: be a hash reference, returns nothing on success
1.191 harris41 11242:
11243: =item *
11244:
1.243 albertel 11245: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11246: similar to restore, but all data is stored in a temporary location and
11247: can be reset using tmpreset. Returns a hash of values on success,
11248: error string otherwise.
1.191 harris41 11249:
11250: =item *
11251:
1.243 albertel 11252: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11253: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11254:
11255: =item *
11256:
1.243 albertel 11257: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11258: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11259:
11260: =item *
11261:
1.243 albertel 11262: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11263: namesp ($udom and $uname are optional)
1.191 harris41 11264:
11265: =item *
11266:
1.702 albertel 11267: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11268: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11269: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11270:
1.702 albertel 11271: $range should be either an integer '100' (give me the first 100
11272: matching records)
11273: or be two integers sperated by a - with no spaces
11274: '30-50' (give me the 30th through the 50th matching
11275: records)
1.449 matthew 11276: =item *
11277:
11278: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11279: $store can be a scalar, an array reference, or if the amount to be
11280: incremented is > 1, a hash reference.
11281:
11282: ($udom and $uname are optional)
1.191 harris41 11283:
11284: =item *
11285:
1.243 albertel 11286: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11287: ($udom and $uname are optional)
1.191 harris41 11288:
11289: =item *
11290:
1.243 albertel 11291: cput($namespace,$storehash,$udom,$uname) : critical put
11292: ($udom and $uname are optional)
1.191 harris41 11293:
11294: =item *
11295:
1.748 albertel 11296: newput($namespace,$storehash,$udom,$uname) :
11297:
11298: Attempts to store the items in the $storehash, but only if they don't
11299: currently exist, if this succeeds you can be certain that you have
11300: successfully created a new key value pair in the $namespace db.
11301:
11302:
11303: Args:
11304: $namespace: name of database to store values to
11305: $storehash: hashref to store to the db
11306: $udom: (optional) domain of user containing the db
11307: $uname: (optional) name of user caontaining the db
11308:
11309: Returns:
11310: 'ok' -> succeeded in storing all keys of $storehash
11311: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11312: least <key> already existed in the db (other
11313: requested keys may also already exist)
1.967 bisitz 11314: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11315: 'con_lost' -> unable to contact request server
11316: 'refused' -> action was not allowed by remote machine
11317:
11318:
11319: =item *
11320:
1.243 albertel 11321: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11322: reference filled in from namesp (encrypts the return communication)
11323: ($udom and $uname are optional)
1.191 harris41 11324:
11325: =item *
11326:
1.243 albertel 11327: log($udom,$name,$home,$message) : write to permanent log for user; use
11328: critical subroutine
11329:
1.806 raeburn 11330: =item *
11331:
1.860 raeburn 11332: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11333: array reference filled in from namespace found in domain level on either
11334: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11335:
11336: =item *
11337:
1.860 raeburn 11338: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11339: domain level either on specified domain server ($uhome) or primary domain
11340: server ($udom and $uhome are optional)
1.806 raeburn 11341:
1.943 raeburn 11342: =item *
11343:
11344: get_domain_defaults($target_domain) : returns hash with defaults for
11345: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11346: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11347: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11348: Values are retrieved from cache (if current), or from domain's configuration.db
11349: (if available), or lastly from values in lonTabs/dns_domain,tab,
11350: or lonTabs/domain.tab.
11351:
11352: %domdefaults = &get_auth_defaults($target_domain);
11353:
1.243 albertel 11354: =back
11355:
11356: =head2 Network Status Functions
11357:
11358: =over 4
1.191 harris41 11359:
11360: =item *
11361:
11362: dirlist($uri) : return directory list based on URI
11363:
11364: =item *
11365:
1.243 albertel 11366: spareserver() : find server with least workload from spare.tab
11367:
1.986 foxr 11368:
11369: =item *
11370:
11371: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11372: if there is no corresponding loncapa host.
11373:
1.243 albertel 11374: =back
11375:
1.986 foxr 11376:
1.243 albertel 11377: =head2 Apache Request
11378:
11379: =over 4
1.191 harris41 11380:
11381: =item *
11382:
1.243 albertel 11383: ssi($url,%hash) : server side include, does a complete request cycle on url to
11384: localhost, posts hash
11385:
11386: =back
11387:
11388: =head2 Data to String to Data
11389:
11390: =over 4
1.191 harris41 11391:
11392: =item *
11393:
1.243 albertel 11394: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11395: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11396:
11397: =item *
11398:
1.243 albertel 11399: hashref2str($hashref) : convert a hashref into a string complete with
11400: escaping and '=' and '&' separators, supports elements that are
11401: arrayrefs and hashrefs
1.191 harris41 11402:
11403: =item *
11404:
1.243 albertel 11405: arrayref2str($arrayref) : convert an arrayref into a string complete
11406: with escaping and '&' separators, supports elements that are arrayrefs
11407: and hashrefs
1.191 harris41 11408:
11409: =item *
11410:
1.243 albertel 11411: str2hash($string) : convert string to hash using unescaping and
11412: splitting on '=' and '&', supports elements that are arrayrefs and
11413: hashrefs
1.191 harris41 11414:
11415: =item *
11416:
1.243 albertel 11417: str2array($string) : convert string to hash using unescaping and
11418: splitting on '&', supports elements that are arrayrefs and hashrefs
11419:
11420: =back
11421:
11422: =head2 Logging Routines
11423:
11424: =over 4
11425:
11426: These routines allow one to make log messages in the lonnet.log and
11427: lonnet.perm logfiles.
1.191 harris41 11428:
11429: =item *
11430:
1.243 albertel 11431: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11432:
11433: =item *
11434:
1.243 albertel 11435: logthis() : append message to the normal lonnet.log file, it gets
11436: preiodically rolled over and deleted.
1.191 harris41 11437:
11438: =item *
11439:
1.243 albertel 11440: logperm() : append a permanent message to lonnet.perm.log, this log
11441: file never gets deleted by any automated portion of the system, only
11442: messages of critical importance should go in here.
11443:
11444: =back
11445:
11446: =head2 General File Helper Routines
11447:
11448: =over 4
1.191 harris41 11449:
11450: =item *
11451:
1.481 raeburn 11452: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11453: (a) files in /uploaded
11454: (i) If a local copy of the file exists -
11455: compares modification date of local copy with last-modified date for
11456: definitive version stored on home server for course. If local copy is
11457: stale, requests a new version from the home server and stores it.
11458: If the original has been removed from the home server, then local copy
11459: is unlinked.
11460: (ii) If local copy does not exist -
11461: requests the file from the home server and stores it.
11462:
11463: If $caller is 'uploadrep':
11464: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11465: for request for files originally uploaded via DOCS.
11466: - returns 'ok' if fresh local copy now available, -1 otherwise.
11467:
11468: Otherwise:
11469: This indicates a call from the content generation phase of the request.
11470: - returns the entire contents of the file or -1.
11471:
11472: (b) files in /res
11473: - returns the entire contents of a file or -1;
11474: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11475:
1.712 albertel 11476:
11477: =item *
11478:
11479: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11480: reference
11481:
11482: returns either a stat() list of data about the file or an empty list
11483: if the file doesn't exist or couldn't find out about it (connection
11484: problems or user unknown)
11485:
1.191 harris41 11486: =item *
11487:
1.243 albertel 11488: filelocation($dir,$file) : returns file system location of a file
11489: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11490: directory that relative $file lookups are to looked in ($dir of /a/dir
11491: and a file of ../bob will become /a/bob)
1.191 harris41 11492:
11493: =item *
11494:
11495: hreflocation($dir,$file) : returns file system location or a URL; same as
11496: filelocation except for hrefs
11497:
11498: =item *
11499:
11500: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11501:
1.243 albertel 11502: =back
11503:
1.608 albertel 11504: =head2 Usererfile file routines (/uploaded*)
11505:
11506: =over 4
11507:
11508: =item *
11509:
11510: userfileupload(): main rotine for putting a file in a user or course's
11511: filespace, arguments are,
11512:
1.620 albertel 11513: formname - required - this is the name of the element in $env where the
1.608 albertel 11514: filename, and the contents of the file to create/modifed exist
1.620 albertel 11515: the filename is in $env{'form.'.$formname.'.filename'} and the
11516: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 11517: context - if coursedoc, store the file in the course of the active role
11518: of the current user;
11519: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11520: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11521: subdir - required - subdirectory to put the file in under ../userfiles/
11522: if undefined, it will be placed in "unknown"
11523:
11524: (This routine calls clean_filename() to remove any dangerous
11525: characters from the filename, and then calls finuserfileupload() to
11526: complete the transaction)
11527:
11528: returns either the url of the uploaded file (/uploaded/....) if successful
11529: and /adm/notfound.html if unsuccessful
11530:
11531: =item *
11532:
11533: clean_filename(): routine for cleaing a filename up for storage in
11534: userfile space, argument is:
11535:
11536: filename - proposed filename
11537:
11538: returns: the new clean filename
11539:
11540: =item *
11541:
1.1090 raeburn 11542: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11543: userspace, probably shouldn't be called directly
11544:
11545: docuname: username or courseid of destination for the file
11546: docudom: domain of user/course of destination for the file
11547: formname: same as for userfileupload()
1.1090 raeburn 11548: fname: filename (including subdirectories) for the file
11549: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11550: allfiles: reference to hash used to store objects found by parser
11551: codebase: reference to hash used for codebases of java objects found by parser
11552: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11553: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11554: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11555: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11556: context: if 'overwrite', will move the uploaded file from its temporary location to
11557: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 11558: mimetype: reference to scalar to accommodate mime type determined
11559: from File::MMagic if $parser = parse.
1.608 albertel 11560:
11561: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 11562: and /adm/notfound.html if unsuccessful (or an error message if context
11563: was 'overwrite').
11564:
1.608 albertel 11565:
11566: =item *
11567:
11568: renameuserfile(): renames an existing userfile to a new name
11569:
11570: Args:
11571: docuname: username or courseid of destination for the file
11572: docudom: domain of user/course of destination for the file
11573: old: current file name (including any subdirs under userfiles)
11574: new: desired file name (including any subdirs under userfiles)
11575:
11576: =item *
11577:
11578: mkdiruserfile(): creates a directory is a userfiles dir
11579:
11580: Args:
11581: docuname: username or courseid of destination for the file
11582: docudom: domain of user/course of destination for the file
11583: dir: dir to create (including any subdirs under userfiles)
11584:
11585: =item *
11586:
11587: removeuserfile(): removes a file that exists in userfiles
11588:
11589: Args:
11590: docuname: username or courseid of destination for the file
11591: docudom: domain of user/course of destination for the file
11592: fname: filname to delete (including any subdirs under userfiles)
11593:
11594: =item *
11595:
11596: removeuploadedurl(): convience function for removeuserfile()
11597:
11598: Args:
11599: url: a full /uploaded/... url to delete
11600:
1.747 albertel 11601: =item *
11602:
11603: get_portfile_permissions():
11604: Args:
11605: domain: domain of user or course contain the portfolio files
11606: user: name of user or num of course contain the portfolio files
11607: Returns:
11608: hashref of a dump of the proper file_permissions.db
11609:
11610:
11611: =item *
11612:
11613: get_access_controls():
11614:
11615: Args:
11616: current_permissions: the hash ref returned from get_portfile_permissions()
11617: group: (optional) the group you want the files associated with
11618: file: (optional) the file you want access info on
11619:
11620: Returns:
1.749 raeburn 11621: a hash (keys are file names) of hashes containing
11622: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11623: values are XML containing access control settings (see below)
1.747 albertel 11624:
11625: Internal notes:
11626:
1.749 raeburn 11627: access controls are stored in file_permissions.db as key=value pairs.
11628: key -> path to file/file_name\0uniqueID:scope_end_start
11629: where scope -> public,guest,course,group,domains or users.
11630: end -> UNIX time for end of access (0 -> no end date)
11631: start -> UNIX time for start of access
11632:
11633: value -> XML description of access control
11634: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11635: <start></start>
11636: <end></end>
11637:
11638: <password></password> for scope type = guest
11639:
11640: <domain></domain> for scope type = course or group
11641: <number></number>
11642: <roles id="">
11643: <role></role>
11644: <access></access>
11645: <section></section>
11646: <group></group>
11647: </roles>
11648:
11649: <dom></dom> for scope type = domains
11650:
11651: <users> for scope type = users
11652: <user>
11653: <uname></uname>
11654: <udom></udom>
11655: </user>
11656: </users>
11657: </scope>
11658:
11659: Access data is also aggregated for each file in an additional key=value pair:
11660: key -> path to file/file_name\0accesscontrol
11661: value -> reference to hash
11662: hash contains key = value pairs
11663: where key = uniqueID:scope_end_start
11664: value = UNIX time record was last updated
11665:
11666: Used to improve speed of look-ups of access controls for each file.
11667:
11668: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11669:
11670: modify_access_controls():
11671:
11672: Modifies access controls for a portfolio file
11673: Args
11674: 1. file name
11675: 2. reference to hash of required changes,
11676: 3. domain
11677: 4. username
11678: where domain,username are the domain of the portfolio owner
11679: (either a user or a course)
11680:
11681: Returns:
11682: 1. result of additions or updates ('ok' or 'error', with error message).
11683: 2. result of deletions ('ok' or 'error', with error message).
11684: 3. reference to hash of any new or updated access controls.
11685: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11686: key = integer (inbound ID)
11687: value = uniqueID
1.747 albertel 11688:
1.608 albertel 11689: =back
11690:
1.243 albertel 11691: =head2 HTTP Helper Routines
11692:
11693: =over 4
11694:
1.191 harris41 11695: =item *
11696:
11697: escape() : unpack non-word characters into CGI-compatible hex codes
11698:
11699: =item *
11700:
11701: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11702:
1.243 albertel 11703: =back
11704:
11705: =head1 PRIVATE SUBROUTINES
11706:
11707: =head2 Underlying communication routines (Shouldn't call)
11708:
11709: =over 4
11710:
11711: =item *
11712:
11713: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11714:
11715: =item *
11716:
11717: reply() : uses subreply to send a message to remote machine, logs all failures
11718:
11719: =item *
11720:
11721: critical() : passes a critical message to another server; if cannot
11722: get through then place message in connection buffer directory and
11723: returns con_delayed, if incapable of saving message, returns
11724: con_failed
11725:
11726: =item *
11727:
11728: reconlonc() : tries to reconnect lonc client processes.
11729:
11730: =back
11731:
11732: =head2 Resource Access Logging
11733:
11734: =over 4
11735:
11736: =item *
11737:
11738: flushcourselogs() : flush (save) buffer logs and access logs
11739:
11740: =item *
11741:
11742: courselog($what) : save message for course in hash
11743:
11744: =item *
11745:
11746: courseacclog($what) : save message for course using &courselog(). Perform
11747: special processing for specific resource types (problems, exams, quizzes, etc).
11748:
1.191 harris41 11749: =item *
11750:
11751: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11752: as a PerlChildExitHandler
1.243 albertel 11753:
11754: =back
11755:
11756: =head2 Other
11757:
11758: =over 4
11759:
11760: =item *
11761:
11762: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11763:
11764: =back
11765:
11766: =cut
1.877 foxr 11767:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>