Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.4.30
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.4.30! raeburn 4: # $Id: lonnet.pm,v 1.1056.4.29 2011/08/16 20:11:23 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1056.4.5 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.1056.4.13 raeburn 98: use File::Copy;
1.676 albertel 99:
1.195 www 100: my $readit;
1.550 foxr 101: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 102:
1.619 albertel 103: require Exporter;
104:
105: our @ISA = qw (Exporter);
106: our @EXPORT = qw(%env);
107:
1.449 matthew 108:
1.1 albertel 109: # --------------------------------------------------------------------- Logging
1.729 www 110: {
111: my $logid;
112: sub instructor_log {
1.957 raeburn 113: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
114: if (($cnum eq '') || ($cdom eq '')) {
115: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
116: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
117: }
1.729 www 118: $logid++;
1.957 raeburn 119: my $now = time();
120: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 121: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 122: { $id => {
123: 'exe_uname' => $env{'user.name'},
124: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 125: 'exe_time' => $now,
1.730 www 126: 'exe_ip' => $ENV{'REMOTE_ADDR'},
127: 'delflag' => $delflag,
128: 'logentry' => $storehash,
129: 'uname' => $uname,
130: 'udom' => $udom,
131: }
1.957 raeburn 132: },$cdom,$cnum);
1.729 www 133: }
134: }
1.1 albertel 135:
1.163 harris41 136: sub logtouch {
137: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 138: unless (-e "$execdir/logs/lonnet.log") {
139: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 140: close $fh;
141: }
142: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
143: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
144: }
145:
1.1 albertel 146: sub logthis {
147: my $message=shift;
148: my $execdir=$perlvar{'lonDaemons'};
149: my $now=time;
150: my $local=localtime($now);
1.448 albertel 151: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 152: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
153: print $fh $logstring;
1.448 albertel 154: close($fh);
155: }
1.1 albertel 156: return 1;
157: }
158:
159: sub logperm {
160: my $message=shift;
161: my $execdir=$perlvar{'lonDaemons'};
162: my $now=time;
163: my $local=localtime($now);
1.448 albertel 164: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
165: print $fh "$now:$message:$local\n";
166: close($fh);
167: }
1.1 albertel 168: return 1;
169: }
170:
1.850 albertel 171: sub create_connection {
1.853 albertel 172: my ($hostname,$lonid) = @_;
1.851 albertel 173: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 174: Type => SOCK_STREAM,
175: Timeout => 10);
176: return 0 if (!$client);
1.890 albertel 177: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 178: my $result = <$client>;
179: chomp($result);
180: return 1 if ($result eq 'done');
181: return 0;
182: }
183:
1.983 raeburn 184: sub get_server_timezone {
185: my ($cnum,$cdom) = @_;
186: my $home=&homeserver($cnum,$cdom);
187: if ($home ne 'no_host') {
188: my $cachetime = 24*3600;
189: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
190: if (defined($cached)) {
191: return $timezone;
192: } else {
193: my $timezone = &reply('servertimezone',$home);
194: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
195: }
196: }
197: }
1.850 albertel 198:
1.1056.4.25 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.1056.4.3 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.1056.4.3 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.1056.4.7 raeburn 249: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 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.1056.4.8 raeburn 257: $ua->timeout(4);
1.1056.4.3 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.1056.4.7 raeburn 265: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3 raeburn 266: $loncaparev = $1;
267: }
268: }
269: } else {
270: $loncaparev = $loncaparevs{$lonhost};
271: }
1.1056.4.7 raeburn 272: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 raeburn 273: $loncaparev = $1;
274: }
275: }
276: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
277: }
278: }
279:
280: sub get_server_homeID {
281: my ($hostname,$ignore_cache,$caller) = @_;
282: unless ($ignore_cache) {
283: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993 raeburn 284: if (defined($cached)) {
1.1056.4.3 raeburn 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: }
1.993 raeburn 298: }
1.1056.4.3 raeburn 299: if ($serverhomeID eq '') {
300: $serverhomeID = $machine_ids[-1];
301: }
302: } else {
303: $serverhomeID = $serverhomeIDs{$hostname};
1.993 raeburn 304: }
1.1056.4.3 raeburn 305: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993 raeburn 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.987 raeburn 638: my ($delthis,$regexp) = @_;
1.56 www 639: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 640: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 641: "Attempt to delete from environment ".$delthis);
642: return 'error';
643: }
1.917 albertel 644: my $opened = open(my $env_file,'+<',$env{'user.environment'});
645: if ($opened
1.915 albertel 646: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 647: &&
648: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
649: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 650: foreach my $key (keys(%disk_env)) {
1.987 raeburn 651: if ($regexp) {
652: if ($key=~/^$delthis/) {
653: delete($env{$key});
654: delete($disk_env{$key});
655: }
656: } else {
657: if ($key=~/^\Q$delthis\E/) {
658: delete($env{$key});
659: delete($disk_env{$key});
660: }
661: }
1.448 albertel 662: }
1.783 albertel 663: untie(%disk_env);
1.5 www 664: }
665: return 'ok';
1.369 albertel 666: }
667:
1.790 albertel 668: sub get_env_multiple {
669: my ($name) = @_;
670: my @values;
671: if (defined($env{$name})) {
672: # exists is it an array
673: if (ref($env{$name})) {
674: @values=@{ $env{$name} };
675: } else {
676: $values[0]=$env{$name};
677: }
678: }
679: return(@values);
680: }
681:
1.958 www 682: # ------------------------------------------------------------------- Locking
683:
684: sub set_lock {
685: my ($text)=@_;
686: $locknum++;
687: my $id=$$.'-'.$locknum;
688: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
689: 'session.lock.'.$id => $text});
690: return $id;
691: }
692:
693: sub get_locks {
694: my $num=0;
695: my %texts=();
696: foreach my $lock (split(/\,/,$env{'session.locks'})) {
697: if ($lock=~/\w/) {
698: $num++;
699: $texts{$lock}=$env{'session.lock.'.$lock};
700: }
701: }
702: return ($num,%texts);
703: }
704:
705: sub remove_lock {
706: my ($id)=@_;
707: my $newlocks='';
708: foreach my $lock (split(/\,/,$env{'session.locks'})) {
709: if (($lock=~/\w/) && ($lock ne $id)) {
710: $newlocks.=','.$lock;
711: }
712: }
713: &appenv({'session.locks' => $newlocks});
714: &delenv('session.lock.'.$id);
715: }
716:
717: sub remove_all_locks {
718: my $activelocks=$env{'session.locks'};
719: foreach my $lock (split(/\,/,$env{'session.locks'})) {
720: if ($lock=~/\w/) {
721: &remove_lock($lock);
722: }
723: }
724: }
725:
726:
1.369 albertel 727: # ------------------------------------------ Find out current server userload
728: sub userload {
729: my $numusers=0;
730: {
731: opendir(LONIDS,$perlvar{'lonIDsDir'});
732: my $filename;
733: my $curtime=time;
734: while ($filename=readdir(LONIDS)) {
1.925 albertel 735: next if ($filename eq '.' || $filename eq '..');
736: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 737: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 738: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 739: }
740: closedir(LONIDS);
741: }
742: my $userloadpercent=0;
743: my $maxuserload=$perlvar{'lonUserLoadLim'};
744: if ($maxuserload) {
1.371 albertel 745: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 746: }
1.372 albertel 747: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 748: return $userloadpercent;
1.283 www 749: }
750:
751: # ------------------------------------------ Fight off request when overloaded
752:
753: sub overloaderror {
754: my ($r,$checkserver)=@_;
755: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
756: my $loadavg;
757: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 758: open(my $loadfile,'/proc/loadavg');
1.283 www 759: $loadavg=<$loadfile>;
760: $loadavg =~ s/\s.*//g;
1.285 matthew 761: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 762: close($loadfile);
1.283 www 763: } else {
764: $loadavg=&reply('load',$checkserver);
765: }
1.285 matthew 766: my $overload=$loadavg-100;
1.283 www 767: if ($overload>0) {
1.285 matthew 768: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 769: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 770: return 413;
1.283 www 771: }
772: return '';
1.5 www 773: }
1.1 albertel 774:
775: # ------------------------------ Find server with least workload from spare.tab
1.11 www 776:
1.1 albertel 777: sub spareserver {
1.1056.4.23 raeburn 778: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 779: my $spare_server;
1.370 albertel 780: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 781: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
782: : $userloadpercent;
1.1056.4.8 raeburn 783: my ($uint_dom,$remotesessions);
1.1056.4.23 raeburn 784: if (($udom ne '') && (&domain($udom) ne '')) {
785: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1.1056.4.8 raeburn 786: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.23 raeburn 787: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
1.1056.4.8 raeburn 788: $remotesessions = $udomdefaults{'remotesessions'};
789: }
1.784 albertel 790: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8 raeburn 791: if ($uint_dom) {
1.1056.4.23 raeburn 792: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
793: $try_server));
1.1056.4.8 raeburn 794: }
1.784 albertel 795: ($spare_server, $lowest_load) =
796: &compare_server_load($try_server, $spare_server, $lowest_load);
797: }
798:
799: my $found_server = ($spare_server ne '' && $lowest_load < 100);
800:
801: if (!$found_server) {
802: foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8 raeburn 803: if ($uint_dom) {
1.1056.4.23 raeburn 804: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
805: $try_server));
1.1056.4.8 raeburn 806: }
1.784 albertel 807: ($spare_server, $lowest_load) =
808: &compare_server_load($try_server, $spare_server, $lowest_load);
809: }
810: }
811:
812: if (!$want_server_name) {
1.968 raeburn 813: my $protocol = 'http';
814: if ($protocol{$spare_server} eq 'https') {
815: $protocol = $protocol{$spare_server};
816: }
1.1001 raeburn 817: if (defined($spare_server)) {
818: my $hostname = &hostname($spare_server);
1.1056.4.8 raeburn 819: if (defined($hostname)) {
1.1001 raeburn 820: $spare_server = $protocol.'://'.$hostname;
821: }
822: }
1.784 albertel 823: }
824: return $spare_server;
825: }
826:
827: sub compare_server_load {
828: my ($try_server, $spare_server, $lowest_load) = @_;
829:
830: my $loadans = &reply('load', $try_server);
831: my $userloadans = &reply('userload',$try_server);
832:
833: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.29 raeburn 834: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 835: }
836:
837: my $load;
838: if ($loadans =~ /\d/) {
839: if ($userloadans =~ /\d/) {
840: #both are numbers, pick the bigger one
841: $load = ($loadans > $userloadans) ? $loadans
842: : $userloadans;
1.411 albertel 843: } else {
1.784 albertel 844: $load = $loadans;
1.411 albertel 845: }
1.784 albertel 846: } else {
847: $load = $userloadans;
848: }
849:
850: if (($load =~ /\d/) && ($load < $lowest_load)) {
851: $spare_server = $try_server;
852: $lowest_load = $load;
1.370 albertel 853: }
1.784 albertel 854: return ($spare_server,$lowest_load);
1.202 matthew 855: }
1.914 albertel 856:
857: # --------------------------- ask offload servers if user already has a session
858: sub find_existing_session {
859: my ($udom,$uname) = @_;
860: foreach my $try_server (@{ $spareid{'primary'} },
861: @{ $spareid{'default'} }) {
862: return $try_server if (&has_user_session($try_server, $udom, $uname));
863: }
864: return;
865: }
866:
867: # -------------------------------- ask if server already has a session for user
868: sub has_user_session {
869: my ($lonid,$udom,$uname) = @_;
870: my $result = &reply(join(':','userhassession',
871: map {&escape($_)} ($udom,$uname)),$lonid);
872: return 1 if ($result eq 'ok');
873:
874: return 0;
875: }
876:
1.1056.4.3 raeburn 877: # --------- determine least loaded server in a user's domain which allows login
878:
879: sub choose_server {
880: my ($udom) = @_;
881: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
882: my %servers = &get_servers($udom);
883: my $lowest_load = 30000;
884: my ($login_host,$hostname);
885: foreach my $lonhost (keys(%servers)) {
886: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
887: if ($loginvia eq '') {
888: ($login_host, $lowest_load) =
889: &compare_server_load($lonhost, $login_host, $lowest_load);
890: }
891: }
892: if ($login_host ne '') {
893: $hostname = $servers{$login_host};
894: }
895: return ($login_host,$hostname);
896: }
897:
1.202 matthew 898: # --------------------------------------------- Try to change a user's password
899:
900: sub changepass {
1.799 raeburn 901: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 902: $currentpass = &escape($currentpass);
903: $newpass = &escape($newpass);
1.1030 raeburn 904: my $lonhost = $perlvar{'lonHostID'};
905: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 906: $server);
907: if (! $answer) {
908: &logthis("No reply on password change request to $server ".
909: "by $uname in domain $udom.");
910: } elsif ($answer =~ "^ok") {
911: &logthis("$uname in $udom successfully changed their password ".
912: "on $server.");
913: } elsif ($answer =~ "^pwchange_failure") {
914: &logthis("$uname in $udom was unable to change their password ".
915: "on $server. The action was blocked by either lcpasswd ".
916: "or pwchange");
917: } elsif ($answer =~ "^non_authorized") {
918: &logthis("$uname in $udom did not get their password correct when ".
919: "attempting to change it on $server.");
920: } elsif ($answer =~ "^auth_mode_error") {
921: &logthis("$uname in $udom attempted to change their password despite ".
922: "not being locally or internally authenticated on $server.");
923: } elsif ($answer =~ "^unknown_user") {
924: &logthis("$uname in $udom attempted to change their password ".
925: "on $server but were unable to because $server is not ".
926: "their home server.");
927: } elsif ($answer =~ "^refused") {
928: &logthis("$server refused to change $uname in $udom password because ".
929: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 930: } elsif ($answer =~ "invalid_client") {
931: &logthis("$server refused to change $uname in $udom password because ".
932: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 933: }
934: return $answer;
1.1 albertel 935: }
936:
1.169 harris41 937: # ----------------------- Try to determine user's current authentication scheme
938:
939: sub queryauthenticate {
940: my ($uname,$udom)=@_;
1.456 albertel 941: my $uhome=&homeserver($uname,$udom);
942: if (!$uhome) {
943: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
944: return 'no_host';
945: }
946: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
947: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
948: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 949: }
1.456 albertel 950: return $answer;
1.169 harris41 951: }
952:
1.1 albertel 953: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 954:
1.1 albertel 955: sub authenticate {
1.1056.4.3 raeburn 956: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 957: $upass=&escape($upass);
958: $uname= &LONCAPA::clean_username($uname);
1.836 www 959: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 960: my $newhome;
1.836 www 961: if ((!$uhome) || ($uhome eq 'no_host')) {
962: # Maybe the machine was offline and only re-appeared again recently?
963: &reconlonc();
964: # One more
1.952 raeburn 965: $uhome=&homeserver($uname,$udom,1);
966: if (($uhome eq 'no_host') && $checkdefauth) {
967: if (defined(&domain($udom,'primary'))) {
968: $newhome=&domain($udom,'primary');
969: }
970: if ($newhome ne '') {
971: $uhome = $newhome;
972: }
973: }
1.836 www 974: if ((!$uhome) || ($uhome eq 'no_host')) {
975: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 976: return 'no_host';
977: }
1.1 albertel 978: }
1.1056.4.3 raeburn 979: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 980: if ($answer eq 'authorized') {
1.952 raeburn 981: if ($newhome) {
982: &logthis("User $uname at $udom authorized by $uhome, but needs account");
983: return 'no_account_on_host';
984: } else {
985: &logthis("User $uname at $udom authorized by $uhome");
986: return $uhome;
987: }
1.471 albertel 988: }
989: if ($answer eq 'non_authorized') {
990: &logthis("User $uname at $udom rejected by $uhome");
991: return 'no_host';
1.9 www 992: }
1.471 albertel 993: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 994: return 'no_host';
995: }
996:
1.1056.4.3 raeburn 997: sub can_host_session {
998: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
999: my $canhost = 1;
1000: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1001: if (ref($remotesessions) eq 'HASH') {
1002: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1003: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1004: $canhost = 0;
1005: } else {
1006: $canhost = 1;
1007: }
1008: }
1009: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1010: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1011: $canhost = 1;
1012: } else {
1013: $canhost = 0;
1014: }
1015: }
1016: if ($canhost) {
1017: if ($remotesessions->{'version'} ne '') {
1018: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1019: if ($reqmajor ne '' && $reqminor ne '') {
1020: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1021: my $major = $1;
1022: my $minor = $2;
1023: if (($major < $reqmajor ) ||
1024: (($major == $reqmajor) && ($minor < $reqminor))) {
1025: $canhost = 0;
1026: }
1027: } else {
1028: $canhost = 0;
1029: }
1030: }
1031: }
1032: }
1033: }
1034: if ($canhost) {
1035: if (ref($hostedsessions) eq 'HASH') {
1.1056.4.28 raeburn 1036: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1037: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.3 raeburn 1038: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1056.4.28 raeburn 1039: if (($uint_dom ne '') &&
1040: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1056.4.3 raeburn 1041: $canhost = 0;
1042: } else {
1043: $canhost = 1;
1044: }
1045: }
1046: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1056.4.28 raeburn 1047: if (($uint_dom ne '') &&
1048: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1056.4.3 raeburn 1049: $canhost = 1;
1050: } else {
1051: $canhost = 0;
1052: }
1053: }
1054: }
1055: }
1056: return $canhost;
1057: }
1058:
1.1056.4.8 raeburn 1059: sub spare_can_host {
1060: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1061: my $canhost=1;
1062: my @intdoms;
1063: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1064: if (ref($internet_names) eq 'ARRAY') {
1065: @intdoms = @{$internet_names};
1066: }
1067: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1068: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1069: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1070: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1071: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1072: $canhost = &can_host_session($udom,$try_server,$remoterev,
1073: $remotesessions,
1074: $defdomdefaults{'hostedsessions'});
1075: }
1076: return $canhost;
1077: }
1078:
1.1 albertel 1079: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1080:
1.599 albertel 1081: my %homecache;
1.1 albertel 1082: sub homeserver {
1.230 stredwic 1083: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1084: my $index="$uname:$udom";
1.426 albertel 1085:
1.599 albertel 1086: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1087:
1088: my %servers = &get_servers($udom,'library');
1089: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1090: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1091: exists($badServerCache{$tryserver}));
1.841 albertel 1092:
1093: my $answer=reply("home:$udom:$uname",$tryserver);
1094: if ($answer eq 'found') {
1095: delete($badServerCache{$tryserver});
1096: return $homecache{$index}=$tryserver;
1097: } elsif ($answer eq 'no_host') {
1098: $badServerCache{$tryserver}=1;
1099: }
1.1 albertel 1100: }
1101: return 'no_host';
1.70 www 1102: }
1103:
1104: # ------------------------------------- Find the usernames behind a list of IDs
1105:
1106: sub idget {
1107: my ($udom,@ids)=@_;
1108: my %returnhash=();
1109:
1.841 albertel 1110: my %servers = &get_servers($udom,'library');
1111: foreach my $tryserver (keys(%servers)) {
1112: my $idlist=join('&',@ids);
1113: $idlist=~tr/A-Z/a-z/;
1114: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1115: my @answer=();
1116: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1117: @answer=split(/\&/,$reply);
1118: } ;
1119: my $i;
1120: for ($i=0;$i<=$#ids;$i++) {
1121: if ($answer[$i]) {
1122: $returnhash{$ids[$i]}=$answer[$i];
1123: }
1124: }
1125: }
1.70 www 1126: return %returnhash;
1127: }
1128:
1129: # ------------------------------------- Find the IDs behind a list of usernames
1130:
1131: sub idrget {
1132: my ($udom,@unames)=@_;
1133: my %returnhash=();
1.800 albertel 1134: foreach my $uname (@unames) {
1135: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1136: }
1.70 www 1137: return %returnhash;
1138: }
1139:
1140: # ------------------------------- Store away a list of names and associated IDs
1141:
1142: sub idput {
1143: my ($udom,%ids)=@_;
1144: my %servers=();
1.800 albertel 1145: foreach my $uname (keys(%ids)) {
1146: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1147: my $uhom=&homeserver($uname,$udom);
1.70 www 1148: if ($uhom ne 'no_host') {
1.800 albertel 1149: my $id=&escape($ids{$uname});
1.70 www 1150: $id=~tr/A-Z/a-z/;
1.800 albertel 1151: my $esc_unam=&escape($uname);
1.70 www 1152: if ($servers{$uhom}) {
1.800 albertel 1153: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1154: } else {
1.800 albertel 1155: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1156: }
1157: }
1.191 harris41 1158: }
1.800 albertel 1159: foreach my $server (keys(%servers)) {
1160: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1161: }
1.344 www 1162: }
1163:
1.1023 raeburn 1164: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1165: sub dump_dom {
1.1023 raeburn 1166: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1167: if (!$udom) {
1168: $udom=$env{'user.domain'};
1169: }
1170: my %returnhash;
1.1023 raeburn 1171: if ($udom) {
1172: my $uname = &get_domainconfiguser($udom);
1173: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1174: }
1175: return %returnhash;
1176: }
1177:
1.1023 raeburn 1178: # ------------------------------------------ get items from domain db files
1.806 raeburn 1179:
1180: sub get_dom {
1.860 raeburn 1181: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1182: my $items='';
1183: foreach my $item (@$storearr) {
1184: $items.=&escape($item).'&';
1185: }
1186: $items=~s/\&$//;
1.860 raeburn 1187: if (!$udom) {
1188: $udom=$env{'user.domain'};
1189: if (defined(&domain($udom,'primary'))) {
1190: $uhome=&domain($udom,'primary');
1191: } else {
1.874 albertel 1192: undef($uhome);
1.860 raeburn 1193: }
1194: } else {
1195: if (!$uhome) {
1196: if (defined(&domain($udom,'primary'))) {
1197: $uhome=&domain($udom,'primary');
1198: }
1199: }
1200: }
1201: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1202: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1203: my %returnhash;
1.875 albertel 1204: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1205: return %returnhash;
1206: }
1.806 raeburn 1207: my @pairs=split(/\&/,$rep);
1208: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1209: return @pairs;
1210: }
1211: my $i=0;
1212: foreach my $item (@$storearr) {
1213: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1214: $i++;
1215: }
1216: return %returnhash;
1217: } else {
1.880 banghart 1218: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1219: }
1220: }
1221:
1222: # -------------------------------------------- put items in domain db files
1223:
1224: sub put_dom {
1.860 raeburn 1225: my ($namespace,$storehash,$udom,$uhome)=@_;
1226: if (!$udom) {
1227: $udom=$env{'user.domain'};
1228: if (defined(&domain($udom,'primary'))) {
1229: $uhome=&domain($udom,'primary');
1230: } else {
1.874 albertel 1231: undef($uhome);
1.860 raeburn 1232: }
1233: } else {
1234: if (!$uhome) {
1235: if (defined(&domain($udom,'primary'))) {
1236: $uhome=&domain($udom,'primary');
1237: }
1238: }
1239: }
1240: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1241: my $items='';
1242: foreach my $item (keys(%$storehash)) {
1243: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1244: }
1245: $items=~s/\&$//;
1246: return &reply("putdom:$udom:$namespace:$items",$uhome);
1247: } else {
1.860 raeburn 1248: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1249: }
1250: }
1251:
1.1023 raeburn 1252: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1253: sub newput_dom {
1.1023 raeburn 1254: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1255: my $result;
1256: if (!$udom) {
1257: $udom=$env{'user.domain'};
1258: }
1.1023 raeburn 1259: if ($udom) {
1260: my $uname = &get_domainconfiguser($udom);
1261: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1262: }
1263: return $result;
1264: }
1265:
1.1023 raeburn 1266: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1267: sub del_dom {
1.1023 raeburn 1268: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1269: if (ref($storearr) eq 'ARRAY') {
1270: if (!$udom) {
1271: $udom=$env{'user.domain'};
1272: }
1.1023 raeburn 1273: if ($udom) {
1274: my $uname = &get_domainconfiguser($udom);
1275: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1276: }
1277: }
1278: }
1279:
1.1023 raeburn 1280: # ----------------------------------construct domainconfig user for a domain
1281: sub get_domainconfiguser {
1282: my ($udom) = @_;
1283: return $udom.'-domainconfig';
1284: }
1285:
1.837 raeburn 1286: sub retrieve_inst_usertypes {
1287: my ($udom) = @_;
1288: my (%returnhash,@order);
1.989 raeburn 1289: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1290: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1291: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1292: %returnhash = %{$domdefs{'inststatustypes'}};
1293: @order = @{$domdefs{'inststatusorder'}};
1294: } else {
1295: if (defined(&domain($udom,'primary'))) {
1296: my $uhome=&domain($udom,'primary');
1297: my $rep=&reply("inst_usertypes:$udom",$uhome);
1298: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1299: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1300: return (\%returnhash,\@order);
1301: }
1302: my ($hashitems,$orderitems) = split(/:/,$rep);
1303: my @pairs=split(/\&/,$hashitems);
1304: foreach my $item (@pairs) {
1305: my ($key,$value)=split(/=/,$item,2);
1306: $key = &unescape($key);
1307: next if ($key =~ /^error: 2 /);
1308: $returnhash{$key}=&thaw_unescape($value);
1309: }
1310: my @esc_order = split(/\&/,$orderitems);
1311: foreach my $item (@esc_order) {
1312: push(@order,&unescape($item));
1313: }
1314: } else {
1315: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1316: }
1317: }
1318: return (\%returnhash,\@order);
1319: }
1320:
1.868 raeburn 1321: sub is_domainimage {
1322: my ($url) = @_;
1323: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1324: if (&domain($1) ne '') {
1325: return '1';
1326: }
1327: }
1328: return;
1329: }
1330:
1.899 raeburn 1331: sub inst_directory_query {
1332: my ($srch) = @_;
1333: my $udom = $srch->{'srchdomain'};
1334: my %results;
1335: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1336: my $outcome;
1.899 raeburn 1337: if ($homeserver ne '') {
1.904 albertel 1338: my $queryid=&reply("querysend:instdirsearch:".
1339: &escape($srch->{'srchby'}).':'.
1340: &escape($srch->{'srchterm'}).':'.
1341: &escape($srch->{'srchtype'}),$homeserver);
1342: my $host=&hostname($homeserver);
1343: if ($queryid !~/^\Q$host\E\_/) {
1344: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1345: return;
1346: }
1347: my $response = &get_query_reply($queryid);
1348: my $maxtries = 5;
1349: my $tries = 1;
1350: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1351: $response = &get_query_reply($queryid);
1352: $tries ++;
1353: }
1354:
1355: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1356: if ($response eq 'unavailable') {
1357: $outcome = $response;
1358: } else {
1359: $outcome = 'ok';
1360: my @matches = split(/\n/,$response);
1361: foreach my $match (@matches) {
1362: my ($key,$value) = split(/=/,$match);
1363: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1364: }
1.899 raeburn 1365: }
1366: }
1367: }
1.909 raeburn 1368: return ($outcome,%results);
1.899 raeburn 1369: }
1370:
1371: sub usersearch {
1372: my ($srch) = @_;
1373: my $dom = $srch->{'srchdomain'};
1374: my %results;
1375: my %libserv = &all_library();
1376: my $query = 'usersearch';
1377: foreach my $tryserver (keys(%libserv)) {
1378: if (&host_domain($tryserver) eq $dom) {
1379: my $host=&hostname($tryserver);
1380: my $queryid=
1.911 raeburn 1381: &reply("querysend:".&escape($query).':'.
1382: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1383: &escape($srch->{'srchtype'}).':'.
1384: &escape($srch->{'srchterm'}),$tryserver);
1385: if ($queryid !~/^\Q$host\E\_/) {
1386: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1387: next;
1.899 raeburn 1388: }
1389: my $reply = &get_query_reply($queryid);
1390: my $maxtries = 1;
1391: my $tries = 1;
1392: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1393: $reply = &get_query_reply($queryid);
1394: $tries ++;
1395: }
1396: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1397: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1398: } else {
1.911 raeburn 1399: my @matches;
1400: if ($reply =~ /\n/) {
1401: @matches = split(/\n/,$reply);
1402: } else {
1403: @matches = split(/\&/,$reply);
1404: }
1.899 raeburn 1405: foreach my $match (@matches) {
1406: my ($uname,$udom,%userhash);
1.911 raeburn 1407: foreach my $entry (split(/:/,$match)) {
1408: my ($key,$value) =
1409: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1410: $userhash{$key} = $value;
1411: if ($key eq 'username') {
1412: $uname = $value;
1413: } elsif ($key eq 'domain') {
1414: $udom = $value;
1.911 raeburn 1415: }
1.899 raeburn 1416: }
1417: $results{$uname.':'.$udom} = \%userhash;
1418: }
1419: }
1420: }
1421: }
1422: return %results;
1423: }
1424:
1.912 raeburn 1425: sub get_instuser {
1426: my ($udom,$uname,$id) = @_;
1427: my $homeserver = &domain($udom,'primary');
1428: my ($outcome,%results);
1429: if ($homeserver ne '') {
1430: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1431: &escape($id).':'.&escape($udom),$homeserver);
1432: my $host=&hostname($homeserver);
1433: if ($queryid !~/^\Q$host\E\_/) {
1434: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1435: return;
1436: }
1437: my $response = &get_query_reply($queryid);
1438: my $maxtries = 5;
1439: my $tries = 1;
1440: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1441: $response = &get_query_reply($queryid);
1442: $tries ++;
1443: }
1444: if (!&error($response) && $response ne 'refused') {
1445: if ($response eq 'unavailable') {
1446: $outcome = $response;
1447: } else {
1448: $outcome = 'ok';
1449: my @matches = split(/\n/,$response);
1450: foreach my $match (@matches) {
1451: my ($key,$value) = split(/=/,$match);
1452: $results{&unescape($key)} = &thaw_unescape($value);
1453: }
1454: }
1455: }
1456: }
1457: my %userinfo;
1458: if (ref($results{$uname}) eq 'HASH') {
1459: %userinfo = %{$results{$uname}};
1460: }
1461: return ($outcome,%userinfo);
1462: }
1463:
1464: sub inst_rulecheck {
1.923 raeburn 1465: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1466: my %returnhash;
1467: if ($udom ne '') {
1468: if (ref($rules) eq 'ARRAY') {
1469: @{$rules} = map {&escape($_);} (@{$rules});
1470: my $rulestr = join(':',@{$rules});
1471: my $homeserver=&domain($udom,'primary');
1472: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1473: my $response;
1474: if ($item eq 'username') {
1475: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1476: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1477: $homeserver));
1.923 raeburn 1478: } elsif ($item eq 'id') {
1479: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1480: ':'.&escape($id).':'.$rulestr,
1481: $homeserver));
1.945 raeburn 1482: } elsif ($item eq 'selfcreate') {
1483: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1484: &escape($udom).':'.&escape($uname).
1485: ':'.$rulestr,$homeserver));
1.923 raeburn 1486: }
1.912 raeburn 1487: if ($response ne 'refused') {
1488: my @pairs=split(/\&/,$response);
1489: foreach my $item (@pairs) {
1490: my ($key,$value)=split(/=/,$item,2);
1491: $key = &unescape($key);
1492: next if ($key =~ /^error: 2 /);
1493: $returnhash{$key}=&thaw_unescape($value);
1494: }
1495: }
1496: }
1497: }
1498: }
1499: return %returnhash;
1500: }
1501:
1502: sub inst_userrules {
1.923 raeburn 1503: my ($udom,$check) = @_;
1.912 raeburn 1504: my (%ruleshash,@ruleorder);
1505: if ($udom ne '') {
1506: my $homeserver=&domain($udom,'primary');
1507: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1508: my $response;
1509: if ($check eq 'id') {
1510: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1511: $homeserver);
1.943 raeburn 1512: } elsif ($check eq 'email') {
1513: $response=&reply('instemailrules:'.&escape($udom),
1514: $homeserver);
1.923 raeburn 1515: } else {
1516: $response=&reply('instuserrules:'.&escape($udom),
1517: $homeserver);
1518: }
1.912 raeburn 1519: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1520: ($response ne 'unknown_cmd') &&
1.912 raeburn 1521: ($response ne 'no_such_host')) {
1522: my ($hashitems,$orderitems) = split(/:/,$response);
1523: my @pairs=split(/\&/,$hashitems);
1524: foreach my $item (@pairs) {
1525: my ($key,$value)=split(/=/,$item,2);
1526: $key = &unescape($key);
1527: next if ($key =~ /^error: 2 /);
1528: $ruleshash{$key}=&thaw_unescape($value);
1529: }
1530: my @esc_order = split(/\&/,$orderitems);
1531: foreach my $item (@esc_order) {
1532: push(@ruleorder,&unescape($item));
1533: }
1534: }
1535: }
1536: }
1537: return (\%ruleshash,\@ruleorder);
1538: }
1539:
1.976 raeburn 1540: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1541:
1542: sub get_domain_defaults {
1543: my ($domain) = @_;
1544: my $cachetime = 60*60*24;
1545: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1546: if (defined($cached)) {
1547: if (ref($result) eq 'HASH') {
1548: return %{$result};
1549: }
1550: }
1551: my %domdefaults;
1552: my %domconfig =
1.989 raeburn 1553: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1554: 'requestcourses','inststatus',
1.1056.4.3 raeburn 1555: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1556: if (ref($domconfig{'defaults'}) eq 'HASH') {
1557: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1558: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1559: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1560: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1561: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1562: } else {
1563: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1564: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1565: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1566: }
1.976 raeburn 1567: if (ref($domconfig{'quotas'}) eq 'HASH') {
1568: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1569: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1570: } else {
1571: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1572: }
1573: my @usertools = ('aboutme','blog','portfolio');
1574: foreach my $item (@usertools) {
1575: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1576: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1577: }
1578: }
1579: }
1.985 raeburn 1580: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1581: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1582: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1583: }
1584: }
1.989 raeburn 1585: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1586: foreach my $item ('inststatustypes','inststatusorder') {
1587: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1588: }
1589: }
1.1047 raeburn 1590: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1591: foreach my $item ('canuse_pdfforms') {
1592: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1593: }
1594: }
1.1056.4.3 raeburn 1595: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1596: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1597: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1598: }
1599: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1600: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1601: }
1602: }
1.943 raeburn 1603: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1604: $cachetime);
1605: return %domdefaults;
1606: }
1607:
1.344 www 1608: # --------------------------------------------------- Assign a key to a student
1609:
1610: sub assign_access_key {
1.364 www 1611: #
1612: # a valid key looks like uname:udom#comments
1613: # comments are being appended
1614: #
1.498 www 1615: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1616: $kdom=
1.620 albertel 1617: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1618: $knum=
1.620 albertel 1619: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1620: $cdom=
1.620 albertel 1621: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1622: $cnum=
1.620 albertel 1623: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1624: $udom=$env{'user.name'} unless (defined($udom));
1625: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1626: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1627: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1628: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1629: # assigned to this person
1630: # - this should not happen,
1.345 www 1631: # unless something went wrong
1632: # the first time around
1633: # ready to assign
1.364 www 1634: $logentry=$1.'; '.$logentry;
1.496 www 1635: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1636: $kdom,$knum) eq 'ok') {
1.345 www 1637: # key now belongs to user
1.346 www 1638: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1639: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1640: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1641: return 'ok';
1642: } else {
1643: return
1644: 'error: Count not permanently assign key, will need to be re-entered later.';
1645: }
1646: } else {
1647: return 'error: Could not assign key, try again later.';
1648: }
1.364 www 1649: } elsif (!$existing{$ckey}) {
1.345 www 1650: # the key does not exist
1651: return 'error: The key does not exist';
1652: } else {
1653: # the key is somebody else's
1654: return 'error: The key is already in use';
1655: }
1.344 www 1656: }
1657:
1.364 www 1658: # ------------------------------------------ put an additional comment on a key
1659:
1660: sub comment_access_key {
1661: #
1662: # a valid key looks like uname:udom#comments
1663: # comments are being appended
1664: #
1665: my ($ckey,$cdom,$cnum,$logentry)=@_;
1666: $cdom=
1.620 albertel 1667: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1668: $cnum=
1.620 albertel 1669: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1670: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1671: if ($existing{$ckey}) {
1672: $existing{$ckey}.='; '.$logentry;
1673: # ready to assign
1.367 www 1674: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1675: $cdom,$cnum) eq 'ok') {
1676: return 'ok';
1677: } else {
1678: return 'error: Count not store comment.';
1679: }
1680: } else {
1681: # the key does not exist
1682: return 'error: The key does not exist';
1683: }
1684: }
1685:
1.344 www 1686: # ------------------------------------------------------ Generate a set of keys
1687:
1688: sub generate_access_keys {
1.364 www 1689: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1690: $cdom=
1.620 albertel 1691: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1692: $cnum=
1.620 albertel 1693: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1694: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1695: unless (($cdom) && ($cnum)) { return 0; }
1696: if ($number>10000) { return 0; }
1697: sleep(2); # make sure don't get same seed twice
1698: srand(time()^($$+($$<<15))); # from "Programming Perl"
1699: my $total=0;
1700: for (my $i=1;$i<=$number;$i++) {
1701: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1702: sprintf("%lx",int(100000*rand)).'-'.
1703: sprintf("%lx",int(100000*rand));
1704: $newkey=~s/1/g/g; # folks mix up 1 and l
1705: $newkey=~s/0/h/g; # and also 0 and O
1706: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1707: if ($existing{$newkey}) {
1708: $i--;
1709: } else {
1.364 www 1710: if (&put('accesskeys',
1711: { $newkey => '# generated '.localtime().
1.620 albertel 1712: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1713: '; '.$logentry },
1714: $cdom,$cnum) eq 'ok') {
1.344 www 1715: $total++;
1716: }
1717: }
1718: }
1.620 albertel 1719: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1720: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1721: return $total;
1722: }
1723:
1724: # ------------------------------------------------------- Validate an accesskey
1725:
1726: sub validate_access_key {
1727: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1728: $cdom=
1.620 albertel 1729: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1730: $cnum=
1.620 albertel 1731: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1732: $udom=$env{'user.domain'} unless (defined($udom));
1733: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1734: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1735: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1736: }
1737:
1738: # ------------------------------------- Find the section of student in a course
1.652 albertel 1739: sub devalidate_getsection_cache {
1740: my ($udom,$unam,$courseid)=@_;
1741: my $hashid="$udom:$unam:$courseid";
1742: &devalidate_cache_new('getsection',$hashid);
1743: }
1.298 matthew 1744:
1.815 albertel 1745: sub courseid_to_courseurl {
1746: my ($courseid) = @_;
1747: #already url style courseid
1748: return $courseid if ($courseid =~ m{^/});
1749:
1750: if (exists($env{'course.'.$courseid.'.num'})) {
1751: my $cnum = $env{'course.'.$courseid.'.num'};
1752: my $cdom = $env{'course.'.$courseid.'.domain'};
1753: return "/$cdom/$cnum";
1754: }
1755:
1756: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1757: if (exists($courseinfo{'num'})) {
1758: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1759: }
1760:
1761: return undef;
1762: }
1763:
1.298 matthew 1764: sub getsection {
1765: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1766: my $cachetime=1800;
1.551 albertel 1767:
1768: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1769: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1770: if (defined($cached)) { return $result; }
1771:
1.298 matthew 1772: my %Pending;
1773: my %Expired;
1774: #
1775: # Each role can either have not started yet (pending), be active,
1776: # or have expired.
1777: #
1778: # If there is an active role, we are done.
1779: #
1780: # If there is more than one role which has not started yet,
1781: # choose the one which will start sooner
1782: # If there is one role which has not started yet, return it.
1783: #
1784: # If there is more than one expired role, choose the one which ended last.
1785: # If there is a role which has expired, return it.
1786: #
1.815 albertel 1787: $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 1788: my $extra = &freeze_escape({'skipcheck' => 1});
1789: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1790: foreach my $key (keys(%roleshash)) {
1.479 albertel 1791: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1792: my $section=$1;
1793: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1794: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1795: my $now=time;
1.548 albertel 1796: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1797: $Expired{$end}=$section;
1798: next;
1799: }
1.548 albertel 1800: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1801: $Pending{$start}=$section;
1802: next;
1803: }
1.599 albertel 1804: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1805: }
1806: #
1807: # Presumedly there will be few matching roles from the above
1808: # loop and the sorting time will be negligible.
1809: if (scalar(keys(%Pending))) {
1810: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1811: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1812: }
1813: if (scalar(keys(%Expired))) {
1814: my @sorted = sort {$a <=> $b} keys(%Expired);
1815: my $time = pop(@sorted);
1.599 albertel 1816: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1817: }
1.599 albertel 1818: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1819: }
1.70 www 1820:
1.599 albertel 1821: sub save_cache {
1822: &purge_remembered();
1.722 albertel 1823: #&Apache::loncommon::validate_page();
1.620 albertel 1824: undef(%env);
1.780 albertel 1825: undef($env_loaded);
1.599 albertel 1826: }
1.452 albertel 1827:
1.599 albertel 1828: my $to_remember=-1;
1829: my %remembered;
1830: my %accessed;
1831: my $kicks=0;
1832: my $hits=0;
1.849 albertel 1833: sub make_key {
1834: my ($name,$id) = @_;
1.872 albertel 1835: if (length($id) > 65
1836: && length(&escape($id)) > 200) {
1837: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1838: }
1.849 albertel 1839: return &escape($name.':'.$id);
1840: }
1841:
1.599 albertel 1842: sub devalidate_cache_new {
1843: my ($name,$id,$debug) = @_;
1844: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1845: $id=&make_key($name,$id);
1.599 albertel 1846: $memcache->delete($id);
1847: delete($remembered{$id});
1848: delete($accessed{$id});
1849: }
1850:
1851: sub is_cached_new {
1852: my ($name,$id,$debug) = @_;
1.849 albertel 1853: $id=&make_key($name,$id);
1.599 albertel 1854: if (exists($remembered{$id})) {
1855: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1856: $accessed{$id}=[&gettimeofday()];
1857: $hits++;
1858: return ($remembered{$id},1);
1859: }
1860: my $value = $memcache->get($id);
1861: if (!(defined($value))) {
1862: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1863: return (undef,undef);
1.416 albertel 1864: }
1.599 albertel 1865: if ($value eq '__undef__') {
1866: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1867: $value=undef;
1868: }
1869: &make_room($id,$value,$debug);
1870: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1871: return ($value,1);
1872: }
1873:
1874: sub do_cache_new {
1875: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1876: $id=&make_key($name,$id);
1.599 albertel 1877: my $setvalue=$value;
1878: if (!defined($setvalue)) {
1879: $setvalue='__undef__';
1880: }
1.623 albertel 1881: if (!defined($time) ) {
1882: $time=600;
1883: }
1.599 albertel 1884: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1885: my $result = $memcache->set($id,$setvalue,$time);
1886: if (! $result) {
1.872 albertel 1887: &logthis("caching of id -> $id failed");
1.910 albertel 1888: $memcache->disconnect_all();
1.872 albertel 1889: }
1.600 albertel 1890: # need to make a copy of $value
1.919 albertel 1891: &make_room($id,$value,$debug);
1.599 albertel 1892: return $value;
1893: }
1894:
1895: sub make_room {
1896: my ($id,$value,$debug)=@_;
1.919 albertel 1897:
1898: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1899: : $value;
1.599 albertel 1900: if ($to_remember<0) { return; }
1901: $accessed{$id}=[&gettimeofday()];
1902: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1903: my $to_kick;
1904: my $max_time=0;
1905: foreach my $other (keys(%accessed)) {
1906: if (&tv_interval($accessed{$other}) > $max_time) {
1907: $to_kick=$other;
1908: $max_time=&tv_interval($accessed{$other});
1909: }
1910: }
1911: delete($remembered{$to_kick});
1912: delete($accessed{$to_kick});
1913: $kicks++;
1914: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1915: return;
1916: }
1917:
1.599 albertel 1918: sub purge_remembered {
1.604 albertel 1919: #&logthis("Tossing ".scalar(keys(%remembered)));
1920: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1921: undef(%remembered);
1922: undef(%accessed);
1.428 albertel 1923: }
1.70 www 1924: # ------------------------------------- Read an entry from a user's environment
1925:
1926: sub userenvironment {
1927: my ($udom,$unam,@what)=@_;
1.976 raeburn 1928: my $items;
1929: foreach my $item (@what) {
1930: $items.=&escape($item).'&';
1931: }
1932: $items=~s/\&$//;
1.70 www 1933: my %returnhash=();
1.1009 raeburn 1934: my $uhome = &homeserver($unam,$udom);
1935: unless ($uhome eq 'no_host') {
1936: my @answer=split(/\&/,
1937: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1938: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1939: return %returnhash;
1940: }
1.1009 raeburn 1941: my $i;
1942: for ($i=0;$i<=$#what;$i++) {
1943: $returnhash{$what[$i]}=&unescape($answer[$i]);
1944: }
1.70 www 1945: }
1946: return %returnhash;
1.1 albertel 1947: }
1948:
1.617 albertel 1949: # ---------------------------------------------------------- Get a studentphoto
1950: sub studentphoto {
1951: my ($udom,$unam,$ext) = @_;
1952: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1953: if (defined($env{'request.course.id'})) {
1.708 raeburn 1954: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1955: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1956: return(&retrievestudentphoto($udom,$unam,$ext));
1957: } else {
1958: my ($result,$perm_reqd)=
1.707 albertel 1959: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1960: if ($result eq 'ok') {
1961: if (!($perm_reqd eq 'yes')) {
1962: return(&retrievestudentphoto($udom,$unam,$ext));
1963: }
1964: }
1965: }
1966: }
1967: } else {
1968: my ($result,$perm_reqd) =
1.707 albertel 1969: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1970: if ($result eq 'ok') {
1971: if (!($perm_reqd eq 'yes')) {
1972: return(&retrievestudentphoto($udom,$unam,$ext));
1973: }
1974: }
1975: }
1976: return '/adm/lonKaputt/lonlogo_broken.gif';
1977: }
1978:
1979: sub retrievestudentphoto {
1980: my ($udom,$unam,$ext,$type) = @_;
1981: my $home=&Apache::lonnet::homeserver($unam,$udom);
1982: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1983: if ($ret eq 'ok') {
1984: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1985: if ($type eq 'thumbnail') {
1986: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1987: }
1988: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1989: return $tokenurl;
1990: } else {
1991: if ($type eq 'thumbnail') {
1992: return '/adm/lonKaputt/genericstudent_tn.gif';
1993: } else {
1994: return '/adm/lonKaputt/lonlogo_broken.gif';
1995: }
1.617 albertel 1996: }
1997: }
1998:
1.263 www 1999: # -------------------------------------------------------------------- New chat
2000:
2001: sub chatsend {
1.724 raeburn 2002: my ($newentry,$anon,$group)=@_;
1.620 albertel 2003: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2004: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2005: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2006: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2007: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2008: &escape($newentry)).':'.$group,$chome);
1.292 www 2009: }
2010:
2011: # ------------------------------------------ Find current version of a resource
2012:
2013: sub getversion {
2014: my $fname=&clutter(shift);
2015: unless ($fname=~/^\/res\//) { return -1; }
2016: return ¤tversion(&filelocation('',$fname));
2017: }
2018:
2019: sub currentversion {
2020: my $fname=shift;
1.599 albertel 2021: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 2022: if (defined($cached)) { return $result; }
1.292 www 2023: my $author=$fname;
2024: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2025: my ($udom,$uname)=split(/\//,$author);
2026: my $home=homeserver($uname,$udom);
2027: if ($home eq 'no_host') {
2028: return -1;
2029: }
2030: my $answer=reply("currentversion:$fname",$home);
2031: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2032: return -1;
2033: }
1.599 albertel 2034: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 2035: }
2036:
1.1 albertel 2037: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2038:
1.1 albertel 2039: sub subscribe {
2040: my $fname=shift;
1.761 raeburn 2041: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2042: $fname=~s/[\n\r]//g;
1.1 albertel 2043: my $author=$fname;
2044: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2045: my ($udom,$uname)=split(/\//,$author);
2046: my $home=homeserver($uname,$udom);
1.335 albertel 2047: if ($home eq 'no_host') {
2048: return 'not_found';
1.1 albertel 2049: }
2050: my $answer=reply("sub:$fname",$home);
1.64 www 2051: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2052: $answer.=' by '.$home;
2053: }
1.1 albertel 2054: return $answer;
2055: }
2056:
1.8 www 2057: # -------------------------------------------------------------- Replicate file
2058:
2059: sub repcopy {
2060: my $filename=shift;
1.23 www 2061: $filename=~s/\/+/\//g;
1.607 raeburn 2062: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2063: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2064: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2065: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2066: return &repcopy_userfile($filename);
2067: }
1.532 albertel 2068: $filename=~s/[\n\r]//g;
1.8 www 2069: my $transname="$filename.in.transfer";
1.828 www 2070: # FIXME: this should flock
1.607 raeburn 2071: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2072: my $remoteurl=subscribe($filename);
1.64 www 2073: if ($remoteurl =~ /^con_lost by/) {
2074: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2075: return 'unavailable';
1.8 www 2076: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2077: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2078: return 'not_found';
1.64 www 2079: } elsif ($remoteurl =~ /^rejected by/) {
2080: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2081: return 'forbidden';
1.20 www 2082: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2083: return 'ok';
1.8 www 2084: } else {
1.290 www 2085: my $author=$filename;
2086: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2087: my ($udom,$uname)=split(/\//,$author);
2088: my $home=homeserver($uname,$udom);
2089: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2090: my @parts=split(/\//,$filename);
2091: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2092: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2093: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2094: return 'bad_request';
1.8 www 2095: }
2096: my $count;
2097: for ($count=5;$count<$#parts;$count++) {
2098: $path.="/$parts[$count]";
2099: if ((-e $path)!=1) {
2100: mkdir($path,0777);
2101: }
2102: }
2103: my $ua=new LWP::UserAgent;
2104: my $request=new HTTP::Request('GET',"$remoteurl");
2105: my $response=$ua->request($request,$transname);
2106: if ($response->is_error()) {
2107: unlink($transname);
2108: my $message=$response->status_line;
1.672 albertel 2109: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2110: ." LWP get: $message: $filename</font>");
1.607 raeburn 2111: return 'unavailable';
1.8 www 2112: } else {
1.16 www 2113: if ($remoteurl!~/\.meta$/) {
2114: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2115: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2116: if ($mresponse->is_error()) {
2117: unlink($filename.'.meta');
2118: &logthis(
1.672 albertel 2119: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2120: }
2121: }
1.8 www 2122: rename($transname,$filename);
1.607 raeburn 2123: return 'ok';
1.8 www 2124: }
1.290 www 2125: }
1.8 www 2126: }
1.330 www 2127: }
2128:
2129: # ------------------------------------------------ Get server side include body
2130: sub ssi_body {
1.381 albertel 2131: my ($filelink,%form)=@_;
1.606 matthew 2132: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2133: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2134: }
1.953 www 2135: my $output='';
2136: my $response;
1.980 raeburn 2137: if ($filelink=~/^https?\:/) {
1.954 raeburn 2138: ($output,$response)=&externalssi($filelink);
1.953 www 2139: } else {
1.1004 droeschl 2140: $filelink .= $filelink=~/\?/ ? '&' : '?';
2141: $filelink .= 'inhibitmenu=yes';
1.953 www 2142: ($output,$response)=&ssi($filelink,%form);
2143: }
1.778 albertel 2144: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2145: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2146: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2147: if (wantarray) {
2148: return ($output, $response);
2149: } else {
2150: return $output;
2151: }
1.8 www 2152: }
2153:
1.15 www 2154: # --------------------------------------------------------- Server Side Include
2155:
1.782 albertel 2156: sub absolute_url {
2157: my ($host_name) = @_;
2158: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2159: if ($host_name eq '') {
2160: $host_name = $ENV{'SERVER_NAME'};
2161: }
2162: return $protocol.$host_name;
2163: }
2164:
1.942 foxr 2165: #
2166: # Server side include.
2167: # Parameters:
2168: # fn Possibly encrypted resource name/id.
2169: # form Hash that describes how the rendering should be done
2170: # and other things.
1.944 foxr 2171: # Returns:
1.950 raeburn 2172: # Scalar context: The content of the response.
2173: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2174: #
1.15 www 2175: sub ssi {
2176:
1.944 foxr 2177: my ($fn,%form)=@_;
1.15 www 2178: my $ua=new LWP::UserAgent;
1.23 www 2179: my $request;
1.711 albertel 2180:
2181: $form{'no_update_last_known'}=1;
1.895 albertel 2182: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2183: if (%form) {
1.782 albertel 2184: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2185: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2186: } else {
1.782 albertel 2187: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2188: }
2189:
1.15 www 2190: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2191: my $response=$ua->request($request);
2192:
1.944 foxr 2193: if (wantarray) {
2194: return ($response->content, $response);
2195: } else {
2196: return $response->content;
1.942 foxr 2197: }
1.324 www 2198: }
2199:
2200: sub externalssi {
2201: my ($url)=@_;
2202: my $ua=new LWP::UserAgent;
2203: my $request=new HTTP::Request('GET',$url);
2204: my $response=$ua->request($request);
1.954 raeburn 2205: if (wantarray) {
2206: return ($response->content, $response);
2207: } else {
2208: return $response->content;
2209: }
1.15 www 2210: }
1.254 www 2211:
1.492 albertel 2212: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2213:
2214: sub allowuploaded {
2215: my ($srcurl,$url)=@_;
2216: $url=&clutter(&declutter($url));
2217: my $dir=$url;
2218: $dir=~s/\/[^\/]+$//;
2219: my %httpref=();
2220: my $httpurl=&hreflocation('',$url);
2221: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2222: &Apache::lonnet::appenv(\%httpref);
1.254 www 2223: }
1.477 raeburn 2224:
1.478 albertel 2225: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2226: # input: action, courseID, current domain, intended
1.637 raeburn 2227: # path to file, source of file, instruction to parse file for objects,
2228: # ref to hash for embedded objects,
2229: # ref to hash for codebase of java objects.
1.1056.4.16 raeburn 2230: # reference to scalar to accommodate mime type determined
2231: # from File::MMagic if $parser = parse.
1.637 raeburn 2232: #
1.485 raeburn 2233: # output: url to file (if action was uploaddoc),
2234: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2235: #
1.478 albertel 2236: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2237: # course.
1.477 raeburn 2238: #
1.478 albertel 2239: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2240: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2241: # course's home server.
1.477 raeburn 2242: #
1.478 albertel 2243: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2244: # be copied from $source (current location) to
2245: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2246: # and will then be copied to
2247: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2248: # course's home server.
1.485 raeburn 2249: #
1.481 raeburn 2250: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2251: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2252: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2253: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2254: # in course's home server.
1.637 raeburn 2255: #
1.477 raeburn 2256:
2257: sub process_coursefile {
1.1056.4.16 raeburn 2258: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2259: $mimetype)=@_;
1.477 raeburn 2260: my $fetchresult;
1.638 albertel 2261: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2262: if ($action eq 'propagate') {
1.638 albertel 2263: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2264: $home);
1.481 raeburn 2265: } else {
1.477 raeburn 2266: my $fpath = '';
2267: my $fname = $file;
1.478 albertel 2268: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2269: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2270: my $filepath = &build_filepath($fpath);
1.481 raeburn 2271: if ($action eq 'copy') {
2272: if ($source eq '') {
2273: $fetchresult = 'no source file';
2274: return $fetchresult;
2275: } else {
2276: my $destination = $filepath.'/'.$fname;
2277: rename($source,$destination);
2278: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2279: $home);
1.481 raeburn 2280: }
2281: } elsif ($action eq 'uploaddoc') {
2282: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2283: print $fh $env{'form.'.$source};
1.481 raeburn 2284: close($fh);
1.637 raeburn 2285: if ($parser eq 'parse') {
1.1024 raeburn 2286: my $mm = new File::MMagic;
1.1056.4.16 raeburn 2287: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2288: if ($type eq 'text/html') {
1.1024 raeburn 2289: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2290: unless ($parse_result eq 'ok') {
2291: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2292: }
1.637 raeburn 2293: }
1.1056.4.16 raeburn 2294: if (ref($mimetype)) {
2295: $$mimetype = $type;
2296: }
1.637 raeburn 2297: }
1.477 raeburn 2298: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2299: $home);
1.481 raeburn 2300: if ($fetchresult eq 'ok') {
2301: return '/uploaded/'.$fpath.'/'.$fname;
2302: } else {
2303: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2304: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2305: return '/adm/notfound.html';
2306: }
1.477 raeburn 2307: }
2308: }
1.485 raeburn 2309: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2310: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2311: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2312: }
2313: return $fetchresult;
2314: }
2315:
1.637 raeburn 2316: sub build_filepath {
2317: my ($fpath) = @_;
2318: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2319: unless ($fpath eq '') {
2320: my @parts=split('/',$fpath);
2321: foreach my $part (@parts) {
2322: $filepath.= '/'.$part;
2323: if ((-e $filepath)!=1) {
2324: mkdir($filepath,0777);
2325: }
2326: }
2327: }
2328: return $filepath;
2329: }
2330:
2331: sub store_edited_file {
1.638 albertel 2332: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2333: my $file = $primary_url;
2334: $file =~ s#^/uploaded/$docudom/$docuname/##;
2335: my $fpath = '';
2336: my $fname = $file;
2337: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2338: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2339: my $filepath = &build_filepath($fpath);
2340: open(my $fh,'>'.$filepath.'/'.$fname);
2341: print $fh $content;
2342: close($fh);
1.638 albertel 2343: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2344: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2345: $home);
1.637 raeburn 2346: if ($$fetchresult eq 'ok') {
2347: return '/uploaded/'.$fpath.'/'.$fname;
2348: } else {
1.638 albertel 2349: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2350: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2351: return '/adm/notfound.html';
2352: }
2353: }
2354:
1.531 albertel 2355: sub clean_filename {
1.831 albertel 2356: my ($fname,$args)=@_;
1.315 www 2357: # Replace Windows backslashes by forward slashes
1.257 www 2358: $fname=~s/\\/\//g;
1.831 albertel 2359: if (!$args->{'keep_path'}) {
2360: # Get rid of everything but the actual filename
2361: $fname=~s/^.*\/([^\/]+)$/$1/;
2362: }
1.315 www 2363: # Replace spaces by underscores
2364: $fname=~s/\s+/\_/g;
2365: # Replace all other weird characters by nothing
1.831 albertel 2366: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2367: # Replace all .\d. sequences with _\d. so they no longer look like version
2368: # numbers
2369: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2370: return $fname;
2371: }
1.1051 raeburn 2372: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2373: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2374: # image with the same aspect ratio as the original, but with dimensions which do
2375: # not exceed $resizewidth and $resizeheight.
2376:
1.984 neumanie 2377: sub resizeImage {
1.1051 raeburn 2378: my ($img_path,$resizewidth,$resizeheight) = @_;
2379: my $ima = Image::Magick->new;
2380: my $resized;
2381: if (-e $img_path) {
2382: $ima->Read($img_path);
2383: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2384: my $width = $ima->Get('width');
2385: my $height = $ima->Get('height');
2386: if ($width > $resizewidth) {
2387: my $factor = $width/$resizewidth;
2388: my $newheight = $height/$factor;
2389: $ima->Scale(width=>$resizewidth,height=>$newheight);
2390: $resized = 1;
2391: }
2392: }
2393: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2394: my $width = $ima->Get('width');
2395: my $height = $ima->Get('height');
2396: if ($height > $resizeheight) {
2397: my $factor = $height/$resizeheight;
2398: my $newwidth = $width/$factor;
2399: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2400: $resized = 1;
2401: }
2402: }
2403: if ($resized) {
2404: $ima->Write($img_path);
2405: }
2406: }
2407: return;
1.977 amueller 2408: }
2409:
1.608 albertel 2410: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2411: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13 raeburn 2412: # the desired filename is in $env{"form.$formname.filename"}
2413: # $context - possible values: coursedoc, existingfile, overwrite,
2414: # canceloverwrite, or ''.
2415: # if 'coursedoc': upload to the current course
2416: # if 'existingfile': write file to tmp/overwrites directory
2417: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2418: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2419: # $subdir - directory in userfile to store the file into
1.858 raeburn 2420: # $parser - instruction to parse file for objects ($parser = parse)
2421: # $allfiles - reference to hash for embedded objects
2422: # $codebase - reference to hash for codebase of java objects
2423: # $desuname - username for permanent storage of uploaded file
2424: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2425: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2426: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2427: # $resizewidth - width (pixels) to which to resize uploaded image
2428: # $resizeheight - height (pixels) to which to resize uploaded image
1.1056.4.16 raeburn 2429: # $mimetype - reference to scalar to accommodate mime type determined
2430: # from File::MMagic if $parser = parse.
1.858 raeburn 2431: #
1.686 albertel 2432: # output: url of file in userspace, or error: <message>
2433: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2434:
1.531 albertel 2435: sub userfileupload {
1.1056.4.13 raeburn 2436: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1056.4.16 raeburn 2437: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2438: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2439: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2440: $fname=&clean_filename($fname);
1.1056.4.13 raeburn 2441: # See if there is anything left
1.257 www 2442: unless ($fname) { return 'error: no uploaded file'; }
1.1056.4.13 raeburn 2443: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2444: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2445: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2446: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2447: my $now = time;
1.1056.4.13 raeburn 2448: my $filepath;
2449: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2450: $filepath = 'tmp/helprequests/'.$now;
2451: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2452: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2453: '_'.$env{'user.domain'}.'/pending';
2454: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2455: my ($docuname,$docudom);
2456: if ($destudom) {
2457: $docudom = $destudom;
2458: } else {
2459: $docudom = $env{'user.domain'};
2460: }
2461: if ($destuname) {
2462: $docuname = $destuname;
2463: } else {
2464: $docuname = $env{'user.name'};
2465: }
2466: if (exists($env{'form.group'})) {
2467: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2468: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2469: }
2470: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2471: if ($context eq 'canceloverwrite') {
2472: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2473: if (-e $tempfile) {
2474: my @info = stat($tempfile);
2475: if ($info[9] eq $env{'form.timestamp'}) {
2476: unlink($tempfile);
2477: }
2478: }
2479: return;
1.523 raeburn 2480: }
2481: }
1.1056.4.13 raeburn 2482: # Create the directory if not present
1.741 raeburn 2483: my @parts=split(/\//,$filepath);
2484: my $fullpath = $perlvar{'lonDaemons'};
2485: for (my $i=0;$i<@parts;$i++) {
2486: $fullpath .= '/'.$parts[$i];
2487: if ((-e $fullpath)!=1) {
2488: mkdir($fullpath,0777);
2489: }
2490: }
2491: open(my $fh,'>'.$fullpath.'/'.$fname);
2492: print $fh $env{'form.'.$formname};
2493: close($fh);
1.1056.4.13 raeburn 2494: if ($context eq 'existingfile') {
2495: my @info = stat($fullpath.'/'.$fname);
2496: return ($fullpath.'/'.$fname,$info[9]);
2497: } else {
2498: return $fullpath.'/'.$fname;
2499: }
1.523 raeburn 2500: }
1.995 raeburn 2501: if ($subdir eq 'scantron') {
2502: $fname = 'scantron_orig_'.$fname;
1.1056.4.14 raeburn 2503: } else {
1.995 raeburn 2504: $fname="$subdir/$fname";
2505: }
1.1056.4.13 raeburn 2506: if ($context eq 'coursedoc') {
1.638 albertel 2507: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2508: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2509: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2510: return &finishuserfileupload($docuname,$docudom,
2511: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2512: $codebase,$thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2513: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2514: } else {
1.620 albertel 2515: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2516: return &process_coursefile('uploaddoc',$docuname,$docudom,
2517: $fname,$formname,$parser,
1.1056.4.16 raeburn 2518: $allfiles,$codebase,$mimetype);
1.481 raeburn 2519: }
1.719 banghart 2520: } elsif (defined($destuname)) {
2521: my $docuname=$destuname;
2522: my $docudom=$destudom;
1.860 raeburn 2523: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2524: $parser,$allfiles,$codebase,
1.1051 raeburn 2525: $thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2526: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2527: } else {
1.638 albertel 2528: my $docuname=$env{'user.name'};
2529: my $docudom=$env{'user.domain'};
1.714 raeburn 2530: if (exists($env{'form.group'})) {
2531: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2532: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2533: }
1.860 raeburn 2534: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2535: $parser,$allfiles,$codebase,
1.1051 raeburn 2536: $thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2537: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2538: }
1.271 www 2539: }
2540:
2541: sub finishuserfileupload {
1.860 raeburn 2542: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.16 raeburn 2543: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2544: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2545: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2546:
1.860 raeburn 2547: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2548: $file=$fname;
2549: if ($fname=~m|/|) {
2550: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2551: $path.=$fnamepath.'/';
2552: }
1.259 www 2553: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2554: my $count;
2555: for ($count=4;$count<=$#parts;$count++) {
2556: $filepath.="/$parts[$count]";
2557: if ((-e $filepath)!=1) {
2558: mkdir($filepath,0777);
2559: }
2560: }
1.984 neumanie 2561:
1.258 www 2562: # Save the file
2563: {
1.701 albertel 2564: if (!open(FH,'>'.$filepath.'/'.$file)) {
2565: &logthis('Failed to create '.$filepath.'/'.$file);
2566: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2567: return '/adm/notfound.html';
2568: }
1.1056.4.13 raeburn 2569: if ($context eq 'overwrite') {
2570: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2571: my $target = $filepath.'/'.$file;
2572: if (-e $source) {
2573: my @info = stat($source);
2574: if ($info[9] eq $env{'form.timestamp'}) {
2575: unless (&File::Copy::move($source,$target)) {
2576: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2577: return "Moving from $source failed";
2578: }
2579: } else {
2580: return "Temporary file: $source had unexpected date/time for last modification";
2581: }
2582: } else {
2583: return "Temporary file: $source missing";
2584: }
2585: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2586: &logthis('Failed to write to '.$filepath.'/'.$file);
2587: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2588: return '/adm/notfound.html';
2589: }
1.570 albertel 2590: close(FH);
1.1051 raeburn 2591: if ($resizewidth && $resizeheight) {
2592: my $mm = new File::MMagic;
2593: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2594: if ($mime_type =~ m{^image/}) {
2595: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2596: }
1.977 amueller 2597: }
1.258 www 2598: }
1.637 raeburn 2599: if ($parser eq 'parse') {
1.1024 raeburn 2600: my $mm = new File::MMagic;
1.1056.4.16 raeburn 2601: my $type = $mm->checktype_filename($filepath.'/'.$file);
2602: if ($type eq 'text/html') {
1.1024 raeburn 2603: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2604: $allfiles,$codebase);
2605: unless ($parse_result eq 'ok') {
2606: &logthis('Failed to parse '.$filepath.$file.
2607: ' for embedded media: '.$parse_result);
2608: }
1.637 raeburn 2609: }
1.1056.4.16 raeburn 2610: if (ref($mimetype)) {
2611: $$mimetype = $type;
2612: }
1.637 raeburn 2613: }
1.860 raeburn 2614: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2615: my $input = $filepath.'/'.$file;
2616: my $output = $filepath.'/'.'tn-'.$file;
2617: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2618: system("convert -sample $thumbsize $input $output");
2619: if (-e $filepath.'/'.'tn-'.$file) {
2620: $fetchthumb = 1;
2621: }
2622: }
1.858 raeburn 2623:
1.259 www 2624: # Notify homeserver to grep it
2625: #
1.984 neumanie 2626: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2627: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2628: if ($fetchresult eq 'ok') {
1.860 raeburn 2629: if ($fetchthumb) {
2630: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2631: if ($thumbresult ne 'ok') {
2632: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2633: $docuhome.': '.$thumbresult);
2634: }
2635: }
1.259 www 2636: #
1.258 www 2637: # Return the URL to it
1.494 albertel 2638: return '/uploaded/'.$path.$file;
1.263 www 2639: } else {
1.494 albertel 2640: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2641: ': '.$fetchresult);
1.263 www 2642: return '/adm/notfound.html';
1.858 raeburn 2643: }
1.493 albertel 2644: }
2645:
1.637 raeburn 2646: sub extract_embedded_items {
1.961 raeburn 2647: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2648: my @state = ();
2649: my %javafiles = (
2650: codebase => '',
2651: code => '',
2652: archive => ''
2653: );
2654: my %mediafiles = (
2655: src => '',
2656: movie => '',
2657: );
1.648 raeburn 2658: my $p;
2659: if ($content) {
2660: $p = HTML::LCParser->new($content);
2661: } else {
1.961 raeburn 2662: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2663: }
1.641 albertel 2664: while (my $t=$p->get_token()) {
1.640 albertel 2665: if ($t->[0] eq 'S') {
2666: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2667: push(@state, $tagname);
1.648 raeburn 2668: if (lc($tagname) eq 'allow') {
2669: &add_filetype($allfiles,$attr->{'src'},'src');
2670: }
1.640 albertel 2671: if (lc($tagname) eq 'img') {
2672: &add_filetype($allfiles,$attr->{'src'},'src');
2673: }
1.886 albertel 2674: if (lc($tagname) eq 'a') {
2675: &add_filetype($allfiles,$attr->{'href'},'href');
2676: }
1.645 raeburn 2677: if (lc($tagname) eq 'script') {
2678: if ($attr->{'archive'} =~ /\.jar$/i) {
2679: &add_filetype($allfiles,$attr->{'archive'},'archive');
2680: } else {
2681: &add_filetype($allfiles,$attr->{'src'},'src');
2682: }
2683: }
2684: if (lc($tagname) eq 'link') {
2685: if (lc($attr->{'rel'}) eq 'stylesheet') {
2686: &add_filetype($allfiles,$attr->{'href'},'href');
2687: }
2688: }
1.640 albertel 2689: if (lc($tagname) eq 'object' ||
2690: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2691: foreach my $item (keys(%javafiles)) {
2692: $javafiles{$item} = '';
2693: }
2694: }
2695: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2696: my $name = lc($attr->{'name'});
2697: foreach my $item (keys(%javafiles)) {
2698: if ($name eq $item) {
2699: $javafiles{$item} = $attr->{'value'};
2700: last;
2701: }
2702: }
2703: foreach my $item (keys(%mediafiles)) {
2704: if ($name eq $item) {
2705: &add_filetype($allfiles, $attr->{'value'}, 'value');
2706: last;
2707: }
2708: }
2709: }
2710: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2711: foreach my $item (keys(%javafiles)) {
2712: if ($attr->{$item}) {
2713: $javafiles{$item} = $attr->{$item};
2714: last;
2715: }
2716: }
2717: foreach my $item (keys(%mediafiles)) {
2718: if ($attr->{$item}) {
2719: &add_filetype($allfiles,$attr->{$item},$item);
2720: last;
2721: }
2722: }
2723: }
2724: } elsif ($t->[0] eq 'E') {
2725: my ($tagname) = ($t->[1]);
2726: if ($javafiles{'codebase'} ne '') {
2727: $javafiles{'codebase'} .= '/';
2728: }
2729: if (lc($tagname) eq 'applet' ||
2730: lc($tagname) eq 'object' ||
2731: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2732: ) {
2733: foreach my $item (keys(%javafiles)) {
2734: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2735: my $file=$javafiles{'codebase'}.$javafiles{$item};
2736: &add_filetype($allfiles,$file,$item);
2737: }
2738: }
2739: }
2740: pop @state;
2741: }
2742: }
1.637 raeburn 2743: return 'ok';
2744: }
2745:
1.639 albertel 2746: sub add_filetype {
2747: my ($allfiles,$file,$type)=@_;
2748: if (exists($allfiles->{$file})) {
2749: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2750: push(@{$allfiles->{$file}}, &escape($type));
2751: }
2752: } else {
2753: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2754: }
2755: }
2756:
1.493 albertel 2757: sub removeuploadedurl {
1.984 neumanie 2758: my ($url)=@_;
2759: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2760: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2761: }
2762:
2763: sub removeuserfile {
2764: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2765: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2766: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2767: if ($result eq 'ok') {
1.798 raeburn 2768: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2769: my $metafile = $fname.'.meta';
2770: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2771: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2772: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2773: my $sqlresult =
1.823 albertel 2774: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2775: 'portfolio_metadata',$group,
2776: 'delete');
1.798 raeburn 2777: }
2778: }
2779: return $result;
1.257 www 2780: }
1.15 www 2781:
1.530 albertel 2782: sub mkdiruserfile {
2783: my ($docuname,$docudom,$dir)=@_;
2784: my $home=&homeserver($docuname,$docudom);
2785: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2786: }
2787:
1.531 albertel 2788: sub renameuserfile {
2789: my ($docuname,$docudom,$old,$new)=@_;
2790: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2791: my $result = &reply("renameuserfile:$docudom:$docuname:".
2792: &escape("$old").':'.&escape("$new"),$home);
2793: if ($result eq 'ok') {
2794: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2795: my $oldmeta = $old.'.meta';
2796: my $newmeta = $new.'.meta';
2797: my $metaresult =
2798: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2799: my $url = "/uploaded/$docudom/$docuname/$old";
2800: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2801: my $sqlresult =
1.823 albertel 2802: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2803: 'portfolio_metadata',$group,
2804: 'delete');
1.798 raeburn 2805: }
2806: }
2807: return $result;
1.531 albertel 2808: }
2809:
1.14 www 2810: # ------------------------------------------------------------------------- Log
2811:
2812: sub log {
2813: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2814: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2815: }
2816:
2817: # ------------------------------------------------------------------ Course Log
1.352 www 2818: #
2819: # This routine flushes several buffers of non-mission-critical nature
2820: #
1.157 www 2821:
2822: sub flushcourselogs {
1.352 www 2823: &logthis('Flushing log buffers');
2824: #
2825: # course logs
2826: # This is a log of all transactions in a course, which can be used
2827: # for data mining purposes
2828: #
2829: # It also collects the courseid database, which lists last transaction
2830: # times and course titles for all courseids
2831: #
2832: my %courseidbuffer=();
1.921 raeburn 2833: foreach my $crsid (keys(%courselogs)) {
1.352 www 2834: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2835: &escape($courselogs{$crsid}),
2836: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2837: delete $courselogs{$crsid};
2838: } else {
2839: &logthis('Failed to flush log buffer for '.$crsid);
2840: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2841: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2842: " exceeded maximum size, deleting.</font>");
2843: delete $courselogs{$crsid};
2844: }
1.352 www 2845: }
1.920 raeburn 2846: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2847: 'description' => $coursedescrbuf{$crsid},
2848: 'inst_code' => $courseinstcodebuf{$crsid},
2849: 'type' => $coursetypebuf{$crsid},
2850: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2851: };
1.191 harris41 2852: }
1.352 www 2853: #
2854: # Write course id database (reverse lookup) to homeserver of courses
2855: # Is used in pickcourse
2856: #
1.840 albertel 2857: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2858: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2859: $courseidbuffer{$crs_home},
2860: $crs_home,'timeonly');
1.352 www 2861: }
2862: #
2863: # File accesses
2864: # Writes to the dynamic metadata of resources to get hit counts, etc.
2865: #
1.449 matthew 2866: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2867: if ($entry =~ /___count$/) {
2868: my ($dom,$name);
1.807 albertel 2869: ($dom,$name,undef)=
1.811 albertel 2870: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2871: if (! defined($dom) || $dom eq '' ||
2872: ! defined($name) || $name eq '') {
1.620 albertel 2873: my $cid = $env{'request.course.id'};
2874: $dom = $env{'request.'.$cid.'.domain'};
2875: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2876: }
1.450 matthew 2877: my $value = $accesshash{$entry};
2878: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2879: my %temphash=($url => $value);
1.449 matthew 2880: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2881: if ($result eq 'ok') {
2882: delete $accesshash{$entry};
2883: } elsif ($result eq 'unknown_cmd') {
2884: # Target server has old code running on it.
1.450 matthew 2885: my %temphash=($entry => $value);
1.449 matthew 2886: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2887: delete $accesshash{$entry};
2888: }
2889: }
2890: } else {
1.811 albertel 2891: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2892: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2893: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2894: delete $accesshash{$entry};
2895: }
1.185 www 2896: }
1.191 harris41 2897: }
1.352 www 2898: #
2899: # Roles
2900: # Reverse lookup of user roles for course faculty/staff and co-authorship
2901: #
1.800 albertel 2902: foreach my $entry (keys(%userrolehash)) {
1.351 www 2903: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2904: split(/\:/,$entry);
2905: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2906: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2907: $rudom,$runame) eq 'ok') {
2908: delete $userrolehash{$entry};
2909: }
2910: }
1.662 raeburn 2911: #
2912: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2913: #
2914: my %domrolebuffer = ();
1.1000 raeburn 2915: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2916: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2917: if ($domrolebuffer{$rudom}) {
2918: $domrolebuffer{$rudom}.='&'.&escape($entry).
2919: '='.&escape($domainrolehash{$entry});
2920: } else {
2921: $domrolebuffer{$rudom}.=&escape($entry).
2922: '='.&escape($domainrolehash{$entry});
2923: }
2924: delete $domainrolehash{$entry};
2925: }
2926: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2927: my %servers = &get_servers($dom,'library');
2928: foreach my $tryserver (keys(%servers)) {
2929: unless (&reply('domroleput:'.$dom.':'.
2930: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2931: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2932: }
1.662 raeburn 2933: }
2934: }
1.186 www 2935: $dumpcount++;
1.157 www 2936: }
2937:
2938: sub courselog {
2939: my $what=shift;
1.158 www 2940: $what=time.':'.$what;
1.620 albertel 2941: unless ($env{'request.course.id'}) { return ''; }
2942: $coursedombuf{$env{'request.course.id'}}=
2943: $env{'course.'.$env{'request.course.id'}.'.domain'};
2944: $coursenumbuf{$env{'request.course.id'}}=
2945: $env{'course.'.$env{'request.course.id'}.'.num'};
2946: $coursehombuf{$env{'request.course.id'}}=
2947: $env{'course.'.$env{'request.course.id'}.'.home'};
2948: $coursedescrbuf{$env{'request.course.id'}}=
2949: $env{'course.'.$env{'request.course.id'}.'.description'};
2950: $courseinstcodebuf{$env{'request.course.id'}}=
2951: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2952: $courseownerbuf{$env{'request.course.id'}}=
2953: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2954: $coursetypebuf{$env{'request.course.id'}}=
2955: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2956: if (defined $courselogs{$env{'request.course.id'}}) {
2957: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2958: } else {
1.620 albertel 2959: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2960: }
1.620 albertel 2961: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2962: &flushcourselogs();
2963: }
1.158 www 2964: }
2965:
2966: sub courseacclog {
2967: my $fnsymb=shift;
1.620 albertel 2968: unless ($env{'request.course.id'}) { return ''; }
2969: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2970: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2971: $what.=':POST';
1.583 matthew 2972: # FIXME: Probably ought to escape things....
1.800 albertel 2973: foreach my $key (keys(%env)) {
2974: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2975: my $formitem = $1;
2976: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2977: $what.=':'.$formitem.'='.$env{$key};
2978: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2979: $what.=':'.$formitem.'='.$env{$key};
2980: }
1.158 www 2981: }
1.191 harris41 2982: }
1.583 matthew 2983: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2984: # FIXME: We should not be depending on a form parameter that someone
2985: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2986: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2987: $what.= ':POST';
2988: # FIXME: Probably ought to escape things....
2989: foreach my $element ('courseexp','crsfulltext','crsrelated',
2990: 'crsdiscuss') {
1.620 albertel 2991: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2992: }
2993: }
1.158 www 2994: }
2995: &courselog($what);
1.149 www 2996: }
2997:
1.185 www 2998: sub countacc {
2999: my $url=&declutter(shift);
1.458 matthew 3000: return if (! defined($url) || $url eq '');
1.620 albertel 3001: unless ($env{'request.course.id'}) { return ''; }
3002: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 3003: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3004: $accesshash{$key}++;
1.185 www 3005: }
1.349 www 3006:
1.361 www 3007: sub linklog {
3008: my ($from,$to)=@_;
3009: $from=&declutter($from);
3010: $to=&declutter($to);
3011: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3012: $accesshash{$to.'___'.$from.'___goto'}=1;
3013: }
3014:
1.349 www 3015: sub userrolelog {
3016: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3017: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3018: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3019: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3020: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3021: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3022: $userrolehash
3023: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3024: =$tend.':'.$tstart;
1.662 raeburn 3025: }
1.898 albertel 3026: if (($env{'request.role'} =~ /dc\./) &&
3027: (($trole=~/^au/) || ($trole=~/^in/) ||
3028: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3029: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3030: ($trole=~/^co/))) {
1.898 albertel 3031: $userrolehash
3032: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3033: =$tend.':'.$tstart;
3034: }
1.662 raeburn 3035: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3036: ($trole=~/^li/) || ($trole=~/^li/) ||
3037: ($trole=~/^au/) || ($trole=~/^dg/) ||
3038: ($trole=~/^sc/)) {
3039: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3040: $domainrolehash
3041: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3042: = $tend.':'.$tstart;
3043: }
1.351 www 3044: }
3045:
1.957 raeburn 3046: sub courserolelog {
3047: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3048: if (($trole eq 'cc') || ($trole eq 'in') ||
3049: ($trole eq 'ep') || ($trole eq 'ad') ||
3050: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3051: ($trole=~/^cr/) || ($trole eq 'gr') ||
3052: ($trole eq 'co')) {
1.957 raeburn 3053: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3054: my $cdom = $1;
3055: my $cnum = $2;
3056: my $sec = $3;
3057: my $namespace = 'rolelog';
3058: my %storehash = (
3059: role => $trole,
3060: start => $tstart,
3061: end => $tend,
3062: selfenroll => $selfenroll,
3063: context => $context,
3064: );
3065: if ($trole eq 'gr') {
3066: $namespace = 'groupslog';
3067: $storehash{'group'} = $sec;
3068: } else {
3069: $storehash{'section'} = $sec;
3070: }
3071: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3072: if (($trole ne 'st') || ($sec ne '')) {
3073: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3074: }
1.957 raeburn 3075: }
3076: }
3077: return;
3078: }
3079:
1.351 www 3080: sub get_course_adv_roles {
1.948 raeburn 3081: my ($cid,$codes) = @_;
1.620 albertel 3082: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3083: my %coursehash=&coursedescription($cid);
1.988 raeburn 3084: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3085: my %nothide=();
1.800 albertel 3086: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3087: if ($user !~ /:/) {
3088: $nothide{join(':',split(/[\@]/,$user))}=1;
3089: } else {
3090: $nothide{$user}=1;
3091: }
1.470 www 3092: }
1.351 www 3093: my %returnhash=();
3094: my %dumphash=
3095: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3096: my $now=time;
1.997 raeburn 3097: my %privileged;
1.1000 raeburn 3098: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3099: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3100: if (($tstart) && ($tstart<0)) { next; }
3101: if (($tend) && ($tend<$now)) { next; }
3102: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3103: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3104: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3105: unless (ref($privileged{$domain}) eq 'HASH') {
3106: my %dompersonnel =
1.998 raeburn 3107: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3108: $privileged{$domain} = {};
3109: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3110: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3111: foreach my $user (keys(%{$dompersonnel{$server}})) {
3112: my ($trole,$uname,$udom) = split(/:/,$user);
3113: $privileged{$udom}{$uname} = 1;
3114: }
3115: }
3116: }
3117: }
3118: if ((exists($privileged{$domain}{$username})) &&
3119: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3120: if ($role eq 'cr') { next; }
1.948 raeburn 3121: if ($codes) {
3122: if ($section) { $role .= ':'.$section; }
3123: if ($returnhash{$role}) {
3124: $returnhash{$role}.=','.$username.':'.$domain;
3125: } else {
3126: $returnhash{$role}=$username.':'.$domain;
3127: }
1.351 www 3128: } else {
1.988 raeburn 3129: my $key=&plaintext($role,$crstype);
1.973 bisitz 3130: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3131: if ($returnhash{$key}) {
3132: $returnhash{$key}.=','.$username.':'.$domain;
3133: } else {
3134: $returnhash{$key}=$username.':'.$domain;
3135: }
1.351 www 3136: }
1.948 raeburn 3137: }
1.400 www 3138: return %returnhash;
3139: }
3140:
3141: sub get_my_roles {
1.937 raeburn 3142: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3143: unless (defined($uname)) { $uname=$env{'user.name'}; }
3144: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3145: my (%dumphash,%nothide);
1.858 raeburn 3146: if ($context eq 'userroles') {
1.1056.4.10 raeburn 3147: my $extra = &freeze_escape({'skipcheck' => 1});
3148: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3149: } else {
3150: %dumphash=
1.400 www 3151: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3152: if ($hidepriv) {
3153: my %coursehash=&coursedescription($udom.'_'.$uname);
3154: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3155: if ($user !~ /:/) {
3156: $nothide{join(':',split(/[\@]/,$user))} = 1;
3157: } else {
3158: $nothide{$user} = 1;
3159: }
3160: }
3161: }
1.858 raeburn 3162: }
1.400 www 3163: my %returnhash=();
3164: my $now=time;
1.999 raeburn 3165: my %privileged;
1.800 albertel 3166: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3167: my ($role,$tend,$tstart);
3168: if ($context eq 'userroles') {
3169: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3170: } else {
3171: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3172: }
1.400 www 3173: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3174: my $status = 'active';
1.939 raeburn 3175: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3176: $status = 'previous';
3177: }
3178: if (($tstart) && ($now<$tstart)) {
3179: $status = 'future';
3180: }
3181: if (ref($types) eq 'ARRAY') {
3182: if (!grep(/^\Q$status\E$/,@{$types})) {
3183: next;
3184: }
3185: } else {
3186: if ($status ne 'active') {
3187: next;
3188: }
3189: }
1.867 raeburn 3190: my ($rolecode,$username,$domain,$section,$area);
3191: if ($context eq 'userroles') {
3192: ($area,$rolecode) = split(/_/,$entry);
3193: (undef,$domain,$username,$section) = split(/\//,$area);
3194: } else {
3195: ($role,$username,$domain,$section) = split(/\:/,$entry);
3196: }
1.832 raeburn 3197: if (ref($roledoms) eq 'ARRAY') {
3198: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3199: next;
3200: }
3201: }
3202: if (ref($roles) eq 'ARRAY') {
3203: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3204: if ($role =~ /^cr\//) {
3205: if (!grep(/^cr$/,@{$roles})) {
3206: next;
3207: }
3208: } else {
3209: next;
3210: }
1.832 raeburn 3211: }
1.867 raeburn 3212: }
1.937 raeburn 3213: if ($hidepriv) {
1.999 raeburn 3214: if ($context eq 'userroles') {
3215: if ((&privileged($username,$domain)) &&
3216: (!$nothide{$username.':'.$domain})) {
3217: next;
3218: }
3219: } else {
3220: unless (ref($privileged{$domain}) eq 'HASH') {
3221: my %dompersonnel =
3222: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3223: $privileged{$domain} = {};
3224: if (keys(%dompersonnel)) {
3225: foreach my $server (keys(%dompersonnel)) {
3226: if (ref($dompersonnel{$server}) eq 'HASH') {
3227: foreach my $user (keys(%{$dompersonnel{$server}})) {
3228: my ($trole,$uname,$udom) = split(/:/,$user);
3229: $privileged{$udom}{$uname} = $trole;
3230: }
3231: }
3232: }
3233: }
3234: }
3235: if (exists($privileged{$domain}{$username})) {
3236: if (!$nothide{$username.':'.$domain}) {
3237: next;
3238: }
3239: }
1.937 raeburn 3240: }
3241: }
1.933 raeburn 3242: if ($withsec) {
3243: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3244: $tstart.':'.$tend;
3245: } else {
3246: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3247: }
1.832 raeburn 3248: }
1.373 www 3249: return %returnhash;
1.399 www 3250: }
3251:
3252: # ----------------------------------------------------- Frontpage Announcements
3253: #
3254: #
3255:
3256: sub postannounce {
3257: my ($server,$text)=@_;
1.844 albertel 3258: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3259: unless ($text=~/\w/) { $text=''; }
3260: return &reply('setannounce:'.&escape($text),$server);
3261: }
3262:
3263: sub getannounce {
1.448 albertel 3264:
3265: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3266: my $announcement='';
1.800 albertel 3267: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3268: close($fh);
1.399 www 3269: if ($announcement=~/\w/) {
3270: return
3271: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3272: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3273: } else {
3274: return '';
3275: }
3276: } else {
3277: return '';
3278: }
1.351 www 3279: }
1.353 www 3280:
3281: # ---------------------------------------------------------- Course ID routines
3282: # Deal with domain's nohist_courseid.db files
3283: #
3284:
3285: sub courseidput {
1.921 raeburn 3286: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3287: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3288: my $outcome;
3289: if ($caller eq 'timeonly') {
3290: my $cids = '';
3291: foreach my $item (keys(%$storehash)) {
3292: $cids.=&escape($item).'&';
3293: }
3294: $cids=~s/\&$//;
3295: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3296: $coursehome);
3297: } else {
3298: my $items = '';
3299: foreach my $item (keys(%$storehash)) {
3300: $items.= &escape($item).'='.
3301: &freeze_escape($$storehash{$item}).'&';
3302: }
3303: $items=~s/\&$//;
3304: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3305: $coursehome);
1.918 raeburn 3306: }
3307: if ($outcome eq 'unknown_cmd') {
3308: my $what;
3309: foreach my $cid (keys(%$storehash)) {
3310: $what .= &escape($cid).'=';
1.921 raeburn 3311: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3312: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3313: }
3314: $what =~ s/\:$/&/;
3315: }
3316: $what =~ s/\&$//;
3317: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3318: } else {
3319: return $outcome;
3320: }
1.353 www 3321: }
3322:
3323: sub courseiddump {
1.921 raeburn 3324: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3325: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3326: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3 raeburn 3327: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3328: my $as_hash = 1;
3329: my %returnhash;
3330: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3331: my %libserv = &all_library();
3332: foreach my $tryserver (keys(%libserv)) {
3333: if ( ( $hostidflag == 1
3334: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3335: || (!defined($hostidflag)) ) {
3336:
1.918 raeburn 3337: if (($domfilter eq '') ||
3338: (&host_domain($tryserver) eq $domfilter)) {
3339: my $rep =
3340: &reply('courseiddump:'.&host_domain($tryserver).':'.
3341: $sincefilter.':'.&escape($descfilter).':'.
3342: &escape($instcodefilter).':'.&escape($ownerfilter).
3343: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3344: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3345: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3346: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3347: &escape($cc_clone).':'.$cloneonly.':'.
3348: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3 raeburn 3349: &escape($creationcontext).':'.$domcloner,
3350: $tryserver);
1.918 raeburn 3351: my @pairs=split(/\&/,$rep);
3352: foreach my $item (@pairs) {
3353: my ($key,$value)=split(/\=/,$item,2);
3354: $key = &unescape($key);
3355: next if ($key =~ /^error: 2 /);
3356: my $result = &thaw_unescape($value);
3357: if (ref($result) eq 'HASH') {
3358: $returnhash{$key}=$result;
3359: } else {
1.921 raeburn 3360: my @responses = split(/:/,$value);
3361: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3362: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3363: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3364: }
1.1008 raeburn 3365: }
1.353 www 3366: }
3367: }
3368: }
3369: }
3370: return %returnhash;
3371: }
3372:
1.1055 raeburn 3373: sub courselastaccess {
3374: my ($cdom,$cnum,$hostidref) = @_;
3375: my %returnhash;
3376: if ($cdom && $cnum) {
3377: my $chome = &homeserver($cnum,$cdom);
3378: if ($chome ne 'no_host') {
3379: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3380: &extract_lastaccess(\%returnhash,$rep);
3381: }
3382: } else {
3383: if (!$cdom) { $cdom=''; }
3384: my %libserv = &all_library();
3385: foreach my $tryserver (keys(%libserv)) {
3386: if (ref($hostidref) eq 'ARRAY') {
3387: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3388: }
3389: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3390: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3391: &extract_lastaccess(\%returnhash,$rep);
3392: }
3393: }
3394: }
3395: return %returnhash;
3396: }
3397:
3398: sub extract_lastaccess {
3399: my ($returnhash,$rep) = @_;
3400: if (ref($returnhash) eq 'HASH') {
3401: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3402: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3403: $rep eq '') {
3404: my @pairs=split(/\&/,$rep);
3405: foreach my $item (@pairs) {
3406: my ($key,$value)=split(/\=/,$item,2);
3407: $key = &unescape($key);
3408: next if ($key =~ /^error: 2 /);
3409: $returnhash->{$key} = &thaw_unescape($value);
3410: }
3411: }
3412: }
3413: return;
3414: }
3415:
1.658 raeburn 3416: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3417:
3418: sub dcmailput {
1.685 raeburn 3419: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3420: my $status = &Apache::lonnet::critical(
1.740 www 3421: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3422: &escape($message),$server);
1.662 raeburn 3423: return $status;
3424: }
3425:
1.658 raeburn 3426: sub dcmaildump {
3427: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3428: my %returnhash=();
1.846 albertel 3429:
3430: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3431: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3432: &escape($enddate).':';
3433: my @esc_senders=map { &escape($_)} @$senders;
3434: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3435: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3436: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3437: if (($key) && ($value)) {
3438: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3439: }
3440: }
3441: }
3442: return %returnhash;
3443: }
1.662 raeburn 3444: # ---------------------------------------------------------- Domain roles
3445:
3446: sub get_domain_roles {
3447: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3448: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3449: $startdate = '.';
3450: }
1.1018 raeburn 3451: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3452: $enddate = '.';
3453: }
1.922 raeburn 3454: my $rolelist;
3455: if (ref($roles) eq 'ARRAY') {
3456: $rolelist = join(':',@{$roles});
3457: }
1.662 raeburn 3458: my %personnel = ();
1.841 albertel 3459:
3460: my %servers = &get_servers($dom,'library');
3461: foreach my $tryserver (keys(%servers)) {
3462: %{$personnel{$tryserver}}=();
3463: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3464: &escape($startdate).':'.
3465: &escape($enddate).':'.
3466: &escape($rolelist), $tryserver))) {
3467: my ($key,$value) = split(/\=/,$line,2);
3468: if (($key) && ($value)) {
3469: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3470: }
3471: }
1.662 raeburn 3472: }
3473: return %personnel;
3474: }
1.658 raeburn 3475:
1.149 www 3476: # ----------------------------------------------------------- Check out an item
3477:
1.504 albertel 3478: sub get_first_access {
3479: my ($type,$argsymb)=@_;
1.790 albertel 3480: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3481: if ($argsymb) { $symb=$argsymb; }
3482: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3483: if ($type eq 'course') {
3484: $res='course';
3485: } elsif ($type eq 'map') {
1.588 albertel 3486: $res=&symbread($map);
3487: } else {
3488: $res=$symb;
3489: }
3490: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3491: return $times{"$courseid\0$res"};
1.504 albertel 3492: }
3493:
3494: sub set_first_access {
3495: my ($type)=@_;
1.790 albertel 3496: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3497: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3498: if ($type eq 'course') {
3499: $res='course';
3500: } elsif ($type eq 'map') {
1.588 albertel 3501: $res=&symbread($map);
3502: } else {
3503: $res=$symb;
3504: }
3505: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3506: if (!$firstaccess) {
1.588 albertel 3507: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3508: }
3509: return 'already_set';
1.504 albertel 3510: }
3511:
1.149 www 3512: sub checkout {
3513: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3514: my $now=time;
3515: my $lonhost=$perlvar{'lonHostID'};
3516: my $infostr=&escape(
1.234 www 3517: 'CHECKOUTTOKEN&'.
1.149 www 3518: $tuname.'&'.
3519: $tudom.'&'.
3520: $tcrsid.'&'.
3521: $symb.'&'.
3522: $now.'&'.$ENV{'REMOTE_ADDR'});
3523: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3524: if ($token=~/^error\:/) {
1.672 albertel 3525: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3526: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3527: "</font>");
3528: return '';
3529: }
3530:
1.149 www 3531: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3532: $token=~tr/a-z/A-Z/;
3533:
1.153 www 3534: my %infohash=('resource.0.outtoken' => $token,
3535: 'resource.0.checkouttime' => $now,
3536: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3537:
3538: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3539: return '';
1.151 www 3540: } else {
1.672 albertel 3541: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3542: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3543: "</font>");
1.149 www 3544: }
3545:
3546: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3547: &escape('Checkout '.$infostr.' - '.
3548: $token)) ne 'ok') {
3549: return '';
1.151 www 3550: } else {
1.672 albertel 3551: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3552: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3553: "</font>");
1.149 www 3554: }
1.151 www 3555: return $token;
1.149 www 3556: }
3557:
3558: # ------------------------------------------------------------ Check in an item
3559:
3560: sub checkin {
3561: my $token=shift;
1.150 www 3562: my $now=time;
3563: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3564: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3565: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3566: $dtoken=~s/\W/\_/g;
1.234 www 3567: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3568: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3569:
1.154 www 3570: unless (($tuname) && ($tudom)) {
3571: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3572: return '';
3573: }
3574:
3575: unless (&allowed('mgr',$tcrsid)) {
3576: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3577: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3578: return '';
3579: }
3580:
1.153 www 3581: my %infohash=('resource.0.intoken' => $token,
3582: 'resource.0.checkintime' => $now,
3583: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3584:
3585: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3586: return '';
3587: }
3588:
3589: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3590: &escape('Checkin - '.$token)) ne 'ok') {
3591: return '';
3592: }
3593:
3594: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3595: }
3596:
3597: # --------------------------------------------- Set Expire Date for Spreadsheet
3598:
3599: sub expirespread {
3600: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3601: my $cid=$env{'request.course.id'};
1.110 www 3602: if ($cid) {
3603: my $now=time;
3604: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3605: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3606: $env{'course.'.$cid.'.num'}.
1.110 www 3607: ':nohist_expirationdates:'.
3608: &escape($key).'='.$now,
1.620 albertel 3609: $env{'course.'.$cid.'.home'})
1.110 www 3610: }
3611: return 'ok';
1.14 www 3612: }
3613:
1.109 www 3614: # ----------------------------------------------------- Devalidate Spreadsheets
3615:
3616: sub devalidate {
1.325 www 3617: my ($symb,$uname,$udom)=@_;
1.620 albertel 3618: my $cid=$env{'request.course.id'};
1.109 www 3619: if ($cid) {
1.391 matthew 3620: # delete the stored spreadsheets for
3621: # - the student level sheet of this user in course's homespace
3622: # - the assessment level sheet for this resource
3623: # for this user in user's homespace
1.553 albertel 3624: # - current conditional state info
1.325 www 3625: my $key=$uname.':'.$udom.':';
1.109 www 3626: my $status=
1.299 matthew 3627: &del('nohist_calculatedsheets',
1.391 matthew 3628: [$key.'studentcalc:'],
1.620 albertel 3629: $env{'course.'.$cid.'.domain'},
3630: $env{'course.'.$cid.'.num'})
1.133 albertel 3631: .' '.
3632: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3633: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3634: unless ($status eq 'ok ok') {
3635: &logthis('Could not devalidate spreadsheet '.
1.325 www 3636: $uname.' at '.$udom.' for '.
1.109 www 3637: $symb.': '.$status);
1.133 albertel 3638: }
1.553 albertel 3639: &delenv('user.state.'.$cid);
1.109 www 3640: }
3641: }
3642:
1.265 albertel 3643: sub get_scalar {
3644: my ($string,$end) = @_;
3645: my $value;
3646: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3647: $value = $1;
3648: } elsif ($$string =~ s/^([^&]*?)&//) {
3649: $value = $1;
3650: }
3651: return &unescape($value);
3652: }
3653:
3654: sub array2str {
3655: my (@array) = @_;
3656: my $result=&arrayref2str(\@array);
3657: $result=~s/^__ARRAY_REF__//;
3658: $result=~s/__END_ARRAY_REF__$//;
3659: return $result;
3660: }
3661:
1.204 albertel 3662: sub arrayref2str {
3663: my ($arrayref) = @_;
1.265 albertel 3664: my $result='__ARRAY_REF__';
1.204 albertel 3665: foreach my $elem (@$arrayref) {
1.265 albertel 3666: if(ref($elem) eq 'ARRAY') {
3667: $result.=&arrayref2str($elem).'&';
3668: } elsif(ref($elem) eq 'HASH') {
3669: $result.=&hashref2str($elem).'&';
3670: } elsif(ref($elem)) {
3671: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3672: } else {
3673: $result.=&escape($elem).'&';
3674: }
3675: }
3676: $result=~s/\&$//;
1.265 albertel 3677: $result .= '__END_ARRAY_REF__';
1.204 albertel 3678: return $result;
3679: }
3680:
1.168 albertel 3681: sub hash2str {
1.204 albertel 3682: my (%hash) = @_;
3683: my $result=&hashref2str(\%hash);
1.265 albertel 3684: $result=~s/^__HASH_REF__//;
3685: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3686: return $result;
3687: }
3688:
3689: sub hashref2str {
3690: my ($hashref)=@_;
1.265 albertel 3691: my $result='__HASH_REF__';
1.800 albertel 3692: foreach my $key (sort(keys(%$hashref))) {
3693: if (ref($key) eq 'ARRAY') {
3694: $result.=&arrayref2str($key).'=';
3695: } elsif (ref($key) eq 'HASH') {
3696: $result.=&hashref2str($key).'=';
3697: } elsif (ref($key)) {
1.265 albertel 3698: $result.='=';
1.800 albertel 3699: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3700: } else {
1.800 albertel 3701: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3702: }
3703:
1.800 albertel 3704: if(ref($hashref->{$key}) eq 'ARRAY') {
3705: $result.=&arrayref2str($hashref->{$key}).'&';
3706: } elsif(ref($hashref->{$key}) eq 'HASH') {
3707: $result.=&hashref2str($hashref->{$key}).'&';
3708: } elsif(ref($hashref->{$key})) {
1.265 albertel 3709: $result.='&';
1.800 albertel 3710: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3711: } else {
1.800 albertel 3712: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3713: }
3714: }
1.168 albertel 3715: $result=~s/\&$//;
1.265 albertel 3716: $result .= '__END_HASH_REF__';
1.168 albertel 3717: return $result;
3718: }
3719:
3720: sub str2hash {
1.265 albertel 3721: my ($string)=@_;
3722: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3723: return %$hash;
3724: }
3725:
3726: sub str2hashref {
1.168 albertel 3727: my ($string) = @_;
1.265 albertel 3728:
3729: my %hash;
3730:
3731: if($string !~ /^__HASH_REF__/) {
3732: if (! ($string eq '' || !defined($string))) {
3733: $hash{'error'}='Not hash reference';
3734: }
3735: return (\%hash, $string);
3736: }
3737:
3738: $string =~ s/^__HASH_REF__//;
3739:
3740: while($string !~ /^__END_HASH_REF__/) {
3741: #key
3742: my $key='';
3743: if($string =~ /^__HASH_REF__/) {
3744: ($key, $string)=&str2hashref($string);
3745: if(defined($key->{'error'})) {
3746: $hash{'error'}='Bad data';
3747: return (\%hash, $string);
3748: }
3749: } elsif($string =~ /^__ARRAY_REF__/) {
3750: ($key, $string)=&str2arrayref($string);
3751: if($key->[0] eq 'Array reference error') {
3752: $hash{'error'}='Bad data';
3753: return (\%hash, $string);
3754: }
3755: } else {
3756: $string =~ s/^(.*?)=//;
1.267 albertel 3757: $key=&unescape($1);
1.265 albertel 3758: }
3759: $string =~ s/^=//;
3760:
3761: #value
3762: my $value='';
3763: if($string =~ /^__HASH_REF__/) {
3764: ($value, $string)=&str2hashref($string);
3765: if(defined($value->{'error'})) {
3766: $hash{'error'}='Bad data';
3767: return (\%hash, $string);
3768: }
3769: } elsif($string =~ /^__ARRAY_REF__/) {
3770: ($value, $string)=&str2arrayref($string);
3771: if($value->[0] eq 'Array reference error') {
3772: $hash{'error'}='Bad data';
3773: return (\%hash, $string);
3774: }
3775: } else {
3776: $value=&get_scalar(\$string,'__END_HASH_REF__');
3777: }
3778: $string =~ s/^&//;
3779:
3780: $hash{$key}=$value;
1.204 albertel 3781: }
1.265 albertel 3782:
3783: $string =~ s/^__END_HASH_REF__//;
3784:
3785: return (\%hash, $string);
1.204 albertel 3786: }
3787:
3788: sub str2array {
1.265 albertel 3789: my ($string)=@_;
3790: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3791: return @$array;
3792: }
3793:
3794: sub str2arrayref {
1.204 albertel 3795: my ($string) = @_;
1.265 albertel 3796: my @array;
3797:
3798: if($string !~ /^__ARRAY_REF__/) {
3799: if (! ($string eq '' || !defined($string))) {
3800: $array[0]='Array reference error';
3801: }
3802: return (\@array, $string);
3803: }
3804:
3805: $string =~ s/^__ARRAY_REF__//;
3806:
3807: while($string !~ /^__END_ARRAY_REF__/) {
3808: my $value='';
3809: if($string =~ /^__HASH_REF__/) {
3810: ($value, $string)=&str2hashref($string);
3811: if(defined($value->{'error'})) {
3812: $array[0] ='Array reference error';
3813: return (\@array, $string);
3814: }
3815: } elsif($string =~ /^__ARRAY_REF__/) {
3816: ($value, $string)=&str2arrayref($string);
3817: if($value->[0] eq 'Array reference error') {
3818: $array[0] ='Array reference error';
3819: return (\@array, $string);
3820: }
3821: } else {
3822: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3823: }
3824: $string =~ s/^&//;
3825:
3826: push(@array, $value);
1.191 harris41 3827: }
1.265 albertel 3828:
3829: $string =~ s/^__END_ARRAY_REF__//;
3830:
3831: return (\@array, $string);
1.168 albertel 3832: }
3833:
1.167 albertel 3834: # -------------------------------------------------------------------Temp Store
3835:
1.168 albertel 3836: sub tmpreset {
3837: my ($symb,$namespace,$domain,$stuname) = @_;
3838: if (!$symb) {
3839: $symb=&symbread();
1.620 albertel 3840: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3841: }
3842: $symb=escape($symb);
3843:
1.620 albertel 3844: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3845: $namespace=~s/\//\_/g;
3846: $namespace=~s/\W//g;
3847:
1.620 albertel 3848: if (!$domain) { $domain=$env{'user.domain'}; }
3849: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3850: if ($domain eq 'public' && $stuname eq 'public') {
3851: $stuname=$ENV{'REMOTE_ADDR'};
3852: }
1.168 albertel 3853: my $path=$perlvar{'lonDaemons'}.'/tmp';
3854: my %hash;
3855: if (tie(%hash,'GDBM_File',
3856: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3857: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3858: foreach my $key (keys(%hash)) {
1.180 albertel 3859: if ($key=~ /:$symb/) {
1.168 albertel 3860: delete($hash{$key});
3861: }
3862: }
3863: }
3864: }
3865:
1.167 albertel 3866: sub tmpstore {
1.168 albertel 3867: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3868:
3869: if (!$symb) {
3870: $symb=&symbread();
1.620 albertel 3871: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3872: }
3873: $symb=escape($symb);
3874:
3875: if (!$namespace) {
3876: # I don't think we would ever want to store this for a course.
3877: # it seems this will only be used if we don't have a course.
1.620 albertel 3878: #$namespace=$env{'request.course.id'};
1.168 albertel 3879: #if (!$namespace) {
1.620 albertel 3880: $namespace=$env{'request.state'};
1.168 albertel 3881: #}
3882: }
3883: $namespace=~s/\//\_/g;
3884: $namespace=~s/\W//g;
1.620 albertel 3885: if (!$domain) { $domain=$env{'user.domain'}; }
3886: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3887: if ($domain eq 'public' && $stuname eq 'public') {
3888: $stuname=$ENV{'REMOTE_ADDR'};
3889: }
1.168 albertel 3890: my $now=time;
3891: my %hash;
3892: my $path=$perlvar{'lonDaemons'}.'/tmp';
3893: if (tie(%hash,'GDBM_File',
3894: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3895: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3896: $hash{"version:$symb"}++;
3897: my $version=$hash{"version:$symb"};
3898: my $allkeys='';
3899: foreach my $key (keys(%$storehash)) {
3900: $allkeys.=$key.':';
1.591 albertel 3901: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3902: }
3903: $hash{"$version:$symb:timestamp"}=$now;
3904: $allkeys.='timestamp';
3905: $hash{"$version:keys:$symb"}=$allkeys;
3906: if (untie(%hash)) {
3907: return 'ok';
3908: } else {
3909: return "error:$!";
3910: }
3911: } else {
3912: return "error:$!";
3913: }
3914: }
1.167 albertel 3915:
1.168 albertel 3916: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3917:
1.168 albertel 3918: sub tmprestore {
3919: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3920:
1.168 albertel 3921: if (!$symb) {
3922: $symb=&symbread();
1.620 albertel 3923: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3924: }
3925: $symb=escape($symb);
3926:
1.620 albertel 3927: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3928:
1.620 albertel 3929: if (!$domain) { $domain=$env{'user.domain'}; }
3930: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3931: if ($domain eq 'public' && $stuname eq 'public') {
3932: $stuname=$ENV{'REMOTE_ADDR'};
3933: }
1.168 albertel 3934: my %returnhash;
3935: $namespace=~s/\//\_/g;
3936: $namespace=~s/\W//g;
3937: my %hash;
3938: my $path=$perlvar{'lonDaemons'}.'/tmp';
3939: if (tie(%hash,'GDBM_File',
3940: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3941: &GDBM_READER(),0640)) {
1.168 albertel 3942: my $version=$hash{"version:$symb"};
3943: $returnhash{'version'}=$version;
3944: my $scope;
3945: for ($scope=1;$scope<=$version;$scope++) {
3946: my $vkeys=$hash{"$scope:keys:$symb"};
3947: my @keys=split(/:/,$vkeys);
3948: my $key;
3949: $returnhash{"$scope:keys"}=$vkeys;
3950: foreach $key (@keys) {
1.591 albertel 3951: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3952: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3953: }
3954: }
1.168 albertel 3955: if (!(untie(%hash))) {
3956: return "error:$!";
3957: }
3958: } else {
3959: return "error:$!";
3960: }
3961: return %returnhash;
1.167 albertel 3962: }
3963:
1.9 www 3964: # ----------------------------------------------------------------------- Store
3965:
3966: sub store {
1.124 www 3967: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3968: my $home='';
3969:
1.168 albertel 3970: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3971:
1.213 www 3972: $symb=&symbclean($symb);
1.122 albertel 3973: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3974:
1.620 albertel 3975: if (!$domain) { $domain=$env{'user.domain'}; }
3976: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3977:
3978: &devalidate($symb,$stuname,$domain);
1.109 www 3979:
3980: $symb=escape($symb);
1.187 www 3981: if (!$namespace) {
1.620 albertel 3982: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3983: return '';
3984: }
3985: }
1.620 albertel 3986: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3987:
3988: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3989: $$storehash{'host'}=$perlvar{'lonHostID'};
3990:
1.12 www 3991: my $namevalue='';
1.800 albertel 3992: foreach my $key (keys(%$storehash)) {
3993: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3994: }
1.12 www 3995: $namevalue=~s/\&$//;
1.187 www 3996: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3997: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3998: }
3999:
1.47 www 4000: # -------------------------------------------------------------- Critical Store
4001:
4002: sub cstore {
1.124 www 4003: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4004: my $home='';
4005:
1.168 albertel 4006: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4007:
1.213 www 4008: $symb=&symbclean($symb);
1.122 albertel 4009: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4010:
1.620 albertel 4011: if (!$domain) { $domain=$env{'user.domain'}; }
4012: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4013:
4014: &devalidate($symb,$stuname,$domain);
1.109 www 4015:
4016: $symb=escape($symb);
1.187 www 4017: if (!$namespace) {
1.620 albertel 4018: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4019: return '';
4020: }
4021: }
1.620 albertel 4022: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4023:
4024: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4025: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4026:
1.47 www 4027: my $namevalue='';
1.800 albertel 4028: foreach my $key (keys(%$storehash)) {
4029: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4030: }
1.47 www 4031: $namevalue=~s/\&$//;
1.187 www 4032: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4033: return critical
4034: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4035: }
4036:
1.9 www 4037: # --------------------------------------------------------------------- Restore
4038:
4039: sub restore {
1.124 www 4040: my ($symb,$namespace,$domain,$stuname) = @_;
4041: my $home='';
4042:
1.168 albertel 4043: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4044:
1.122 albertel 4045: if (!$symb) {
4046: unless ($symb=escape(&symbread())) { return ''; }
4047: } else {
1.213 www 4048: $symb=&escape(&symbclean($symb));
1.122 albertel 4049: }
1.188 www 4050: if (!$namespace) {
1.620 albertel 4051: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4052: return '';
4053: }
4054: }
1.620 albertel 4055: if (!$domain) { $domain=$env{'user.domain'}; }
4056: if (!$stuname) { $stuname=$env{'user.name'}; }
4057: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4058: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4059:
1.12 www 4060: my %returnhash=();
1.800 albertel 4061: foreach my $line (split(/\&/,$answer)) {
4062: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4063: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4064: }
1.75 www 4065: my $version;
4066: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4067: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4068: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4069: }
1.75 www 4070: }
1.13 www 4071: return %returnhash;
1.34 www 4072: }
4073:
4074: # ---------------------------------------------------------- Course Description
4075:
4076: sub coursedescription {
1.731 albertel 4077: my ($courseid,$args)=@_;
1.34 www 4078: $courseid=~s/^\///;
1.49 www 4079: $courseid=~s/\_/\//g;
1.34 www 4080: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4081: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4082: my $normalid=$cdomain.'_'.$cnum;
4083: # need to always cache even if we get errors otherwise we keep
4084: # trying and trying and trying to get the course description.
4085: my %envhash=();
4086: my %returnhash=();
1.731 albertel 4087:
4088: my $expiretime=600;
4089: if ($env{'request.course.id'} eq $normalid) {
4090: $expiretime=120;
4091: }
4092:
4093: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4094: if (!$args->{'freshen_cache'}
4095: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4096: foreach my $key (keys(%env)) {
4097: next if ($key !~ /^\Q$prefix\E(.*)/);
4098: my ($setting) = $1;
4099: $returnhash{$setting} = $env{$key};
4100: }
4101: return %returnhash;
4102: }
4103:
4104: # get the data agin
4105: if (!$args->{'one_time'}) {
4106: $envhash{'course.'.$normalid.'.last_cache'}=time;
4107: }
1.811 albertel 4108:
1.34 www 4109: if ($chome ne 'no_host') {
1.302 albertel 4110: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4111: if (!exists($returnhash{'con_lost'})) {
4112: $returnhash{'home'}= $chome;
4113: $returnhash{'domain'} = $cdomain;
4114: $returnhash{'num'} = $cnum;
1.741 raeburn 4115: if (!defined($returnhash{'type'})) {
4116: $returnhash{'type'} = 'Course';
4117: }
1.130 albertel 4118: while (my ($name,$value) = each %returnhash) {
1.53 www 4119: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4120: }
1.270 www 4121: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4122: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4123: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4124: $envhash{'course.'.$normalid.'.home'}=$chome;
4125: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4126: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4127: }
4128: }
1.731 albertel 4129: if (!$args->{'one_time'}) {
1.949 raeburn 4130: &appenv(\%envhash);
1.731 albertel 4131: }
1.302 albertel 4132: return %returnhash;
1.461 www 4133: }
4134:
1.1056.4.5 raeburn 4135: sub update_released_required {
4136: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4137: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4138: $cid = $env{'request.course.id'};
4139: $cdom = $env{'course.'.$cid.'.domain'};
4140: $cnum = $env{'course.'.$cid.'.num'};
4141: $chome = $env{'course.'.$cid.'.home'};
4142: }
4143: if ($needsrelease) {
4144: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4145: my $needsupdate;
4146: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4147: $needsupdate = 1;
4148: } else {
4149: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4150: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4151: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4152: $needsupdate = 1;
4153: }
4154: }
4155: if ($needsupdate) {
4156: my %needshash = (
4157: 'internal.releaserequired' => $needsrelease,
4158: );
4159: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4160: if ($putresult eq 'ok') {
4161: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4162: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4163: if (ref($crsinfo{$cid}) eq 'HASH') {
4164: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4165: &courseidput($cdom,\%crsinfo,$chome,'notime');
4166: }
4167: }
4168: }
4169: }
4170: return;
4171: }
4172:
1.461 www 4173: # -------------------------------------------------See if a user is privileged
4174:
4175: sub privileged {
4176: my ($username,$domain)=@_;
4177: my $rolesdump=&reply("dump:$domain:$username:roles",
4178: &homeserver($username,$domain));
1.1033 raeburn 4179: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4180: ($rolesdump =~ /^error:/)) {
4181: return 0;
4182: }
1.461 www 4183: my $now=time;
4184: if ($rolesdump ne '') {
1.800 albertel 4185: foreach my $entry (split(/&/,$rolesdump)) {
4186: if ($entry!~/^rolesdef_/) {
4187: my ($area,$role)=split(/=/,$entry);
1.461 www 4188: $area=~s/\_\w\w$//;
4189: my ($trole,$tend,$tstart)=split(/_/,$role);
4190: if (($trole eq 'dc') || ($trole eq 'su')) {
4191: my $active=1;
4192: if ($tend) {
4193: if ($tend<$now) { $active=0; }
4194: }
4195: if ($tstart) {
4196: if ($tstart>$now) { $active=0; }
4197: }
4198: if ($active) { return 1; }
4199: }
4200: }
4201: }
4202: }
4203: return 0;
1.9 www 4204: }
1.1 albertel 4205:
1.103 harris41 4206: # -------------------------------------------------------- Get user privileges
1.11 www 4207:
4208: sub rolesinit {
4209: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4210: my $now=time;
4211: my %userroles = ('user.login.time' => $now);
1.1056.4.10 raeburn 4212: my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3 raeburn 4213: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4214: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1056.4.3 raeburn 4215: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4216: return \%userroles;
4217: }
1.11 www 4218: my %allroles=();
1.678 raeburn 4219: my %allgroups=();
4220: my $group_privs;
1.11 www 4221:
4222: if ($rolesdump ne '') {
1.800 albertel 4223: foreach my $entry (split(/&/,$rolesdump)) {
4224: if ($entry!~/^rolesdef_/) {
4225: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4226: $area=~s/\_\w\w$//;
1.678 raeburn 4227: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4228: if ($role=~/^cr/) {
1.807 albertel 4229: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4230: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4231: ($tend,$tstart)=split('_',$trest);
4232: } else {
4233: $trole=$role;
4234: }
1.678 raeburn 4235: } elsif ($role =~ m|^gr/|) {
4236: ($trole,$tend,$tstart) = split(/_/,$role);
4237: ($trole,$group_privs) = split(/\//,$trole);
4238: $group_privs = &unescape($group_privs);
1.587 albertel 4239: } else {
4240: ($trole,$tend,$tstart)=split(/_/,$role);
4241: }
1.743 albertel 4242: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4243: $username);
4244: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4245: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4246: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4247: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4248: my $spec=$trole.'.'.$area;
4249: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4250: if ($trole =~ /^cr\//) {
1.567 raeburn 4251: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4252: } elsif ($trole eq 'gr') {
4253: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4254: } else {
1.567 raeburn 4255: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4256: }
1.12 www 4257: }
1.662 raeburn 4258: }
1.191 harris41 4259: }
1.743 albertel 4260: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4261: $userroles{'user.adv'} = $adv;
4262: $userroles{'user.author'} = $author;
1.620 albertel 4263: $env{'user.adv'}=$adv;
1.11 www 4264: }
1.743 albertel 4265: return \%userroles;
1.11 www 4266: }
4267:
1.567 raeburn 4268: sub set_arearole {
4269: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4270: # log the associated role with the area
4271: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4272: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4273: }
4274:
4275: sub custom_roleprivs {
4276: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4277: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4278: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4279: if (&hostname($homsvr) ne '') {
1.567 raeburn 4280: my ($rdummy,$roledef)=
4281: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4282: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4283: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4284: if (defined($syspriv)) {
1.1043 raeburn 4285: if ($trest =~ /^$match_community$/) {
4286: $syspriv =~ s/bre\&S//;
4287: }
1.567 raeburn 4288: $$allroles{'cm./'}.=':'.$syspriv;
4289: $$allroles{$spec.'./'}.=':'.$syspriv;
4290: }
4291: if ($tdomain ne '') {
4292: if (defined($dompriv)) {
4293: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4294: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4295: }
4296: if (($trest ne '') && (defined($coursepriv))) {
4297: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4298: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4299: }
4300: }
4301: }
4302: }
4303: }
4304:
1.678 raeburn 4305: sub group_roleprivs {
4306: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4307: my $access = 1;
4308: my $now = time;
4309: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4310: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4311: if ($access) {
1.811 albertel 4312: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4313: $$allgroups{$course}{$group} .=':'.$group_privs;
4314: }
4315: }
1.567 raeburn 4316:
4317: sub standard_roleprivs {
4318: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4319: if (defined($pr{$trole.':s'})) {
4320: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4321: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4322: }
4323: if ($tdomain ne '') {
4324: if (defined($pr{$trole.':d'})) {
4325: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4326: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4327: }
4328: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4329: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4330: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4331: }
4332: }
4333: }
4334:
4335: sub set_userprivs {
1.1056.4.2 raeburn 4336: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4337: my $author=0;
4338: my $adv=0;
1.678 raeburn 4339: my %grouproles = ();
4340: if (keys(%{$allgroups}) > 0) {
1.1056.4.2 raeburn 4341: my @groupkeys;
1.1000 raeburn 4342: foreach my $role (keys(%{$allroles})) {
1.1056.4.2 raeburn 4343: push(@groupkeys,$role);
4344: }
4345: if (ref($groups_roles) eq 'HASH') {
4346: foreach my $key (keys(%{$groups_roles})) {
4347: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4348: push(@groupkeys,$key);
4349: }
4350: }
4351: }
4352: if (@groupkeys > 0) {
4353: foreach my $role (@groupkeys) {
4354: my ($trole,$area,$sec,$extendedarea);
4355: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4356: $trole = $1;
4357: $area = $2;
4358: $sec = $3;
4359: $extendedarea = $area.$sec;
4360: if (exists($$allgroups{$area})) {
4361: foreach my $group (keys(%{$$allgroups{$area}})) {
4362: my $spec = $trole.'.'.$extendedarea;
4363: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4364: $$allgroups{$area}{$group};
1.1056.4.2 raeburn 4365: }
1.678 raeburn 4366: }
4367: }
4368: }
4369: }
4370: }
1.800 albertel 4371: foreach my $group (keys(%grouproles)) {
4372: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4373: }
1.800 albertel 4374: foreach my $role (keys(%{$allroles})) {
4375: my %thesepriv;
1.941 raeburn 4376: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4377: foreach my $item (split(/:/,$$allroles{$role})) {
4378: if ($item ne '') {
4379: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4380: if ($restrictions eq '') {
4381: $thesepriv{$privilege}='F';
4382: } elsif ($thesepriv{$privilege} ne 'F') {
4383: $thesepriv{$privilege}.=$restrictions;
4384: }
4385: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4386: }
4387: }
4388: my $thesestr='';
1.800 albertel 4389: foreach my $priv (keys(%thesepriv)) {
4390: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4391: }
4392: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4393: }
4394: return ($author,$adv);
4395: }
4396:
1.994 raeburn 4397: sub role_status {
1.1002 raeburn 4398: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4399: my @pwhere = ();
4400: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4401: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4402: unless (!defined($$role) || $$role eq '') {
4403: $$where=join('.',@pwhere);
4404: $$trolecode=$$role.'.'.$$where;
4405: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4406: $$tstatus='is';
4407: if ($$tstart && $$tstart>$then) {
4408: $$tstatus='future';
1.1034 raeburn 4409: if ($$tstart<$now) {
4410: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4411: if (($$where ne '') && ($$role ne '')) {
1.1056.4.2 raeburn 4412: my (%allroles,%allgroups,$group_privs,
4413: %groups_roles,@rolecodes);
1.1002 raeburn 4414: my %userroles = (
4415: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4416: );
1.1056.4.2 raeburn 4417: @rolecodes = ('cm');
1.1002 raeburn 4418: my $spec=$$role.'.'.$$where;
4419: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4420: if ($$role =~ /^cr\//) {
4421: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2 raeburn 4422: push(@rolecodes,'cr');
1.1002 raeburn 4423: } elsif ($$role eq 'gr') {
1.1056.4.2 raeburn 4424: push(@rolecodes,$$role);
1.1002 raeburn 4425: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4426: $env{'user.name'});
1.1056.4.2 raeburn 4427: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4428: (undef,my $group_privs) = split(/\//,$trole);
4429: $group_privs = &unescape($group_privs);
4430: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2 raeburn 4431: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4432: if (keys(%course_roles) > 0) {
4433: my ($tnum) = ($trest =~ /^($match_courseid)/);
4434: if ($tdomain ne '' && $tnum ne '') {
4435: foreach my $key (keys(%course_roles)) {
4436: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4437: my $crsrole = $1;
4438: my $crssec = $2;
4439: if ($crsrole =~ /^cr/) {
4440: unless (grep(/^cr$/,@rolecodes)) {
4441: push(@rolecodes,'cr');
4442: }
4443: } else {
4444: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4445: push(@rolecodes,$crsrole);
4446: }
4447: }
4448: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4449: if ($crssec ne '') {
4450: $rolekey .= '/'.$crssec;
4451: }
4452: $rolekey .= './';
4453: $groups_roles{$rolekey} = \@rolecodes;
4454: }
4455: }
4456: }
4457: }
1.1002 raeburn 4458: } else {
1.1056.4.2 raeburn 4459: push(@rolecodes,$$role);
1.1002 raeburn 4460: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4461: }
1.1056.4.2 raeburn 4462: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4463: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4464: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4465: }
4466: }
1.1034 raeburn 4467: $$tstatus = 'is';
1.1002 raeburn 4468: }
1.994 raeburn 4469: }
4470: if ($$tend) {
4471: if ($$tend<$then) {
4472: $$tstatus='expired';
4473: } elsif ($$tend<$now) {
4474: $$tstatus='will_not';
4475: }
4476: }
4477: }
4478: }
4479: }
4480:
4481: sub check_adhoc_privs {
1.1056.4.12 raeburn 4482: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4483: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4484: if ($env{$cckey}) {
4485: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4486: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4487: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12 raeburn 4488: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4489: }
4490: } else {
1.1056.4.12 raeburn 4491: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4492: }
4493: }
4494:
4495: sub set_adhoc_privileges {
4496: # role can be cc or ca
1.1056.4.12 raeburn 4497: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4498: my $area = '/'.$dcdom.'/'.$pickedcourse;
4499: my $spec = $role.'.'.$area;
4500: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4501: $env{'user.name'});
4502: my %ccrole = ();
4503: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4504: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4505: &appenv(\%userroles,[$role,'cm']);
4506: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12 raeburn 4507: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4508: &appenv( {'request.role' => $spec,
4509: 'request.role.domain' => $dcdom,
4510: 'request.course.sec' => ''
4511: }
4512: );
4513: my $tadv=0;
4514: if (&allowed('adv') eq 'F') { $tadv=1; }
4515: &appenv({'request.role.adv' => $tadv});
4516: }
1.994 raeburn 4517: }
4518:
1.12 www 4519: # --------------------------------------------------------------- get interface
4520:
4521: sub get {
1.131 albertel 4522: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4523: my $items='';
1.800 albertel 4524: foreach my $item (@$storearr) {
4525: $items.=&escape($item).'&';
1.191 harris41 4526: }
1.12 www 4527: $items=~s/\&$//;
1.620 albertel 4528: if (!$udomain) { $udomain=$env{'user.domain'}; }
4529: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4530: my $uhome=&homeserver($uname,$udomain);
4531:
1.133 albertel 4532: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4533: my @pairs=split(/\&/,$rep);
1.273 albertel 4534: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4535: return @pairs;
4536: }
1.15 www 4537: my %returnhash=();
1.42 www 4538: my $i=0;
1.800 albertel 4539: foreach my $item (@$storearr) {
4540: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4541: $i++;
1.191 harris41 4542: }
1.15 www 4543: return %returnhash;
1.27 www 4544: }
4545:
4546: # --------------------------------------------------------------- del interface
4547:
4548: sub del {
1.133 albertel 4549: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4550: my $items='';
1.800 albertel 4551: foreach my $item (@$storearr) {
4552: $items.=&escape($item).'&';
1.191 harris41 4553: }
1.984 neumanie 4554:
1.27 www 4555: $items=~s/\&$//;
1.620 albertel 4556: if (!$udomain) { $udomain=$env{'user.domain'}; }
4557: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4558: my $uhome=&homeserver($uname,$udomain);
4559: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4560: }
4561:
4562: # -------------------------------------------------------------- dump interface
4563:
4564: sub dump {
1.1056.4.10 raeburn 4565: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4566: if (!$udomain) { $udomain=$env{'user.domain'}; }
4567: if (!$uname) { $uname=$env{'user.name'}; }
4568: my $uhome=&homeserver($uname,$udomain);
4569: if ($regexp) {
4570: $regexp=&escape($regexp);
4571: } else {
4572: $regexp='.';
4573: }
1.1056.4.10 raeburn 4574: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4575: my @pairs=split(/\&/,$rep);
4576: my %returnhash=();
4577: foreach my $item (@pairs) {
4578: my ($key,$value)=split(/=/,$item,2);
4579: $key = &unescape($key);
4580: next if ($key =~ /^error: 2 /);
4581: $returnhash{$key}=&thaw_unescape($value);
4582: }
4583: return %returnhash;
1.407 www 4584: }
4585:
1.717 albertel 4586: # --------------------------------------------------------- dumpstore interface
4587:
4588: sub dumpstore {
4589: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4590: if (!$udomain) { $udomain=$env{'user.domain'}; }
4591: if (!$uname) { $uname=$env{'user.name'}; }
4592: my $uhome=&homeserver($uname,$udomain);
4593: if ($regexp) {
4594: $regexp=&escape($regexp);
4595: } else {
4596: $regexp='.';
4597: }
4598: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4599: my @pairs=split(/\&/,$rep);
4600: my %returnhash=();
4601: foreach my $item (@pairs) {
4602: my ($key,$value)=split(/=/,$item,2);
4603: next if ($key =~ /^error: 2 /);
4604: $returnhash{$key}=&thaw_unescape($value);
4605: }
4606: return %returnhash;
1.717 albertel 4607: }
4608:
1.407 www 4609: # -------------------------------------------------------------- keys interface
4610:
4611: sub getkeys {
4612: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4613: if (!$udomain) { $udomain=$env{'user.domain'}; }
4614: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4615: my $uhome=&homeserver($uname,$udomain);
4616: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4617: my @keyarray=();
1.800 albertel 4618: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4619: next if ($key =~ /^error: 2 /);
1.800 albertel 4620: push(@keyarray,&unescape($key));
1.407 www 4621: }
4622: return @keyarray;
1.318 matthew 4623: }
4624:
1.319 matthew 4625: # --------------------------------------------------------------- currentdump
4626: sub currentdump {
1.328 matthew 4627: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4628: $courseid = $env{'request.course.id'} if (! defined($courseid));
4629: $sdom = $env{'user.domain'} if (! defined($sdom));
4630: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4631: my $uhome = &homeserver($sname,$sdom);
4632: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4633: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4634: #
1.318 matthew 4635: my %returnhash=();
1.319 matthew 4636: #
4637: if ($rep eq "unknown_cmd") {
4638: # an old lond will not know currentdump
4639: # Do a dump and make it look like a currentdump
1.822 albertel 4640: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4641: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4642: my %hash = @tmp;
4643: @tmp=();
1.424 matthew 4644: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4645: } else {
4646: my @pairs=split(/\&/,$rep);
1.800 albertel 4647: foreach my $pair (@pairs) {
4648: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4649: my ($symb,$param) = split(/:/,$key);
4650: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4651: &thaw_unescape($value);
1.319 matthew 4652: }
1.191 harris41 4653: }
1.12 www 4654: return %returnhash;
1.424 matthew 4655: }
4656:
4657: sub convert_dump_to_currentdump{
4658: my %hash = %{shift()};
4659: my %returnhash;
4660: # Code ripped from lond, essentially. The only difference
4661: # here is the unescaping done by lonnet::dump(). Conceivably
4662: # we might run in to problems with parameter names =~ /^v\./
4663: while (my ($key,$value) = each(%hash)) {
4664: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4665: $symb = &unescape($symb);
4666: $param = &unescape($param);
1.424 matthew 4667: next if ($v eq 'version' || $symb eq 'keys');
4668: next if (exists($returnhash{$symb}) &&
4669: exists($returnhash{$symb}->{$param}) &&
4670: $returnhash{$symb}->{'v.'.$param} > $v);
4671: $returnhash{$symb}->{$param}=$value;
4672: $returnhash{$symb}->{'v.'.$param}=$v;
4673: }
4674: #
4675: # Remove all of the keys in the hashes which keep track of
4676: # the version of the parameter.
4677: while (my ($symb,$param_hash) = each(%returnhash)) {
4678: # use a foreach because we are going to delete from the hash.
4679: foreach my $key (keys(%$param_hash)) {
4680: delete($param_hash->{$key}) if ($key =~ /^v\./);
4681: }
4682: }
4683: return \%returnhash;
1.12 www 4684: }
4685:
1.627 albertel 4686: # ------------------------------------------------------ critical inc interface
4687:
4688: sub cinc {
4689: return &inc(@_,'critical');
4690: }
4691:
1.449 matthew 4692: # --------------------------------------------------------------- inc interface
4693:
4694: sub inc {
1.627 albertel 4695: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4696: if (!$udomain) { $udomain=$env{'user.domain'}; }
4697: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4698: my $uhome=&homeserver($uname,$udomain);
4699: my $items='';
4700: if (! ref($store)) {
4701: # got a single value, so use that instead
4702: $items = &escape($store).'=&';
4703: } elsif (ref($store) eq 'SCALAR') {
4704: $items = &escape($$store).'=&';
4705: } elsif (ref($store) eq 'ARRAY') {
4706: $items = join('=&',map {&escape($_);} @{$store});
4707: } elsif (ref($store) eq 'HASH') {
4708: while (my($key,$value) = each(%{$store})) {
4709: $items.= &escape($key).'='.&escape($value).'&';
4710: }
4711: }
4712: $items=~s/\&$//;
1.627 albertel 4713: if ($critical) {
4714: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4715: } else {
4716: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4717: }
1.449 matthew 4718: }
4719:
1.12 www 4720: # --------------------------------------------------------------- put interface
4721:
4722: sub put {
1.134 albertel 4723: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4724: if (!$udomain) { $udomain=$env{'user.domain'}; }
4725: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4726: my $uhome=&homeserver($uname,$udomain);
1.12 www 4727: my $items='';
1.800 albertel 4728: foreach my $item (keys(%$storehash)) {
4729: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4730: }
1.12 www 4731: $items=~s/\&$//;
1.134 albertel 4732: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4733: }
4734:
1.631 albertel 4735: # ------------------------------------------------------------ newput interface
4736:
4737: sub newput {
4738: my ($namespace,$storehash,$udomain,$uname)=@_;
4739: if (!$udomain) { $udomain=$env{'user.domain'}; }
4740: if (!$uname) { $uname=$env{'user.name'}; }
4741: my $uhome=&homeserver($uname,$udomain);
4742: my $items='';
4743: foreach my $key (keys(%$storehash)) {
4744: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4745: }
4746: $items=~s/\&$//;
4747: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4748: }
4749:
4750: # --------------------------------------------------------- putstore interface
4751:
1.524 raeburn 4752: sub putstore {
1.715 albertel 4753: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4754: if (!$udomain) { $udomain=$env{'user.domain'}; }
4755: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4756: my $uhome=&homeserver($uname,$udomain);
4757: my $items='';
1.715 albertel 4758: foreach my $key (keys(%$storehash)) {
4759: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4760: }
1.715 albertel 4761: $items=~s/\&$//;
1.716 albertel 4762: my $esc_symb=&escape($symb);
4763: my $esc_v=&escape($version);
1.715 albertel 4764: my $reply =
1.716 albertel 4765: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4766: $uhome);
4767: if ($reply eq 'unknown_cmd') {
1.716 albertel 4768: # gfall back to way things use to be done
1.715 albertel 4769: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4770: $uname);
1.524 raeburn 4771: }
1.715 albertel 4772: return $reply;
4773: }
4774:
4775: sub old_putstore {
1.716 albertel 4776: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4777: if (!$udomain) { $udomain=$env{'user.domain'}; }
4778: if (!$uname) { $uname=$env{'user.name'}; }
4779: my $uhome=&homeserver($uname,$udomain);
4780: my %newstorehash;
1.800 albertel 4781: foreach my $item (keys(%$storehash)) {
4782: my $key = $version.':'.&escape($symb).':'.$item;
4783: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4784: }
4785: my $items='';
4786: my %allitems = ();
1.800 albertel 4787: foreach my $item (keys(%newstorehash)) {
4788: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4789: my $key = $1.':keys:'.$2;
4790: $allitems{$key} .= $3.':';
4791: }
1.800 albertel 4792: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4793: }
1.800 albertel 4794: foreach my $item (keys(%allitems)) {
4795: $allitems{$item} =~ s/\:$//;
4796: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4797: }
4798: $items=~s/\&$//;
4799: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4800: }
4801:
1.47 www 4802: # ------------------------------------------------------ critical put interface
4803:
4804: sub cput {
1.134 albertel 4805: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4806: if (!$udomain) { $udomain=$env{'user.domain'}; }
4807: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4808: my $uhome=&homeserver($uname,$udomain);
1.47 www 4809: my $items='';
1.800 albertel 4810: foreach my $item (keys(%$storehash)) {
4811: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4812: }
1.47 www 4813: $items=~s/\&$//;
1.134 albertel 4814: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4815: }
4816:
4817: # -------------------------------------------------------------- eget interface
4818:
4819: sub eget {
1.133 albertel 4820: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4821: my $items='';
1.800 albertel 4822: foreach my $item (@$storearr) {
4823: $items.=&escape($item).'&';
1.191 harris41 4824: }
1.12 www 4825: $items=~s/\&$//;
1.620 albertel 4826: if (!$udomain) { $udomain=$env{'user.domain'}; }
4827: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4828: my $uhome=&homeserver($uname,$udomain);
4829: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4830: my @pairs=split(/\&/,$rep);
4831: my %returnhash=();
1.42 www 4832: my $i=0;
1.800 albertel 4833: foreach my $item (@$storearr) {
4834: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4835: $i++;
1.191 harris41 4836: }
1.12 www 4837: return %returnhash;
4838: }
4839:
1.667 albertel 4840: # ------------------------------------------------------------ tmpput interface
4841: sub tmpput {
1.802 raeburn 4842: my ($storehash,$server,$context)=@_;
1.667 albertel 4843: my $items='';
1.800 albertel 4844: foreach my $item (keys(%$storehash)) {
4845: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4846: }
4847: $items=~s/\&$//;
1.802 raeburn 4848: if (defined($context)) {
4849: $items .= ':'.&escape($context);
4850: }
1.667 albertel 4851: return &reply("tmpput:$items",$server);
4852: }
4853:
4854: # ------------------------------------------------------------ tmpget interface
4855: sub tmpget {
1.688 albertel 4856: my ($token,$server)=@_;
4857: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4858: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4859: my %returnhash;
4860: foreach my $item (split(/\&/,$rep)) {
4861: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4862: next if ($key =~ /^error: 2 /);
1.667 albertel 4863: $returnhash{&unescape($key)}=&thaw_unescape($value);
4864: }
4865: return %returnhash;
4866: }
4867:
1.688 albertel 4868: # ------------------------------------------------------------ tmpget interface
4869: sub tmpdel {
4870: my ($token,$server)=@_;
4871: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4872: return &reply("tmpdel:$token",$server);
4873: }
4874:
1.765 albertel 4875: # -------------------------------------------------- portfolio access checking
4876:
4877: sub portfolio_access {
1.766 albertel 4878: my ($requrl) = @_;
1.765 albertel 4879: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4880: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4881: if ($result) {
4882: my %setters;
4883: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4884: my ($startblock,$endblock) =
4885: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4886: if ($startblock && $endblock) {
4887: return 'B';
4888: }
4889: } else {
4890: my ($startblock,$endblock) =
4891: &Apache::loncommon::blockcheck(\%setters,'port');
4892: if ($startblock && $endblock) {
4893: return 'B';
4894: }
4895: }
4896: }
1.765 albertel 4897: if ($result eq 'ok') {
1.766 albertel 4898: return 'F';
1.765 albertel 4899: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4900: return 'A';
1.765 albertel 4901: }
1.766 albertel 4902: return '';
1.765 albertel 4903: }
4904:
4905: sub get_portfolio_access {
1.767 albertel 4906: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4907:
4908: if (!ref($access_hash)) {
4909: my $current_perms = &get_portfile_permissions($udom,$unum);
4910: my %access_controls = &get_access_controls($current_perms,$group,
4911: $file_name);
4912: $access_hash = $access_controls{$file_name};
4913: }
4914:
1.765 albertel 4915: my ($public,$guest,@domains,@users,@courses,@groups);
4916: my $now = time;
4917: if (ref($access_hash) eq 'HASH') {
4918: foreach my $key (keys(%{$access_hash})) {
4919: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4920: if ($start > $now) {
4921: next;
4922: }
4923: if ($end && $end<$now) {
4924: next;
4925: }
4926: if ($scope eq 'public') {
4927: $public = $key;
4928: last;
4929: } elsif ($scope eq 'guest') {
4930: $guest = $key;
4931: } elsif ($scope eq 'domains') {
4932: push(@domains,$key);
4933: } elsif ($scope eq 'users') {
4934: push(@users,$key);
4935: } elsif ($scope eq 'course') {
4936: push(@courses,$key);
4937: } elsif ($scope eq 'group') {
4938: push(@groups,$key);
4939: }
4940: }
4941: if ($public) {
4942: return 'ok';
4943: }
4944: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4945: if ($guest) {
4946: return $guest;
4947: }
4948: } else {
4949: if (@domains > 0) {
4950: foreach my $domkey (@domains) {
4951: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4952: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4953: return 'ok';
4954: }
4955: }
4956: }
4957: }
4958: if (@users > 0) {
4959: foreach my $userkey (@users) {
1.865 raeburn 4960: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4961: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4962: if (ref($item) eq 'HASH') {
4963: if (($item->{'uname'} eq $env{'user.name'}) &&
4964: ($item->{'udom'} eq $env{'user.domain'})) {
4965: return 'ok';
4966: }
4967: }
4968: }
4969: }
1.765 albertel 4970: }
4971: }
4972: my %roleshash;
4973: my @courses_and_groups = @courses;
4974: push(@courses_and_groups,@groups);
4975: if (@courses_and_groups > 0) {
4976: my (%allgroups,%allroles);
4977: my ($start,$end,$role,$sec,$group);
4978: foreach my $envkey (%env) {
1.1056.4.1 raeburn 4979: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4980: my $cid = $2.'_'.$3;
4981: if ($1 eq 'gr') {
4982: $group = $4;
4983: $allgroups{$cid}{$group} = $env{$envkey};
4984: } else {
4985: if ($4 eq '') {
4986: $sec = 'none';
4987: } else {
4988: $sec = $4;
4989: }
4990: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4991: }
1.811 albertel 4992: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4993: my $cid = $2.'_'.$3;
4994: if ($4 eq '') {
4995: $sec = 'none';
4996: } else {
4997: $sec = $4;
4998: }
4999: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5000: }
5001: }
5002: if (keys(%allroles) == 0) {
5003: return;
5004: }
5005: foreach my $key (@courses_and_groups) {
5006: my %content = %{$$access_hash{$key}};
5007: my $cnum = $content{'number'};
5008: my $cdom = $content{'domain'};
5009: my $cid = $cdom.'_'.$cnum;
5010: if (!exists($allroles{$cid})) {
5011: next;
5012: }
5013: foreach my $role_id (keys(%{$content{'roles'}})) {
5014: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5015: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5016: my @status = @{$content{'roles'}{$role_id}{'access'}};
5017: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5018: foreach my $role (keys(%{$allroles{$cid}})) {
5019: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5020: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5021: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5022: if (grep/^all$/,@sections) {
5023: return 'ok';
5024: } else {
5025: if (grep/^$sec$/,@sections) {
5026: return 'ok';
5027: }
5028: }
5029: }
5030: }
5031: if (keys(%{$allgroups{$cid}}) == 0) {
5032: if (grep/^none$/,@groups) {
5033: return 'ok';
5034: }
5035: } else {
5036: if (grep/^all$/,@groups) {
5037: return 'ok';
5038: }
5039: foreach my $group (keys(%{$allgroups{$cid}})) {
5040: if (grep/^$group$/,@groups) {
5041: return 'ok';
5042: }
5043: }
5044: }
5045: }
5046: }
5047: }
5048: }
5049: }
5050: if ($guest) {
5051: return $guest;
5052: }
5053: }
5054: }
5055: return;
5056: }
5057:
5058: sub course_group_datechecker {
5059: my ($dates,$now,$status) = @_;
5060: my ($start,$end) = split(/\./,$dates);
5061: if (!$start && !$end) {
5062: return 'ok';
5063: }
5064: if (grep/^active$/,@{$status}) {
5065: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5066: return 'ok';
5067: }
5068: }
5069: if (grep/^previous$/,@{$status}) {
5070: if ($end > $now ) {
5071: return 'ok';
5072: }
5073: }
5074: if (grep/^future$/,@{$status}) {
5075: if ($start > $now) {
5076: return 'ok';
5077: }
5078: }
5079: return;
5080: }
5081:
5082: sub parse_portfolio_url {
5083: my ($url) = @_;
5084:
5085: my ($type,$udom,$unum,$group,$file_name);
5086:
1.823 albertel 5087: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5088: $type = 1;
5089: $udom = $1;
5090: $unum = $2;
5091: $file_name = $3;
1.823 albertel 5092: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5093: $type = 2;
5094: $udom = $1;
5095: $unum = $2;
5096: $group = $3;
5097: $file_name = $3.'/'.$4;
5098: }
5099: if (wantarray) {
5100: return ($type,$udom,$unum,$file_name,$group);
5101: }
5102: return $type;
5103: }
5104:
5105: sub is_portfolio_url {
5106: my ($url) = @_;
5107: return scalar(&parse_portfolio_url($url));
5108: }
5109:
1.798 raeburn 5110: sub is_portfolio_file {
5111: my ($file) = @_;
1.820 raeburn 5112: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5113: return 1;
5114: }
5115: return;
5116: }
5117:
1.976 raeburn 5118: sub usertools_access {
1.1056.4.9 raeburn 5119: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985 raeburn 5120: my ($access,%tools);
5121: if ($context eq '') {
5122: $context = 'tools';
5123: }
5124: if ($context eq 'requestcourses') {
5125: %tools = (
5126: official => 1,
5127: unofficial => 1,
1.1006 raeburn 5128: community => 1,
1.985 raeburn 5129: );
5130: } else {
5131: %tools = (
5132: aboutme => 1,
5133: blog => 1,
5134: portfolio => 1,
5135: );
5136: }
1.976 raeburn 5137: return if (!defined($tools{$tool}));
5138:
5139: if ((!defined($udom)) || (!defined($uname))) {
5140: $udom = $env{'user.domain'};
5141: $uname = $env{'user.name'};
5142: }
5143:
1.978 raeburn 5144: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5145: if ($action ne 'reload') {
1.985 raeburn 5146: if ($context eq 'requestcourses') {
5147: return $env{'environment.canrequest.'.$tool};
5148: } else {
5149: return $env{'environment.availabletools.'.$tool};
5150: }
5151: }
1.976 raeburn 5152: }
5153:
5154: my ($toolstatus,$inststatus);
5155:
1.985 raeburn 5156: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5157: ($action ne 'reload')) {
5158: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5159: $inststatus = $env{'environment.inststatus'};
5160: } else {
1.1056.4.9 raeburn 5161: if (ref($userenvref) eq 'HASH') {
5162: $toolstatus = $userenvref->{$context.'.'.$tool};
5163: $inststatus = $userenvref->{'inststatus'};
5164: } else {
5165: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5166: $toolstatus = $userenv{$context.'.'.$tool};
5167: $inststatus = $userenv{'inststatus'};
5168: }
1.976 raeburn 5169: }
5170:
5171: if ($toolstatus ne '') {
5172: if ($toolstatus) {
5173: $access = 1;
5174: } else {
5175: $access = 0;
5176: }
5177: return $access;
5178: }
5179:
1.1056.4.9 raeburn 5180: my ($is_adv,%domdef);
5181: if (ref($is_advref) eq 'HASH') {
5182: $is_adv = $is_advref->{'is_adv'};
5183: } else {
5184: $is_adv = &is_advanced_user($udom,$uname);
5185: }
5186: if (ref($domdefref) eq 'HASH') {
5187: %domdef = %{$domdefref};
5188: } else {
5189: %domdef = &get_domain_defaults($udom);
5190: }
1.976 raeburn 5191: if (ref($domdef{$tool}) eq 'HASH') {
5192: if ($is_adv) {
5193: if ($domdef{$tool}{'_LC_adv'} ne '') {
5194: if ($domdef{$tool}{'_LC_adv'}) {
5195: $access = 1;
5196: } else {
5197: $access = 0;
5198: }
5199: return $access;
5200: }
5201: }
5202: if ($inststatus ne '') {
5203: my ($hasaccess,$hasnoaccess);
5204: foreach my $affiliation (split(/:/,$inststatus)) {
5205: if ($domdef{$tool}{$affiliation} ne '') {
5206: if ($domdef{$tool}{$affiliation}) {
5207: $hasaccess = 1;
5208: } else {
5209: $hasnoaccess = 1;
5210: }
5211: }
5212: }
5213: if ($hasaccess || $hasnoaccess) {
5214: if ($hasaccess) {
5215: $access = 1;
5216: } elsif ($hasnoaccess) {
5217: $access = 0;
5218: }
5219: return $access;
5220: }
5221: } else {
5222: if ($domdef{$tool}{'default'} ne '') {
5223: if ($domdef{$tool}{'default'}) {
5224: $access = 1;
5225: } elsif ($domdef{$tool}{'default'} == 0) {
5226: $access = 0;
5227: }
5228: return $access;
5229: }
5230: }
5231: } else {
1.985 raeburn 5232: if ($context eq 'tools') {
5233: $access = 1;
5234: } else {
5235: $access = 0;
5236: }
1.976 raeburn 5237: return $access;
5238: }
5239: }
5240:
1.1050 raeburn 5241: sub is_course_owner {
5242: my ($cdom,$cnum,$udom,$uname) = @_;
5243: if (($udom eq '') || ($uname eq '')) {
5244: $udom = $env{'user.domain'};
5245: $uname = $env{'user.name'};
5246: }
5247: unless (($udom eq '') || ($uname eq '')) {
5248: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5249: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5250: return 1;
5251: } else {
5252: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5253: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5254: return 1;
5255: }
5256: }
5257: }
5258: }
5259: return;
5260: }
5261:
1.976 raeburn 5262: sub is_advanced_user {
5263: my ($udom,$uname) = @_;
1.1056.4.10 raeburn 5264: if ($udom ne '' && $uname ne '') {
5265: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5266: return $env{'user.adv'};
5267: }
5268: }
1.976 raeburn 5269: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5270: my %allroles;
5271: my $is_adv;
5272: foreach my $role (keys(%roleshash)) {
5273: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5274: my $area = '/'.$tdomain.'/'.$trest;
5275: if ($sec ne '') {
5276: $area .= '/'.$sec;
5277: }
5278: if (($area ne '') && ($trole ne '')) {
5279: my $spec=$trole.'.'.$area;
5280: if ($trole =~ /^cr\//) {
5281: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5282: } elsif ($trole ne 'gr') {
5283: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5284: }
5285: }
5286: }
5287: foreach my $role (keys(%allroles)) {
5288: last if ($is_adv);
5289: foreach my $item (split(/:/,$allroles{$role})) {
5290: if ($item ne '') {
5291: my ($privilege,$restrictions)=split(/&/,$item);
5292: if ($privilege eq 'adv') {
5293: $is_adv = 1;
5294: last;
5295: }
5296: }
5297: }
5298: }
5299: return $is_adv;
5300: }
1.798 raeburn 5301:
1.1035 raeburn 5302: sub check_can_request {
1.1036 raeburn 5303: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5304: my $canreq = 0;
5305: my ($types,$typename) = &Apache::loncommon::course_types();
5306: my @options = ('approval','validate','autolimit');
5307: my $optregex = join('|',@options);
5308: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5309: foreach my $type (@{$types}) {
5310: if (&usertools_access($env{'user.name'},
5311: $env{'user.domain'},
5312: $type,undef,'requestcourses')) {
5313: $canreq ++;
1.1036 raeburn 5314: if (ref($request_domains) eq 'HASH') {
5315: push(@{$request_domains->{$type}},$env{'user.domain'});
5316: }
1.1035 raeburn 5317: if ($dom eq $env{'user.domain'}) {
5318: $can_request->{$type} = 1;
5319: }
5320: }
5321: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5322: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5323: if (@curr > 0) {
1.1036 raeburn 5324: foreach my $item (@curr) {
5325: if (ref($request_domains) eq 'HASH') {
5326: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5327: if ($otherdom ne '') {
5328: if (ref($request_domains->{$type}) eq 'ARRAY') {
5329: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5330: push(@{$request_domains->{$type}},$otherdom);
5331: }
5332: } else {
5333: push(@{$request_domains->{$type}},$otherdom);
5334: }
5335: }
5336: }
5337: }
5338: unless($dom eq $env{'user.domain'}) {
5339: $canreq ++;
1.1035 raeburn 5340: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5341: $can_request->{$type} = 1;
5342: }
5343: }
5344: }
5345: }
5346: }
5347: }
5348: return $canreq;
5349: }
5350:
1.341 www 5351: # ---------------------------------------------- Custom access rule evaluation
5352:
5353: sub customaccess {
5354: my ($priv,$uri)=@_;
1.807 albertel 5355: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5356: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5357: $udom = &LONCAPA::clean_domain($udom);
5358: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5359: my $access=0;
1.800 albertel 5360: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5361: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5362: if ($type eq 'user') {
5363: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5364: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5365: if ($tdom) {
5366: if ($tdom ne $env{'user.domain'}) { next; }
5367: }
1.896 albertel 5368: if ($tuname) {
5369: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5370: }
5371: $access=($effect eq 'allow');
5372: last;
5373: }
5374: } else {
5375: if ($role) {
5376: if ($role ne $urole) { next; }
5377: }
5378: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5379: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5380: if ($tdom) {
5381: if ($tdom ne $udom) { next; }
5382: }
5383: if ($tcrs) {
5384: if ($tcrs ne $ucrs) { next; }
5385: }
5386: if ($tsec) {
5387: if ($tsec ne $usec) { next; }
5388: }
5389: $access=($effect eq 'allow');
5390: last;
5391: }
5392: if ($realm eq '' && $role eq '') {
5393: $access=($effect eq 'allow');
5394: }
1.402 bowersj2 5395: }
1.341 www 5396: }
5397: return $access;
5398: }
5399:
1.103 harris41 5400: # ------------------------------------------------- Check for a user privilege
1.12 www 5401:
5402: sub allowed {
1.810 raeburn 5403: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5404: my $ver_orguri=$uri;
1.439 www 5405: $uri=&deversion($uri);
1.152 www 5406: my $orguri=$uri;
1.52 www 5407: $uri=&declutter($uri);
1.809 raeburn 5408:
1.810 raeburn 5409: if ($priv eq 'evb') {
5410: # Evade communication block restrictions for specified role in a course
5411: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5412: return $1;
5413: } else {
5414: return;
5415: }
5416: }
5417:
1.620 albertel 5418: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5419: # Free bre access to adm and meta resources
1.775 albertel 5420: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5421: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5422: && ($priv eq 'bre')) {
1.14 www 5423: return 'F';
1.159 www 5424: }
5425:
1.545 banghart 5426: # Free bre access to user's own portfolio contents
1.714 raeburn 5427: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5428: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5429: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5430: my %setters;
5431: my ($startblock,$endblock) =
5432: &Apache::loncommon::blockcheck(\%setters,'port');
5433: if ($startblock && $endblock) {
5434: return 'B';
5435: } else {
5436: return 'F';
5437: }
1.545 banghart 5438: }
5439:
1.762 raeburn 5440: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5441: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5442: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5443: if (exists($env{'request.course.id'})) {
5444: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5445: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5446: if (($domain eq $cdom) && ($name eq $cnum)) {
5447: my $courseprivid=$env{'request.course.id'};
5448: $courseprivid=~s/\_/\//;
5449: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5450: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5451: return $1;
1.762 raeburn 5452: } else {
5453: if ($env{'request.course.sec'}) {
5454: $courseprivid.='/'.$env{'request.course.sec'};
5455: }
5456: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5457: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5458: return $2;
5459: }
1.714 raeburn 5460: }
5461: }
5462: }
5463: }
5464:
1.159 www 5465: # Free bre to public access
5466:
5467: if ($priv eq 'bre') {
1.238 www 5468: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5469: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5470: return 'F';
5471: }
1.238 www 5472: if ($copyright eq 'priv') {
5473: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5474: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5475: return '';
5476: }
5477: }
5478: if ($copyright eq 'domain') {
5479: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5480: unless (($env{'user.domain'} eq $1) ||
5481: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5482: return '';
5483: }
1.262 matthew 5484: }
1.620 albertel 5485: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5486: # Library role, so allow browsing of resources in this domain.
5487: return 'F';
1.238 www 5488: }
1.341 www 5489: if ($copyright eq 'custom') {
5490: unless (&customaccess($priv,$uri)) { return ''; }
5491: }
1.14 www 5492: }
1.264 matthew 5493: # Domain coordinator is trying to create a course
1.620 albertel 5494: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5495: # uri is the requested domain in this case.
5496: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5497: # a role of dc for the domain in question.
1.620 albertel 5498: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5499: }
1.29 www 5500:
1.52 www 5501: my $thisallowed='';
5502: my $statecond=0;
5503: my $courseprivid='';
5504:
1.1039 raeburn 5505: my $ownaccess;
1.1043 raeburn 5506: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5507: if (($priv eq 'bro') && ($env{'user.author'})) {
5508: if ($uri eq '') {
5509: $ownaccess = 1;
5510: } else {
5511: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5512: my $udom = $env{'user.domain'};
5513: my $uname = $env{'user.name'};
5514: if ($uri =~ m{^\Q$udom\E/?$}) {
5515: $ownaccess = 1;
1.1040 raeburn 5516: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5517: unless ($uri =~ m{\.\./}) {
5518: $ownaccess = 1;
5519: }
5520: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5521: my $now = time;
5522: if ($uri =~ m{^([^/]+)/?$}) {
5523: my $adom = $1;
5524: foreach my $key (keys(%env)) {
1.1042 raeburn 5525: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5526: my ($start,$end) = split('.',$env{$key});
5527: if (($now >= $start) && (!$end || $end < $now)) {
5528: $ownaccess = 1;
5529: last;
5530: }
5531: }
5532: }
5533: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5534: my $adom = $1;
5535: my $aname = $2;
1.1042 raeburn 5536: foreach my $role ('ca','aa') {
5537: if ($env{"user.role.$role./$adom/$aname"}) {
5538: my ($start,$end) =
5539: split('.',$env{"user.role.$role./$adom/$aname"});
5540: if (($now >= $start) && (!$end || $end < $now)) {
5541: $ownaccess = 1;
5542: last;
5543: }
1.1039 raeburn 5544: }
5545: }
5546: }
5547: }
5548: }
5549: }
5550: }
5551:
1.52 www 5552: # Course
5553:
1.620 albertel 5554: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5555: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5556: $thisallowed.=$1;
5557: }
1.52 www 5558: }
1.29 www 5559:
1.52 www 5560: # Domain
5561:
1.620 albertel 5562: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5563: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5564: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5565: $thisallowed.=$1;
5566: }
1.12 www 5567: }
1.52 www 5568:
5569: # Course: uri itself is a course
1.66 www 5570: my $courseuri=$uri;
5571: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5572: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5573:
1.620 albertel 5574: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5575: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5576: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5577: $thisallowed.=$1;
5578: }
1.12 www 5579: }
1.29 www 5580:
1.665 albertel 5581: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5582: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5583: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5584: $thisallowed='';
1.671 raeburn 5585: my ($match)=&is_on_map($uri);
5586: if ($match) {
5587: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5588: =~/\Q$priv\E\&([^\:]*)/) {
5589: $thisallowed.=$1;
5590: }
5591: } else {
1.705 albertel 5592: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5593: if ($refuri) {
5594: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5595: $thisallowed='F';
1.671 raeburn 5596: } else {
5597: $refuri=&declutter($refuri);
5598: my ($match) = &is_on_map($refuri);
5599: if ($match) {
5600: $thisallowed='F';
5601: }
1.669 raeburn 5602: }
1.671 raeburn 5603: }
5604: }
1.314 www 5605: }
1.492 albertel 5606:
1.766 albertel 5607: if ($priv eq 'bre'
5608: && $thisallowed ne 'F'
5609: && $thisallowed ne '2'
5610: && &is_portfolio_url($uri)) {
5611: $thisallowed = &portfolio_access($uri);
5612: }
5613:
1.52 www 5614: # Full access at system, domain or course-wide level? Exit.
1.29 www 5615: if ($thisallowed=~/F/) {
5616: return 'F';
5617: }
5618:
1.52 www 5619: # If this is generating or modifying users, exit with special codes
1.29 www 5620:
1.643 www 5621: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5622: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5623: my ($audom,$auname)=split('/',$uri);
1.643 www 5624: # no author name given, so this just checks on the general right to make a co-author in this domain
5625: unless ($auname) { return $thisallowed; }
5626: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5627: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5628: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5629: ($audom ne $env{'request.role.domain'}))) { return ''; }
5630: }
1.52 www 5631: return $thisallowed;
5632: }
5633: #
1.103 harris41 5634: # Gathered so far: system, domain and course wide privileges
1.52 www 5635: #
5636: # Course: See if uri or referer is an individual resource that is part of
5637: # the course
5638:
1.620 albertel 5639: if ($env{'request.course.id'}) {
1.232 www 5640:
1.620 albertel 5641: $courseprivid=$env{'request.course.id'};
5642: if ($env{'request.course.sec'}) {
5643: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5644: }
5645: $courseprivid=~s/\_/\//;
5646: my $checkreferer=1;
1.232 www 5647: my ($match,$cond)=&is_on_map($uri);
5648: if ($match) {
5649: $statecond=$cond;
1.620 albertel 5650: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5651: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5652: $thisallowed.=$1;
5653: $checkreferer=0;
5654: }
1.29 www 5655: }
1.83 www 5656:
1.148 www 5657: if ($checkreferer) {
1.620 albertel 5658: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5659: unless ($refuri) {
1.800 albertel 5660: foreach my $key (keys(%env)) {
5661: if ($key=~/^httpref\..*\*/) {
5662: my $pattern=$key;
1.156 www 5663: $pattern=~s/^httpref\.\/res\///;
1.148 www 5664: $pattern=~s/\*/\[\^\/\]\+/g;
5665: $pattern=~s/\//\\\//g;
1.152 www 5666: if ($orguri=~/$pattern/) {
1.800 albertel 5667: $refuri=$env{$key};
1.148 www 5668: }
5669: }
1.191 harris41 5670: }
1.148 www 5671: }
1.232 www 5672:
1.148 www 5673: if ($refuri) {
1.152 www 5674: $refuri=&declutter($refuri);
1.232 www 5675: my ($match,$cond)=&is_on_map($refuri);
5676: if ($match) {
5677: my $refstatecond=$cond;
1.620 albertel 5678: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5679: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5680: $thisallowed.=$1;
1.53 www 5681: $uri=$refuri;
5682: $statecond=$refstatecond;
1.52 www 5683: }
5684: }
1.148 www 5685: }
1.29 www 5686: }
1.52 www 5687: }
1.29 www 5688:
1.52 www 5689: #
1.103 harris41 5690: # Gathered now: all privileges that could apply, and condition number
1.52 www 5691: #
5692: #
5693: # Full or no access?
5694: #
1.29 www 5695:
1.52 www 5696: if ($thisallowed=~/F/) {
5697: return 'F';
5698: }
1.29 www 5699:
1.52 www 5700: unless ($thisallowed) {
5701: return '';
5702: }
1.29 www 5703:
1.52 www 5704: # Restrictions exist, deal with them
5705: #
5706: # C:according to course preferences
5707: # R:according to resource settings
5708: # L:unless locked
5709: # X:according to user session state
5710: #
5711:
5712: # Possibly locked functionality, check all courses
1.54 www 5713: # Locks might take effect only after 10 minutes cache expiration for other
5714: # courses, and 2 minutes for current course
1.52 www 5715:
5716: my $envkey;
5717: if ($thisallowed=~/L/) {
1.1000 raeburn 5718: foreach $envkey (keys(%env)) {
1.54 www 5719: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5720: my $courseid=$2;
5721: my $roleid=$1.'.'.$2;
1.92 www 5722: $courseid=~s/^\///;
1.54 www 5723: my $expiretime=600;
1.620 albertel 5724: if ($env{'request.role'} eq $roleid) {
1.54 www 5725: $expiretime=120;
5726: }
5727: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5728: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5729: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5730: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5731: }
1.620 albertel 5732: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5733: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5734: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5735: &log($env{'user.domain'},$env{'user.name'},
5736: $env{'user.home'},
1.57 www 5737: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5738: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5739: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5740: return '';
5741: }
5742: }
1.620 albertel 5743: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5744: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5745: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5746: &log($env{'user.domain'},$env{'user.name'},
5747: $env{'user.home'},
1.57 www 5748: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5749: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5750: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5751: return '';
5752: }
5753: }
5754: }
1.29 www 5755: }
1.52 www 5756: }
5757:
5758: #
5759: # Rest of the restrictions depend on selected course
5760: #
5761:
1.620 albertel 5762: unless ($env{'request.course.id'}) {
1.766 albertel 5763: if ($thisallowed eq 'A') {
5764: return 'A';
1.814 raeburn 5765: } elsif ($thisallowed eq 'B') {
5766: return 'B';
1.766 albertel 5767: } else {
5768: return '1';
5769: }
1.52 www 5770: }
1.29 www 5771:
1.52 www 5772: #
5773: # Now user is definitely in a course
5774: #
1.53 www 5775:
5776:
5777: # Course preferences
5778:
5779: if ($thisallowed=~/C/) {
1.620 albertel 5780: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5781: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5782: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5783: =~/\Q$rolecode\E/) {
1.1056.4.22 raeburn 5784: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5785: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5786: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5787: $env{'request.course.id'});
5788: }
1.237 www 5789: return '';
5790: }
5791:
1.620 albertel 5792: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5793: =~/\Q$unamedom\E/) {
1.1056.4.22 raeburn 5794: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5795: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5796: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5797: $env{'request.course.id'});
5798: }
1.54 www 5799: return '';
5800: }
1.53 www 5801: }
5802:
5803: # Resource preferences
5804:
5805: if ($thisallowed=~/R/) {
1.620 albertel 5806: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5807: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1056.4.22 raeburn 5808: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5809: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5810: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5811: }
5812: return '';
1.54 www 5813: }
1.53 www 5814: }
1.30 www 5815:
1.246 www 5816: # Restricted by state or randomout?
1.30 www 5817:
1.52 www 5818: if ($thisallowed=~/X/) {
1.620 albertel 5819: if ($env{'acc.randomout'}) {
1.579 albertel 5820: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5821: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5822: return '';
5823: }
1.247 www 5824: }
5825: if (&condval($statecond)) {
1.52 www 5826: return '2';
5827: } else {
5828: return '';
5829: }
5830: }
1.30 www 5831:
1.766 albertel 5832: if ($thisallowed eq 'A') {
5833: return 'A';
1.814 raeburn 5834: } elsif ($thisallowed eq 'B') {
5835: return 'B';
1.766 albertel 5836: }
1.52 www 5837: return 'F';
1.232 www 5838: }
5839:
1.710 albertel 5840: sub split_uri_for_cond {
5841: my $uri=&deversion(&declutter(shift));
5842: my @uriparts=split(/\//,$uri);
5843: my $filename=pop(@uriparts);
5844: my $pathname=join('/',@uriparts);
5845: return ($pathname,$filename);
5846: }
1.232 www 5847: # --------------------------------------------------- Is a resource on the map?
5848:
5849: sub is_on_map {
1.710 albertel 5850: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5851: #Trying to find the conditional for the file
1.620 albertel 5852: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5853: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5854: if ($match) {
1.289 bowersj2 5855: return (1,$1);
5856: } else {
1.434 www 5857: return (0,0);
1.289 bowersj2 5858: }
1.12 www 5859: }
5860:
1.427 www 5861: # --------------------------------------------------------- Get symb from alias
5862:
5863: sub get_symb_from_alias {
5864: my $symb=shift;
5865: my ($map,$resid,$url)=&decode_symb($symb);
5866: # Already is a symb
5867: if ($url) { return $symb; }
5868: # Must be an alias
5869: my $aliassymb='';
5870: my %bighash;
1.620 albertel 5871: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5872: &GDBM_READER(),0640)) {
5873: my $rid=$bighash{'mapalias_'.$symb};
5874: if ($rid) {
5875: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5876: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5877: $resid,$bighash{'src_'.$rid});
1.427 www 5878: }
5879: untie %bighash;
5880: }
5881: return $aliassymb;
5882: }
5883:
1.12 www 5884: # ----------------------------------------------------------------- Define Role
5885:
5886: sub definerole {
5887: if (allowed('mcr','/')) {
5888: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5889: foreach my $role (split(':',$sysrole)) {
5890: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5891: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5892: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5893: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5894: return "refused:s:$crole&$cqual";
5895: }
5896: }
1.191 harris41 5897: }
1.800 albertel 5898: foreach my $role (split(':',$domrole)) {
5899: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5900: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5901: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5902: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5903: return "refused:d:$crole&$cqual";
5904: }
5905: }
1.191 harris41 5906: }
1.800 albertel 5907: foreach my $role (split(':',$courole)) {
5908: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5909: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5910: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5911: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5912: return "refused:c:$crole&$cqual";
5913: }
5914: }
1.191 harris41 5915: }
1.620 albertel 5916: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5917: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5918: "rolesdef_$rolename=".
5919: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5920: return reply($command,$env{'user.home'});
1.12 www 5921: } else {
5922: return 'refused';
5923: }
1.105 harris41 5924: }
5925:
5926: # ---------------- Make a metadata query against the network of library servers
5927:
5928: sub metadata_query {
1.244 matthew 5929: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5930: my %rhash;
1.845 albertel 5931: my %libserv = &all_library();
1.244 matthew 5932: my @server_list = (defined($server_array) ? @$server_array
5933: : keys(%libserv) );
5934: for my $server (@server_list) {
1.118 harris41 5935: unless ($custom or $customshow) {
5936: my $reply=&reply("querysend:".&escape($query),$server);
5937: $rhash{$server}=$reply;
5938: }
5939: else {
5940: my $reply=&reply("querysend:".&escape($query).':'.
5941: &escape($custom).':'.&escape($customshow),
5942: $server);
5943: $rhash{$server}=$reply;
5944: }
1.112 harris41 5945: }
1.118 harris41 5946: return \%rhash;
1.240 www 5947: }
5948:
5949: # ----------------------------------------- Send log queries and wait for reply
5950:
5951: sub log_query {
5952: my ($uname,$udom,$query,%filters)=@_;
5953: my $uhome=&homeserver($uname,$udom);
5954: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5955: my $uhost=&hostname($uhome);
1.800 albertel 5956: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5957: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5958: $uhome);
1.479 albertel 5959: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5960: return get_query_reply($queryid);
5961: }
5962:
1.818 raeburn 5963: # -------------------------- Update MySQL table for portfolio file
5964:
5965: sub update_portfolio_table {
1.821 raeburn 5966: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5967: if ($group ne '') {
5968: $file_name =~s /^\Q$group\E//;
5969: }
1.818 raeburn 5970: my $homeserver = &homeserver($uname,$udom);
5971: my $queryid=
1.821 raeburn 5972: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5973: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5974: my $reply = &get_query_reply($queryid);
5975: return $reply;
5976: }
5977:
1.899 raeburn 5978: # -------------------------- Update MySQL allusers table
5979:
5980: sub update_allusers_table {
5981: my ($uname,$udom,$names) = @_;
5982: my $homeserver = &homeserver($uname,$udom);
5983: my $queryid=
5984: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5985: 'lastname='.&escape($names->{'lastname'}).'%%'.
5986: 'firstname='.&escape($names->{'firstname'}).'%%'.
5987: 'middlename='.&escape($names->{'middlename'}).'%%'.
5988: 'generation='.&escape($names->{'generation'}).'%%'.
5989: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5990: 'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4 raeburn 5991: return;
1.899 raeburn 5992: }
5993:
1.508 raeburn 5994: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5995:
5996: sub fetch_enrollment_query {
1.511 raeburn 5997: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5998: my $homeserver;
1.547 raeburn 5999: my $maxtries = 1;
1.508 raeburn 6000: if ($context eq 'automated') {
6001: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6002: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6003: } else {
6004: $homeserver = &homeserver($cnum,$dom);
6005: }
1.838 albertel 6006: my $host=&hostname($homeserver);
1.506 raeburn 6007: my $cmd = '';
1.1000 raeburn 6008: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6009: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6010: }
6011: $cmd =~ s/%%$//;
6012: $cmd = &escape($cmd);
6013: my $query = 'fetchenrollment';
1.620 albertel 6014: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6015: unless ($queryid=~/^\Q$host\E\_/) {
6016: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6017: return 'error: '.$queryid;
6018: }
1.506 raeburn 6019: my $reply = &get_query_reply($queryid);
1.547 raeburn 6020: my $tries = 1;
6021: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6022: $reply = &get_query_reply($queryid);
6023: $tries ++;
6024: }
1.526 raeburn 6025: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6026: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6027: } else {
1.901 albertel 6028: my @responses = split(/:/,$reply);
1.515 raeburn 6029: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6030: foreach my $line (@responses) {
6031: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6032: $$replyref{$key} = $value;
6033: }
6034: } else {
1.506 raeburn 6035: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 6036: foreach my $line (@responses) {
6037: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6038: $$replyref{$key} = $value;
6039: if ($value > 0) {
1.800 albertel 6040: foreach my $item (@{$$affiliatesref{$key}}) {
6041: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6042: my $destname = $pathname.'/'.$filename;
6043: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6044: if ($xml_classlist =~ /^error/) {
6045: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6046: } else {
1.506 raeburn 6047: if ( open(FILE,">$destname") ) {
6048: print FILE &unescape($xml_classlist);
6049: close(FILE);
1.526 raeburn 6050: } else {
6051: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6052: }
6053: }
6054: }
6055: }
6056: }
6057: }
6058: return 'ok';
6059: }
6060: return 'error';
6061: }
6062:
1.242 www 6063: sub get_query_reply {
6064: my $queryid=shift;
1.240 www 6065: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
6066: my $reply='';
6067: for (1..100) {
6068: sleep 2;
6069: if (-e $replyfile.'.end') {
1.448 albertel 6070: if (open(my $fh,$replyfile)) {
1.904 albertel 6071: $reply = join('',<$fh>);
6072: close($fh);
1.240 www 6073: } else { return 'error: reply_file_error'; }
1.242 www 6074: return &unescape($reply);
6075: }
1.240 www 6076: }
1.242 www 6077: return 'timeout:'.$queryid;
1.240 www 6078: }
6079:
6080: sub courselog_query {
1.241 www 6081: #
6082: # possible filters:
6083: # url: url or symb
6084: # username
6085: # domain
6086: # action: view, submit, grade
6087: # start: timestamp
6088: # end: timestamp
6089: #
1.240 www 6090: my (%filters)=@_;
1.620 albertel 6091: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6092: if ($filters{'url'}) {
6093: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6094: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6095: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6096: }
1.620 albertel 6097: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6098: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6099: return &log_query($cname,$cdom,'courselog',%filters);
6100: }
6101:
6102: sub userlog_query {
1.858 raeburn 6103: #
6104: # possible filters:
6105: # action: log check role
6106: # start: timestamp
6107: # end: timestamp
6108: #
1.240 www 6109: my ($uname,$udom,%filters)=@_;
6110: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6111: }
6112:
1.506 raeburn 6113: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6114:
6115: sub auto_run {
1.508 raeburn 6116: my ($cnum,$cdom) = @_;
1.876 raeburn 6117: my $response = 0;
6118: my $settings;
6119: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6120: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6121: $settings = $domconfig{'autoenroll'};
6122: if ($settings->{'run'} eq '1') {
6123: $response = 1;
6124: }
6125: } else {
1.934 raeburn 6126: my $homeserver;
6127: if (&is_course($cdom,$cnum)) {
6128: $homeserver = &homeserver($cnum,$cdom);
6129: } else {
6130: $homeserver = &domain($cdom,'primary');
6131: }
6132: if ($homeserver ne 'no_host') {
6133: $response = &reply('autorun:'.$cdom,$homeserver);
6134: }
1.876 raeburn 6135: }
1.506 raeburn 6136: return $response;
6137: }
1.776 albertel 6138:
1.506 raeburn 6139: sub auto_get_sections {
1.508 raeburn 6140: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6141: my $homeserver;
6142: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6143: $homeserver = &homeserver($cnum,$cdom);
6144: }
6145: if (!defined($homeserver)) {
6146: if ($cdom =~ /^$match_domain$/) {
6147: $homeserver = &domain($cdom,'primary');
6148: }
6149: }
6150: my @secs;
6151: if (defined($homeserver)) {
6152: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6153: unless ($response eq 'refused') {
6154: @secs = split(/:/,$response);
6155: }
1.506 raeburn 6156: }
6157: return @secs;
6158: }
1.776 albertel 6159:
1.506 raeburn 6160: sub auto_new_course {
1.1056.4.19 raeburn 6161: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6162: my $homeserver = &homeserver($cnum,$cdom);
1.1056.4.19 raeburn 6163: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6164: return $response;
6165: }
1.776 albertel 6166:
1.506 raeburn 6167: sub auto_validate_courseID {
1.508 raeburn 6168: my ($cnum,$cdom,$inst_course_id) = @_;
6169: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6170: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6171: return $response;
6172: }
1.776 albertel 6173:
1.1007 raeburn 6174: sub auto_validate_instcode {
1.1020 raeburn 6175: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6176: my ($homeserver,$response);
6177: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6178: $homeserver = &homeserver($cnum,$cdom);
6179: }
6180: if (!defined($homeserver)) {
6181: if ($cdom =~ /^$match_domain$/) {
6182: $homeserver = &domain($cdom,'primary');
6183: }
6184: }
1.1056.4.2 raeburn 6185: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6186: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6187: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6188: return ($outcome,$description);
1.1007 raeburn 6189: }
6190:
1.506 raeburn 6191: sub auto_create_password {
1.873 raeburn 6192: my ($cnum,$cdom,$authparam,$udom) = @_;
6193: my ($homeserver,$response);
1.506 raeburn 6194: my $create_passwd = 0;
6195: my $authchk = '';
1.873 raeburn 6196: if ($udom =~ /^$match_domain$/) {
6197: $homeserver = &domain($udom,'primary');
6198: }
6199: if ($homeserver eq '') {
6200: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6201: $homeserver = &homeserver($cnum,$cdom);
6202: }
6203: }
6204: if ($homeserver eq '') {
6205: $authchk = 'nodomain';
1.506 raeburn 6206: } else {
1.873 raeburn 6207: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6208: if ($response eq 'refused') {
6209: $authchk = 'refused';
6210: } else {
1.901 albertel 6211: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6212: }
1.506 raeburn 6213: }
6214: return ($authparam,$create_passwd,$authchk);
6215: }
6216:
1.706 raeburn 6217: sub auto_photo_permission {
6218: my ($cnum,$cdom,$students) = @_;
6219: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6220: my ($outcome,$perm_reqd,$conditions) =
6221: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6222: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6223: return (undef,undef);
6224: }
1.706 raeburn 6225: return ($outcome,$perm_reqd,$conditions);
6226: }
6227:
6228: sub auto_checkphotos {
6229: my ($uname,$udom,$pid) = @_;
6230: my $homeserver = &homeserver($uname,$udom);
6231: my ($result,$resulttype);
6232: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6233: &escape($uname).':'.&escape($pid),
6234: $homeserver));
1.709 albertel 6235: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6236: return (undef,undef);
6237: }
1.706 raeburn 6238: if ($outcome) {
6239: ($result,$resulttype) = split(/:/,$outcome);
6240: }
6241: return ($result,$resulttype);
6242: }
6243:
6244: sub auto_photochoice {
6245: my ($cnum,$cdom) = @_;
6246: my $homeserver = &homeserver($cnum,$cdom);
6247: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6248: &escape($cdom),
6249: $homeserver)));
1.709 albertel 6250: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6251: return (undef,undef);
6252: }
1.706 raeburn 6253: return ($update,$comment);
6254: }
6255:
6256: sub auto_photoupdate {
6257: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6258: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6259: my $host=&hostname($homeserver);
1.706 raeburn 6260: my $cmd = '';
6261: my $maxtries = 1;
1.800 albertel 6262: foreach my $affiliate (keys(%{$affiliatesref})) {
6263: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6264: }
6265: $cmd =~ s/%%$//;
6266: $cmd = &escape($cmd);
6267: my $query = 'institutionalphotos';
6268: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6269: unless ($queryid=~/^\Q$host\E\_/) {
6270: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6271: return 'error: '.$queryid;
6272: }
6273: my $reply = &get_query_reply($queryid);
6274: my $tries = 1;
6275: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6276: $reply = &get_query_reply($queryid);
6277: $tries ++;
6278: }
6279: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6280: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6281: } else {
6282: my @responses = split(/:/,$reply);
6283: my $outcome = shift(@responses);
6284: foreach my $item (@responses) {
6285: my ($key,$value) = split(/=/,$item);
6286: $$photo{$key} = $value;
6287: }
6288: return $outcome;
6289: }
6290: return 'error';
6291: }
6292:
1.521 raeburn 6293: sub auto_instcode_format {
1.793 albertel 6294: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6295: $cat_order) = @_;
1.521 raeburn 6296: my $courses = '';
1.772 raeburn 6297: my @homeservers;
1.521 raeburn 6298: if ($caller eq 'global') {
1.841 albertel 6299: my %servers = &get_servers($codedom,'library');
6300: foreach my $tryserver (keys(%servers)) {
6301: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6302: push(@homeservers,$tryserver);
6303: }
1.584 raeburn 6304: }
1.1022 raeburn 6305: } elsif ($caller eq 'requests') {
6306: if ($codedom =~ /^$match_domain$/) {
6307: my $chome = &domain($codedom,'primary');
6308: unless ($chome eq 'no_host') {
6309: push(@homeservers,$chome);
6310: }
6311: }
1.521 raeburn 6312: } else {
1.772 raeburn 6313: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6314: }
1.793 albertel 6315: foreach my $code (keys(%{$instcodes})) {
6316: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6317: }
6318: chop($courses);
1.772 raeburn 6319: my $ok_response = 0;
6320: my $response;
6321: while (@homeservers > 0 && $ok_response == 0) {
6322: my $server = shift(@homeservers);
6323: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6324: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6325: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6326: split(/:/,$response);
1.772 raeburn 6327: %{$codes} = (%{$codes},&str2hash($codes_str));
6328: push(@{$codetitles},&str2array($codetitles_str));
6329: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6330: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6331: $ok_response = 1;
6332: }
6333: }
6334: if ($ok_response) {
1.521 raeburn 6335: return 'ok';
1.772 raeburn 6336: } else {
6337: return $response;
1.521 raeburn 6338: }
6339: }
6340:
1.792 raeburn 6341: sub auto_instcode_defaults {
6342: my ($domain,$returnhash,$code_order) = @_;
6343: my @homeservers;
1.841 albertel 6344:
6345: my %servers = &get_servers($domain,'library');
6346: foreach my $tryserver (keys(%servers)) {
6347: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6348: push(@homeservers,$tryserver);
6349: }
1.792 raeburn 6350: }
1.841 albertel 6351:
1.792 raeburn 6352: my $response;
1.841 albertel 6353: foreach my $server (@homeservers) {
1.792 raeburn 6354: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6355: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6356:
6357: foreach my $pair (split(/\&/,$response)) {
6358: my ($name,$value)=split(/\=/,$pair);
6359: if ($name eq 'code_order') {
6360: @{$code_order} = split(/\&/,&unescape($value));
6361: } else {
6362: $returnhash->{&unescape($name)}=&unescape($value);
6363: }
6364: }
6365: return 'ok';
1.792 raeburn 6366: }
1.841 albertel 6367:
6368: return $response;
1.1003 raeburn 6369: }
6370:
6371: sub auto_possible_instcodes {
1.1007 raeburn 6372: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6373: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6374: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6375: return;
6376: }
1.1003 raeburn 6377: my (@homeservers,$uhome);
6378: if (defined(&domain($domain,'primary'))) {
6379: $uhome=&domain($domain,'primary');
6380: push(@homeservers,&domain($domain,'primary'));
6381: } else {
6382: my %servers = &get_servers($domain,'library');
6383: foreach my $tryserver (keys(%servers)) {
6384: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6385: push(@homeservers,$tryserver);
6386: }
6387: }
6388: }
6389: my $response;
6390: foreach my $server (@homeservers) {
6391: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6392: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6393: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6394: split(':',$response);
6395: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6396: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6397: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6398: my ($name,$value)=split('=',$item);
6399: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6400: }
6401: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6402: my ($name,$value)=split('=',$item);
6403: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6404: }
6405: return 'ok';
6406: }
6407: return $response;
6408: }
1.792 raeburn 6409:
1.1010 raeburn 6410: sub auto_courserequest_checks {
6411: my ($dom) = @_;
1.1020 raeburn 6412: my ($homeserver,%validations);
6413: if ($dom =~ /^$match_domain$/) {
6414: $homeserver = &domain($dom,'primary');
6415: }
6416: unless ($homeserver eq 'no_host') {
6417: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6418: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6419: my @items = split(/&/,$response);
6420: foreach my $item (@items) {
6421: my ($key,$value) = split('=',$item);
6422: $validations{&unescape($key)} = &thaw_unescape($value);
6423: }
6424: }
6425: }
1.1010 raeburn 6426: return %validations;
6427: }
6428:
1.1020 raeburn 6429: sub auto_courserequest_validation {
6430: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6431: my ($homeserver,$response);
6432: if ($dom =~ /^$match_domain$/) {
6433: $homeserver = &domain($dom,'primary');
6434: }
6435: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6436:
1.1020 raeburn 6437: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6438: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6439: ':'.&escape($instcode).':'.&escape($instseclist),
6440: $homeserver));
6441: }
6442: return $response;
6443: }
6444:
1.777 albertel 6445: sub auto_validate_class_sec {
1.918 raeburn 6446: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6447: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6448: my $ownerlist;
6449: if (ref($owners) eq 'ARRAY') {
6450: $ownerlist = join(',',@{$owners});
6451: } else {
6452: $ownerlist = $owners;
6453: }
1.773 raeburn 6454: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6455: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6456: return $response;
6457: }
6458:
1.679 raeburn 6459: # ------------------------------------------------------- Course Group routines
6460:
6461: sub get_coursegroups {
1.809 raeburn 6462: my ($cdom,$cnum,$group,$namespace) = @_;
6463: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6464: }
6465:
1.679 raeburn 6466: sub modify_coursegroup {
6467: my ($cdom,$cnum,$groupsettings) = @_;
6468: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6469: }
6470:
1.809 raeburn 6471: sub toggle_coursegroup_status {
6472: my ($cdom,$cnum,$group,$action) = @_;
6473: my ($from_namespace,$to_namespace);
6474: if ($action eq 'delete') {
6475: $from_namespace = 'coursegroups';
6476: $to_namespace = 'deleted_groups';
6477: } else {
6478: $from_namespace = 'deleted_groups';
6479: $to_namespace = 'coursegroups';
6480: }
6481: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6482: if (my $tmp = &error(%curr_group)) {
6483: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6484: return ('read error',$tmp);
6485: } else {
6486: my %savedsettings = %curr_group;
1.809 raeburn 6487: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6488: my $deloutcome;
6489: if ($result eq 'ok') {
1.809 raeburn 6490: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6491: } else {
6492: return ('write error',$result);
6493: }
6494: if ($deloutcome eq 'ok') {
6495: return 'ok';
6496: } else {
6497: return ('delete error',$deloutcome);
6498: }
6499: }
6500: }
6501:
1.679 raeburn 6502: sub modify_group_roles {
1.957 raeburn 6503: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6504: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6505: my $role = 'gr/'.&escape($userprivs);
6506: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6507: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6508: if ($result eq 'ok') {
6509: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6510: }
1.679 raeburn 6511: return $result;
6512: }
6513:
6514: sub modify_coursegroup_membership {
6515: my ($cdom,$cnum,$membership) = @_;
6516: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6517: return $result;
6518: }
6519:
1.682 raeburn 6520: sub get_active_groups {
6521: my ($udom,$uname,$cdom,$cnum) = @_;
6522: my $now = time;
6523: my %groups = ();
6524: foreach my $key (keys(%env)) {
1.811 albertel 6525: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6526: my ($start,$end) = split(/\./,$env{$key});
6527: if (($end!=0) && ($end<$now)) { next; }
6528: if (($start!=0) && ($start>$now)) { next; }
6529: if ($1 eq $cdom && $2 eq $cnum) {
6530: $groups{$3} = $env{$key} ;
6531: }
6532: }
6533: }
6534: return %groups;
6535: }
6536:
1.683 raeburn 6537: sub get_group_membership {
6538: my ($cdom,$cnum,$group) = @_;
6539: return(&dump('groupmembership',$cdom,$cnum,$group));
6540: }
6541:
6542: sub get_users_groups {
6543: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6544: my @usersgroups;
1.683 raeburn 6545: my $cachetime=1800;
6546:
6547: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6548: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6549: if (defined($cached)) {
1.734 albertel 6550: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6551: } else {
6552: $grouplist = '';
1.816 raeburn 6553: my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 6554: my $extra = &freeze_escape({'skipcheck' => 1});
6555: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6556: my $access_end = $env{'course.'.$courseid.
6557: '.default_enrollment_end_date'};
6558: my $now = time;
6559: foreach my $key (keys(%roleshash)) {
6560: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6561: my $group = $1;
6562: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6563: my $start = $2;
6564: my $end = $1;
6565: if ($start == -1) { next; } # deleted from group
6566: if (($start!=0) && ($start>$now)) { next; }
6567: if (($end!=0) && ($end<$now)) {
6568: if ($access_end && $access_end < $now) {
6569: if ($access_end - $end < 86400) {
6570: push(@usersgroups,$group);
1.733 raeburn 6571: }
6572: }
1.817 raeburn 6573: next;
1.733 raeburn 6574: }
1.817 raeburn 6575: push(@usersgroups,$group);
1.683 raeburn 6576: }
6577: }
6578: }
1.817 raeburn 6579: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6580: $grouplist = join(':',@usersgroups);
6581: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6582: }
1.733 raeburn 6583: return @usersgroups;
1.683 raeburn 6584: }
6585:
6586: sub devalidate_getgroups_cache {
6587: my ($udom,$uname,$cdom,$cnum)=@_;
6588: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6589:
1.683 raeburn 6590: my $hashid="$udom:$uname:$courseid";
6591: &devalidate_cache_new('getgroups',$hashid);
6592: }
6593:
1.12 www 6594: # ------------------------------------------------------------------ Plain Text
6595:
6596: sub plaintext {
1.988 raeburn 6597: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6598: if ($short =~ m{^cr/}) {
1.758 albertel 6599: return (split('/',$short))[-1];
6600: }
1.742 raeburn 6601: if (!defined($cid)) {
6602: $cid = $env{'request.course.id'};
6603: }
6604: my %rolenames = (
1.1008 raeburn 6605: Course => 'std',
6606: Community => 'alt1',
1.742 raeburn 6607: );
1.1037 raeburn 6608: if ($cid ne '') {
6609: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6610: unless ($forcedefault) {
6611: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6612: &Apache::lonlocal::mt_escape(\$roletext);
6613: return &Apache::lonlocal::mt($roletext);
6614: }
6615: }
6616: }
6617: if ((defined($type)) && (defined($rolenames{$type})) &&
6618: (defined($rolenames{$type})) &&
6619: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6620: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6621: } elsif ($cid ne '') {
6622: my $crstype = $env{'course.'.$cid.'.type'};
6623: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6624: (defined($prp{$short}{$rolenames{$crstype}}))) {
6625: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6626: }
1.742 raeburn 6627: }
1.1037 raeburn 6628: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6629: }
6630:
6631: # ----------------------------------------------------------------- Assign Role
6632:
6633: sub assignrole {
1.957 raeburn 6634: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6635: $context)=@_;
1.21 www 6636: my $mrole;
6637: if ($role =~ /^cr\//) {
1.393 www 6638: my $cwosec=$url;
1.811 albertel 6639: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6640: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6641: my $refused = 1;
6642: if ($context eq 'requestcourses') {
6643: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6644: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6645: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6646: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6647: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6648: if ($crsenv{'internal.courseowner'} eq
6649: $env{'user.name'}.':'.$env{'user.domain'}) {
6650: $refused = '';
6651: }
6652: }
6653: }
6654: }
6655: }
6656: if ($refused) {
6657: &logthis('Refused custom assignrole: '.
6658: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6659: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6660: return 'refused';
6661: }
1.104 www 6662: }
1.21 www 6663: $mrole='cr';
1.678 raeburn 6664: } elsif ($role =~ /^gr\//) {
6665: my $cwogrp=$url;
1.811 albertel 6666: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6667: unless (&allowed('mdg',$cwogrp)) {
6668: &logthis('Refused group assignrole: '.
6669: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6670: $env{'user.name'}.' at '.$env{'user.domain'});
6671: return 'refused';
6672: }
6673: $mrole='gr';
1.21 www 6674: } else {
1.82 www 6675: my $cwosec=$url;
1.811 albertel 6676: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6677: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6678: my $refused;
6679: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6680: if (!(&allowed('c'.$role,$url))) {
6681: $refused = 1;
6682: }
6683: } else {
6684: $refused = 1;
6685: }
1.947 raeburn 6686: if ($refused) {
1.1045 raeburn 6687: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6688: if (!$selfenroll && $context eq 'course') {
6689: my %crsenv;
6690: if ($role eq 'cc' || $role eq 'co') {
6691: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6692: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6693: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6694: if ($crsenv{'internal.courseowner'} eq
6695: $env{'user.name'}.':'.$env{'user.domain'}) {
6696: $refused = '';
6697: }
6698: }
6699: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6700: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6701: if ($crsenv{'internal.courseowner'} eq
6702: $env{'user.name'}.':'.$env{'user.domain'}) {
6703: $refused = '';
6704: }
6705: }
6706: }
6707: }
6708: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6709: $refused = '';
1.1017 raeburn 6710: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6711: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6712: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6713: my $wrongcc;
6714: if ($cnum =~ /^$match_community$/) {
6715: $wrongcc = 1 if ($role eq 'cc');
6716: } else {
6717: $wrongcc = 1 if ($role eq 'co');
6718: }
6719: unless ($wrongcc) {
6720: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6721: if ($crsenv{'internal.courseowner'} eq
6722: $env{'user.name'}.':'.$env{'user.domain'}) {
6723: $refused = '';
6724: }
1.1017 raeburn 6725: }
6726: }
6727: }
6728: if ($refused) {
1.947 raeburn 6729: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6730: ' '.$role.' '.$end.' '.$start.' by '.
6731: $env{'user.name'}.' at '.$env{'user.domain'});
6732: return 'refused';
6733: }
1.932 raeburn 6734: }
1.1056.4.30! raeburn 6735: } elsif ($role eq 'au') {
! 6736: if ($url ne '/'.$udom.'/') {
! 6737: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
! 6738: ' to assign author role for '.$uname.':'.$udom.
! 6739: ' in domain: '.$url.' refused (wrong domain).');
! 6740: return 'refused';
! 6741: }
1.104 www 6742: }
1.21 www 6743: $mrole=$role;
6744: }
1.620 albertel 6745: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6746: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6747: if ($end) { $command.='_'.$end; }
1.21 www 6748: if ($start) {
6749: if ($end) {
1.81 www 6750: $command.='_'.$start;
1.21 www 6751: } else {
1.81 www 6752: $command.='_0_'.$start;
1.21 www 6753: }
6754: }
1.739 raeburn 6755: my $origstart = $start;
6756: my $origend = $end;
1.957 raeburn 6757: my $delflag;
1.357 www 6758: # actually delete
6759: if ($deleteflag) {
1.373 www 6760: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6761: # modify command to delete the role
1.620 albertel 6762: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6763: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6764: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6765: # set start and finish to negative values for userrolelog
6766: $start=-1;
6767: $end=-1;
1.957 raeburn 6768: $delflag = 1;
1.357 www 6769: }
6770: }
6771: # send command
1.349 www 6772: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6773: # log new user role if status is ok
1.349 www 6774: if ($answer eq 'ok') {
1.663 raeburn 6775: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6776: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6777: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6778: unless ($role =~ /^gr/) {
6779: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6780: $origstart,$selfenroll,$context);
1.739 raeburn 6781: }
1.1053 raeburn 6782: if ($role eq 'cc') {
6783: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6784: }
1.349 www 6785: }
6786: return $answer;
1.169 harris41 6787: }
6788:
1.1053 raeburn 6789: sub autoupdate_coowners {
6790: my ($url,$end,$start,$uname,$udom) = @_;
6791: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6792: if (($cdom ne '') && ($cnum ne '')) {
6793: my $now = time;
6794: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6795: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6796: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6797: my $instcode = $coursehash{'internal.coursecode'};
6798: if ($instcode ne '') {
1.1056 raeburn 6799: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6800: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6801: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6802: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6803: if ($result eq 'valid') {
6804: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6805: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6806: push(@newcoowners,$coowner);
6807: }
6808: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6809: push(@newcoowners,$uname.':'.$udom);
6810: }
6811: @newcoowners = sort(@newcoowners);
6812: } else {
6813: push(@newcoowners,$uname.':'.$udom);
6814: }
6815: } else {
6816: if ($coursehash{'internal.co-owners'}) {
6817: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6818: unless ($coowner eq $uname.':'.$udom) {
6819: push(@newcoowners,$coowner);
6820: }
6821: }
6822: unless (@newcoowners > 0) {
6823: $delcoowners = 1;
6824: $coowners = '';
6825: }
6826: }
6827: }
6828: if (@newcoowners || $delcoowners) {
6829: &store_coowners($cdom,$cnum,$coursehash{'home'},
6830: $delcoowners,@newcoowners);
6831: }
6832: }
6833: }
6834: }
6835: }
6836: }
6837: }
6838:
6839: sub store_coowners {
6840: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6841: my $cid = $cdom.'_'.$cnum;
6842: my ($coowners,$delresult,$putresult);
6843: if (@newcoowners) {
6844: $coowners = join(',',@newcoowners);
6845: my %coownershash = (
6846: 'internal.co-owners' => $coowners,
6847: );
6848: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6849: if ($putresult eq 'ok') {
6850: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6851: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6852: }
6853: }
6854: }
6855: if ($delcoowners) {
6856: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6857: if ($delresult eq 'ok') {
6858: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6859: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6860: }
6861: }
6862: }
6863: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6864: my %crsinfo =
6865: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6866: if (ref($crsinfo{$cid}) eq 'HASH') {
6867: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6868: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6869: }
6870: }
6871: }
6872:
1.169 harris41 6873: # -------------------------------------------------- Modify user authentication
1.197 www 6874: # Overrides without validation
6875:
1.169 harris41 6876: sub modifyuserauth {
6877: my ($udom,$uname,$umode,$upass)=@_;
6878: my $uhome=&homeserver($uname,$udom);
1.197 www 6879: unless (&allowed('mau',$udom)) { return 'refused'; }
6880: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6881: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6882: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6883: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6884: &escape($upass),$uhome);
1.620 albertel 6885: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6886: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6887: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6888: &log($udom,,$uname,$uhome,
1.620 albertel 6889: 'Authentication changed by '.$env{'user.domain'}.', '.
6890: $env{'user.name'}.', '.$umode.
1.197 www 6891: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6892: unless ($reply eq 'ok') {
1.197 www 6893: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6894: return 'error: '.$reply;
6895: }
1.170 harris41 6896: return 'ok';
1.80 www 6897: }
6898:
1.81 www 6899: # --------------------------------------------------------------- Modify a user
1.80 www 6900:
1.81 www 6901: sub modifyuser {
1.206 matthew 6902: my ($udom, $uname, $uid,
6903: $umode, $upass, $first,
6904: $middle, $last, $gene,
1.1056.4.1 raeburn 6905: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6906: $udom= &LONCAPA::clean_domain($udom);
6907: $uname=&LONCAPA::clean_username($uname);
1.1056.4.1 raeburn 6908: my $showcandelete = 'none';
6909: if (ref($candelete) eq 'ARRAY') {
6910: if (@{$candelete} > 0) {
6911: $showcandelete = join(', ',@{$candelete});
6912: }
6913: }
1.81 www 6914: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6915: $umode.', '.$first.', '.$middle.', '.
1.1056.4.1 raeburn 6916: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6917: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6918: ' desiredhome not specified').
1.620 albertel 6919: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6920: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6921: my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4 raeburn 6922: my $newuser;
6923: if ($uhome eq 'no_host') {
6924: $newuser = 1;
6925: }
1.80 www 6926: # ----------------------------------------------------------------- Create User
1.406 albertel 6927: if (($uhome eq 'no_host') &&
6928: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6929: my $unhome='';
1.844 albertel 6930: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6931: $unhome = $desiredhome;
1.620 albertel 6932: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6933: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6934: } else { # load balancing routine for determining $unhome
1.81 www 6935: my $loadm=10000000;
1.841 albertel 6936: my %servers = &get_servers($udom,'library');
6937: foreach my $tryserver (keys(%servers)) {
6938: my $answer=reply('load',$tryserver);
6939: if (($answer=~/\d+/) && ($answer<$loadm)) {
6940: $loadm=$answer;
6941: $unhome=$tryserver;
6942: }
1.80 www 6943: }
6944: }
6945: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6946: return 'error: unable to find a home server for '.$uname.
6947: ' in domain '.$udom;
1.80 www 6948: }
6949: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6950: &escape($upass),$unhome);
6951: unless ($reply eq 'ok') {
6952: return 'error: '.$reply;
6953: }
1.230 stredwic 6954: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6955: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6956: return 'error: unable verify users home machine.';
1.80 www 6957: }
1.209 matthew 6958: } # End of creation of new user
1.80 www 6959: # ---------------------------------------------------------------------- Add ID
6960: if ($uid) {
6961: $uid=~tr/A-Z/a-z/;
6962: my %uidhash=&idrget($udom,$uname);
1.196 www 6963: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6964: && (!$forceid)) {
1.80 www 6965: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6966: return 'error: user id "'.$uid.'" does not match '.
6967: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6968: }
6969: } else {
6970: &idput($udom,($uname => $uid));
6971: }
6972: }
6973: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6974: my @tmp=&get('environment',
1.899 raeburn 6975: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6976: 'permanentemail','inststatus'],
1.134 albertel 6977: $udom,$uname);
1.1056.4.4 raeburn 6978: my (%names,%oldnames);
1.313 matthew 6979: if ($tmp[0] =~ m/^error:.*/) {
6980: %names=();
6981: } else {
6982: %names = @tmp;
1.1056.4.4 raeburn 6983: %oldnames = %names;
1.313 matthew 6984: }
1.1056.4.6 raeburn 6985: #
1.1056.4.1 raeburn 6986: # If name, email and/or uid are blank (e.g., because an uploaded file
6987: # of users did not contain them), do not overwrite existing values
6988: # unless field is in $candelete array ref.
6989: #
6990:
6991: my @fields = ('firstname','middlename','lastname','generation',
6992: 'permanentemail','id');
6993: my %newvalues;
6994: if (ref($candelete) eq 'ARRAY') {
6995: foreach my $field (@fields) {
6996: if (grep(/^\Q$field\E$/,@{$candelete})) {
6997: if ($field eq 'firstname') {
6998: $names{$field} = $first;
6999: } elsif ($field eq 'middlename') {
7000: $names{$field} = $middle;
7001: } elsif ($field eq 'lastname') {
7002: $names{$field} = $last;
7003: } elsif ($field eq 'generation') {
7004: $names{$field} = $gene;
7005: } elsif ($field eq 'permanentemail') {
7006: $names{$field} = $email;
7007: } elsif ($field eq 'id') {
7008: $names{$field} = $uid;
7009: }
7010: }
7011: }
7012: }
1.388 www 7013: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7014: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7015: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7016: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7017: if ($email) {
7018: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7019: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7020: }
1.899 raeburn 7021: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7022: if (defined($inststatus)) {
7023: $names{'inststatus'} = '';
7024: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7025: if (ref($usertypes) eq 'HASH') {
7026: my @okstatuses;
7027: foreach my $item (split(/:/,$inststatus)) {
7028: if (defined($usertypes->{$item})) {
7029: push(@okstatuses,$item);
7030: }
7031: }
7032: if (@okstatuses) {
7033: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7034: }
7035: }
7036: }
1.1056.4.4 raeburn 7037: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7038: $umode.', '.$first.', '.$middle.', '.
1.1056.4.4 raeburn 7039: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7040: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7041: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7042: } else {
7043: $logmsg .= ' during self creation';
7044: }
1.1056.4.4 raeburn 7045: my $changed;
7046: if ($newuser) {
7047: $changed = 1;
7048: } else {
7049: foreach my $field (@fields) {
7050: if ($names{$field} ne $oldnames{$field}) {
7051: $changed = 1;
7052: last;
7053: }
7054: }
7055: }
7056: unless ($changed) {
7057: $logmsg = 'No changes in user information needed for: '.$logmsg;
7058: &logthis($logmsg);
7059: return 'ok';
7060: }
7061: my $reply = &put('environment', \%names, $udom,$uname);
7062: if ($reply ne 'ok') {
7063: return 'error: '.$reply;
7064: }
1.1056.4.11 raeburn 7065: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7066: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7067: }
1.1056.4.4 raeburn 7068: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7069: &devalidate_cache_new('namescache',$uname.':'.$udom);
7070: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7071: &logthis($logmsg);
1.134 albertel 7072: return 'ok';
1.80 www 7073: }
7074:
1.81 www 7075: # -------------------------------------------------------------- Modify student
1.80 www 7076:
1.81 www 7077: sub modifystudent {
7078: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7079: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7080: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7081: if (!$cid) {
1.620 albertel 7082: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7083: return 'not_in_class';
7084: }
1.80 www 7085: }
7086: # --------------------------------------------------------------- Make the user
1.81 www 7087: my $reply=&modifyuser
1.209 matthew 7088: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7089: $desiredhome,$email,$inststatus);
1.80 www 7090: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7091: # This will cause &modify_student_enrollment to get the uid from the
7092: # students environment
7093: $uid = undef if (!$forceid);
1.455 albertel 7094: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7095: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7096: return $reply;
7097: }
7098:
7099: sub modify_student_enrollment {
1.957 raeburn 7100: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7101: my ($cdom,$cnum,$chome);
7102: if (!$cid) {
1.620 albertel 7103: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7104: return 'not_in_class';
7105: }
1.620 albertel 7106: $cdom=$env{'course.'.$cid.'.domain'};
7107: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7108: } else {
7109: ($cdom,$cnum)=split(/_/,$cid);
7110: }
1.620 albertel 7111: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7112: if (!$chome) {
1.457 raeburn 7113: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7114: }
1.455 albertel 7115: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7116: # Make sure the user exists
1.81 www 7117: my $uhome=&homeserver($uname,$udom);
7118: if (($uhome eq '') || ($uhome eq 'no_host')) {
7119: return 'error: no such user';
7120: }
1.297 matthew 7121: # Get student data if we were not given enough information
7122: if (!defined($first) || $first eq '' ||
7123: !defined($last) || $last eq '' ||
7124: !defined($uid) || $uid eq '' ||
7125: !defined($middle) || $middle eq '' ||
7126: !defined($gene) || $gene eq '') {
1.294 matthew 7127: # They did not supply us with enough data to enroll the student, so
7128: # we need to pick up more information.
1.297 matthew 7129: my %tmp = &get('environment',
1.294 matthew 7130: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7131: ,$udom,$uname);
7132:
1.800 albertel 7133: #foreach my $key (keys(%tmp)) {
7134: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7135: #}
1.294 matthew 7136: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7137: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7138: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7139: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7140: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7141: }
1.556 albertel 7142: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7143: my $reply=cput('classlist',
7144: {"$uname:$udom" =>
1.515 raeburn 7145: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7146: $cdom,$cnum);
1.81 www 7147: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7148: return 'error: '.$reply;
1.652 albertel 7149: } else {
7150: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7151: }
1.297 matthew 7152: # Add student role to user
1.83 www 7153: my $uurl='/'.$cid;
1.81 www 7154: $uurl=~s/\_/\//g;
7155: if ($usec) {
7156: $uurl.='/'.$usec;
7157: }
1.957 raeburn 7158: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7159: }
7160:
1.556 albertel 7161: sub format_name {
7162: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7163: my $name;
7164: if ($first ne 'lastname') {
7165: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7166: } else {
7167: if ($lastname=~/\S/) {
7168: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7169: $name=~s/\s+,/,/;
7170: } else {
7171: $name.= $firstname.' '.$middlename.' '.$generation;
7172: }
7173: }
7174: $name=~s/^\s+//;
7175: $name=~s/\s+$//;
7176: $name=~s/\s+/ /g;
7177: return $name;
7178: }
7179:
1.84 www 7180: # ------------------------------------------------- Write to course preferences
7181:
7182: sub writecoursepref {
7183: my ($courseid,%prefs)=@_;
7184: $courseid=~s/^\///;
7185: $courseid=~s/\_/\//g;
7186: my ($cdomain,$cnum)=split(/\//,$courseid);
7187: my $chome=homeserver($cnum,$cdomain);
7188: if (($chome eq '') || ($chome eq 'no_host')) {
7189: return 'error: no such course';
7190: }
7191: my $cstring='';
1.800 albertel 7192: foreach my $pref (keys(%prefs)) {
7193: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7194: }
1.84 www 7195: $cstring=~s/\&$//;
7196: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7197: }
7198:
7199: # ---------------------------------------------------------- Make/modify course
7200:
7201: sub createcourse {
1.741 raeburn 7202: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7203: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7204: $url=&declutter($url);
7205: my $cid='';
1.1028 raeburn 7206: if ($context eq 'requestcourses') {
7207: my $can_create = 0;
7208: my ($ownername,$ownerdom) = split(':',$course_owner);
7209: if ($udom eq $ownerdom) {
7210: if (&usertools_access($ownername,$ownerdom,$category,undef,
7211: $context)) {
7212: $can_create = 1;
7213: }
7214: } else {
7215: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7216: $category);
7217: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7218: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7219: if (@curr > 0) {
7220: my @options = qw(approval validate autolimit);
7221: my $optregex = join('|',@options);
7222: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7223: $can_create = 1;
7224: }
7225: }
7226: }
7227: }
7228: if ($can_create) {
7229: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7230: unless (&allowed('ccc',$udom)) {
7231: return 'refused';
7232: }
1.1017 raeburn 7233: }
7234: } else {
7235: return 'refused';
7236: }
1.1028 raeburn 7237: } elsif (!&allowed('ccc',$udom)) {
7238: return 'refused';
1.84 www 7239: }
1.1011 raeburn 7240: # --------------------------------------------------------------- Get Unique ID
7241: my $uname;
7242: if ($cnum =~ /^$match_courseid$/) {
7243: my $chome=&homeserver($cnum,$udom,'true');
7244: if (($chome eq '') || ($chome eq 'no_host')) {
7245: $uname = $cnum;
7246: } else {
1.1038 raeburn 7247: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7248: }
7249: } else {
1.1038 raeburn 7250: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7251: }
7252: return $uname if ($uname =~ /^error/);
7253: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7254: if (!defined($course_server)) {
7255: if (defined(&domain($udom,'primary'))) {
7256: $course_server = &domain($udom,'primary');
7257: } else {
7258: $course_server = $env{'user.home'};
7259: }
7260: }
7261: my %host_servers =
7262: &Apache::lonnet::get_servers($udom,'library');
7263: unless ($host_servers{$course_server}) {
7264: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7265: }
1.84 www 7266: # ------------------------------------------------------------- Make the course
7267: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7268: $course_server);
1.84 www 7269: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7270: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7271: if (($uhome eq '') || ($uhome eq 'no_host')) {
7272: return 'error: no such course';
7273: }
1.271 www 7274: # ----------------------------------------------------------------- Course made
1.516 raeburn 7275: # log existence
1.1029 raeburn 7276: my $now = time;
1.918 raeburn 7277: my $newcourse = {
7278: $udom.'_'.$uname => {
1.921 raeburn 7279: description => $description,
7280: inst_code => $inst_code,
7281: owner => $course_owner,
7282: type => $crstype,
1.1029 raeburn 7283: creator => $env{'user.name'}.':'.
7284: $env{'user.domain'},
7285: created => $now,
7286: context => $context,
1.918 raeburn 7287: },
7288: };
1.921 raeburn 7289: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7290: # set toplevel url
1.271 www 7291: my $topurl=$url;
7292: unless ($nonstandard) {
7293: # ------------------------------------------ For standard courses, make top url
7294: my $mapurl=&clutter($url);
1.278 www 7295: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7296: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7297: <map>
7298: <resource id="1" type="start"></resource>
7299: <resource id="2" src="$mapurl"></resource>
7300: <resource id="3" type="finish"></resource>
7301: <link index="1" from="1" to="2"></link>
7302: <link index="2" from="2" to="3"></link>
7303: </map>
7304: ENDINITMAP
7305: $topurl=&declutter(
1.638 albertel 7306: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7307: );
7308: }
7309: # ----------------------------------------------------------- Write preferences
1.84 www 7310: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7311: ('description' => $description,
7312: 'url' => $topurl,
7313: 'internal.creator' => $env{'user.name'}.':'.
7314: $env{'user.domain'},
7315: 'internal.created' => $now,
7316: 'internal.creationcontext' => $context)
7317: );
1.84 www 7318: return '/'.$udom.'/'.$uname;
7319: }
7320:
1.1011 raeburn 7321: # ------------------------------------------------------------------- Create ID
7322: sub generate_coursenum {
1.1038 raeburn 7323: my ($udom,$crstype) = @_;
1.1011 raeburn 7324: my $domdesc = &domain($udom);
7325: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7326: my $first;
7327: if ($crstype eq 'Community') {
7328: $first = '0';
7329: } else {
7330: $first = int(1+rand(9));
7331: }
7332: my $uname=$first.
1.1011 raeburn 7333: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7334: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7335: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7336: # ----------------------------------------------- Make sure that does not exist
7337: my $uhome=&homeserver($uname,$udom,'true');
7338: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7339: if ($crstype eq 'Community') {
7340: $first = '0';
7341: } else {
7342: $first = int(1+rand(9));
7343: }
7344: $uname=$first.
1.1011 raeburn 7345: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7346: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7347: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7348: $uhome=&homeserver($uname,$udom,'true');
7349: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7350: return 'error: unable to generate unique course-ID';
7351: }
7352: }
7353: return $uname;
7354: }
7355:
1.813 albertel 7356: sub is_course {
7357: my ($cdom,$cnum) = @_;
7358: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7359: undef,'.');
1.813 albertel 7360: if (exists($courses{$cdom.'_'.$cnum})) {
7361: return 1;
7362: }
7363: return 0;
7364: }
7365:
1.1015 raeburn 7366: sub store_userdata {
7367: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7368: my $result;
1.1016 raeburn 7369: if ($datakey ne '') {
1.1013 raeburn 7370: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7371: if ($udom eq '' || $uname eq '') {
7372: $udom = $env{'user.domain'};
7373: $uname = $env{'user.name'};
7374: }
7375: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7376: if (($uhome eq '') || ($uhome eq 'no_host')) {
7377: $result = 'error: no_host';
7378: } else {
7379: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7380: $storehash->{'host'} = $perlvar{'lonHostID'};
7381:
7382: my $namevalue='';
7383: foreach my $key (keys(%{$storehash})) {
7384: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7385: }
7386: $namevalue=~s/\&$//;
1.1056.4.24 raeburn 7387: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7388: $namevalue,$uhome);
1.1013 raeburn 7389: }
7390: } else {
7391: $result = 'error: data to store was not a hash reference';
7392: }
7393: } else {
7394: $result= 'error: invalid requestkey';
7395: }
7396: return $result;
7397: }
7398:
1.21 www 7399: # ---------------------------------------------------------- Assign Custom Role
7400:
7401: sub assigncustomrole {
1.957 raeburn 7402: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7403: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7404: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7405: }
7406:
7407: # ----------------------------------------------------------------- Revoke Role
7408:
7409: sub revokerole {
1.957 raeburn 7410: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7411: my $now=time;
1.965 raeburn 7412: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7413: }
7414:
7415: # ---------------------------------------------------------- Revoke Custom Role
7416:
7417: sub revokecustomrole {
1.957 raeburn 7418: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7419: my $now=time;
1.357 www 7420: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7421: $deleteflag,$selfenroll,$context);
1.17 www 7422: }
7423:
1.533 banghart 7424: # ------------------------------------------------------------ Disk usage
1.535 albertel 7425: sub diskusage {
1.955 raeburn 7426: my ($udom,$uname,$directorypath,$getpropath)=@_;
7427: $directorypath =~ s/\/$//;
7428: my $listing=&reply('du2:'.&escape($directorypath).':'
7429: .&escape($getpropath).':'.&escape($uname).':'
7430: .&escape($udom),homeserver($uname,$udom));
7431: if ($listing eq 'unknown_cmd') {
7432: if ($getpropath) {
7433: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7434: }
7435: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7436: }
1.514 albertel 7437: return $listing;
1.512 banghart 7438: }
7439:
1.566 banghart 7440: sub is_locked {
1.1056.4.17 raeburn 7441: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7442: my @check;
7443: my $is_locked;
1.1056.4.14 raeburn 7444: push(@check,$file_name);
1.613 albertel 7445: my %locked = &get('file_permissions',\@check,
1.620 albertel 7446: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7447: my ($tmp)=keys(%locked);
7448: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7449:
1.566 banghart 7450: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7451: $is_locked = 'false';
7452: foreach my $entry (@{$locked{$file_name}}) {
1.1056.4.17 raeburn 7453: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7454: $is_locked = 'true';
1.1056.4.17 raeburn 7455: if (ref($which) eq 'ARRAY') {
7456: push(@{$which},$entry);
7457: } else {
7458: last;
7459: }
1.745 raeburn 7460: }
7461: }
1.566 banghart 7462: } else {
7463: $is_locked = 'false';
7464: }
1.1056.4.14 raeburn 7465: return $is_locked;
1.566 banghart 7466: }
7467:
1.759 albertel 7468: sub declutter_portfile {
7469: my ($file) = @_;
1.833 albertel 7470: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7471: return $file;
7472: }
7473:
1.559 banghart 7474: # ------------------------------------------------------------- Mark as Read Only
7475:
7476: sub mark_as_readonly {
7477: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7478: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7479: my ($tmp)=keys(%current_permissions);
7480: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7481: foreach my $file (@{$files}) {
1.759 albertel 7482: $file = &declutter_portfile($file);
1.561 banghart 7483: push(@{$current_permissions{$file}},$what);
1.559 banghart 7484: }
1.613 albertel 7485: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7486: return;
7487: }
7488:
1.572 banghart 7489: # ------------------------------------------------------------Save Selected Files
7490:
7491: sub save_selected_files {
7492: my ($user, $path, @files) = @_;
7493: my $filename = $user."savedfiles";
1.573 banghart 7494: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7495: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7496: foreach my $file (@files) {
1.620 albertel 7497: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7498: }
7499: foreach my $file (@other_files) {
1.574 banghart 7500: print (OUT $file."\n");
1.572 banghart 7501: }
1.574 banghart 7502: close (OUT);
1.572 banghart 7503: return 'ok';
7504: }
7505:
1.574 banghart 7506: sub clear_selected_files {
7507: my ($user) = @_;
7508: my $filename = $user."savedfiles";
7509: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7510: print (OUT undef);
7511: close (OUT);
7512: return ("ok");
7513: }
7514:
1.572 banghart 7515: sub files_in_path {
7516: my ($user, $path) = @_;
7517: my $filename = $user."savedfiles";
7518: my %return_files;
1.574 banghart 7519: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7520: while (my $line_in = <IN>) {
1.574 banghart 7521: chomp ($line_in);
7522: my @paths_and_file = split (m!/!, $line_in);
7523: my $file_part = pop (@paths_and_file);
7524: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7525: $path_part.='/';
7526: my $path_and_file = $path_part.$file_part;
7527: if ($path_part eq $path) {
7528: $return_files{$file_part}= 'selected';
7529: }
7530: }
1.574 banghart 7531: close (IN);
7532: return (\%return_files);
1.572 banghart 7533: }
7534:
7535: # called in portfolio select mode, to show files selected NOT in current directory
7536: sub files_not_in_path {
7537: my ($user, $path) = @_;
7538: my $filename = $user."savedfiles";
7539: my @return_files;
7540: my $path_part;
1.800 albertel 7541: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7542: while (my $line = <IN>) {
1.572 banghart 7543: #ok, I know it's clunky, but I want it to work
1.800 albertel 7544: my @paths_and_file = split(m|/|, $line);
7545: my $file_part = pop(@paths_and_file);
7546: chomp($file_part);
7547: my $path_part = join('/', @paths_and_file);
1.572 banghart 7548: $path_part .= '/';
7549: my $path_and_file = $path_part.$file_part;
7550: if ($path_part ne $path) {
1.800 albertel 7551: push(@return_files, ($path_and_file));
1.572 banghart 7552: }
7553: }
1.800 albertel 7554: close(OUT);
1.574 banghart 7555: return (@return_files);
1.572 banghart 7556: }
7557:
1.745 raeburn 7558: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7559:
1.745 raeburn 7560: sub get_portfile_permissions {
7561: my ($domain,$user) = @_;
1.613 albertel 7562: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7563: my ($tmp)=keys(%current_permissions);
7564: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7565: return \%current_permissions;
7566: }
7567:
7568: #---------------------------------------------Get portfolio file access controls
7569:
1.749 raeburn 7570: sub get_access_controls {
1.745 raeburn 7571: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7572: my %access;
7573: my $real_file = $file;
7574: $file =~ s/\.meta$//;
1.745 raeburn 7575: if (defined($file)) {
1.749 raeburn 7576: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7577: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7578: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7579: }
7580: }
1.745 raeburn 7581: } else {
1.749 raeburn 7582: foreach my $key (keys(%{$current_permissions})) {
7583: if ($key =~ /\0accesscontrol$/) {
7584: if (defined($group)) {
7585: if ($key !~ m-^\Q$group\E/-) {
7586: next;
7587: }
7588: }
7589: my ($fullpath) = split(/\0/,$key);
7590: if (ref($$current_permissions{$key}) eq 'HASH') {
7591: foreach my $control (keys(%{$$current_permissions{$key}})) {
7592: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7593: }
7594: }
7595: }
7596: }
7597: }
7598: return %access;
7599: }
7600:
7601: sub modify_access_controls {
7602: my ($file_name,$changes,$domain,$user)=@_;
7603: my ($outcome,$deloutcome);
7604: my %store_permissions;
7605: my %new_values;
7606: my %new_control;
7607: my %translation;
7608: my @deletions = ();
7609: my $now = time;
7610: if (exists($$changes{'activate'})) {
7611: if (ref($$changes{'activate'}) eq 'HASH') {
7612: my @newitems = sort(keys(%{$$changes{'activate'}}));
7613: my $numnew = scalar(@newitems);
7614: for (my $i=0; $i<$numnew; $i++) {
7615: my $newkey = $newitems[$i];
7616: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7617: if ($newkey =~ /^\d+:/) {
7618: $newkey =~ s/^(\d+)/$newid/;
7619: $translation{$1} = $newid;
7620: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7621: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7622: $translation{$1} = $newid;
7623: }
1.749 raeburn 7624: $new_values{$file_name."\0".$newkey} =
7625: $$changes{'activate'}{$newitems[$i]};
7626: $new_control{$newkey} = $now;
7627: }
7628: }
7629: }
7630: my %todelete;
7631: my %changed_items;
7632: foreach my $action ('delete','update') {
7633: if (exists($$changes{$action})) {
7634: if (ref($$changes{$action}) eq 'HASH') {
7635: foreach my $key (keys(%{$$changes{$action}})) {
7636: my ($itemnum) = ($key =~ /^([^:]+):/);
7637: if ($action eq 'delete') {
7638: $todelete{$itemnum} = 1;
7639: } else {
7640: $changed_items{$itemnum} = $key;
7641: }
7642: }
1.745 raeburn 7643: }
7644: }
1.749 raeburn 7645: }
7646: # get lock on access controls for file.
7647: my $lockhash = {
7648: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7649: ':'.$env{'user.domain'},
7650: };
7651: my $tries = 0;
7652: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7653:
7654: while (($gotlock ne 'ok') && $tries <3) {
7655: $tries ++;
7656: sleep 1;
7657: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7658: }
7659: if ($gotlock eq 'ok') {
7660: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7661: my ($tmp)=keys(%curr_permissions);
7662: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7663: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7664: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7665: if (ref($curr_controls) eq 'HASH') {
7666: foreach my $control_item (keys(%{$curr_controls})) {
7667: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7668: if (defined($todelete{$itemnum})) {
7669: push(@deletions,$file_name."\0".$control_item);
7670: } else {
7671: if (defined($changed_items{$itemnum})) {
7672: $new_control{$changed_items{$itemnum}} = $now;
7673: push(@deletions,$file_name."\0".$control_item);
7674: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7675: } else {
7676: $new_control{$control_item} = $$curr_controls{$control_item};
7677: }
7678: }
1.745 raeburn 7679: }
7680: }
7681: }
1.970 raeburn 7682: my ($group);
7683: if (&is_course($domain,$user)) {
7684: ($group,my $file) = split(/\//,$file_name,2);
7685: }
1.749 raeburn 7686: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7687: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7688: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7689: # remove lock
7690: my @del_lock = ($file_name."\0".'locked_access_records');
7691: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7692: my $sqlresult =
1.970 raeburn 7693: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7694: $group);
1.749 raeburn 7695: } else {
7696: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7697: }
1.749 raeburn 7698: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7699: }
7700:
1.827 raeburn 7701: sub make_public_indefinitely {
7702: my ($requrl) = @_;
7703: my $now = time;
7704: my $action = 'activate';
7705: my $aclnum = 0;
7706: if (&is_portfolio_url($requrl)) {
7707: my (undef,$udom,$unum,$file_name,$group) =
7708: &parse_portfolio_url($requrl);
7709: my $current_perms = &get_portfile_permissions($udom,$unum);
7710: my %access_controls = &get_access_controls($current_perms,
7711: $group,$file_name);
7712: foreach my $key (keys(%{$access_controls{$file_name}})) {
7713: my ($num,$scope,$end,$start) =
7714: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7715: if ($scope eq 'public') {
7716: if ($start <= $now && $end == 0) {
7717: $action = 'none';
7718: } else {
7719: $action = 'update';
7720: $aclnum = $num;
7721: }
7722: last;
7723: }
7724: }
7725: if ($action eq 'none') {
7726: return 'ok';
7727: } else {
7728: my %changes;
7729: my $newend = 0;
7730: my $newstart = $now;
7731: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7732: $changes{$action}{$newkey} = {
7733: type => 'public',
7734: time => {
7735: start => $newstart,
7736: end => $newend,
7737: },
7738: };
7739: my ($outcome,$deloutcome,$new_values,$translation) =
7740: &modify_access_controls($file_name,\%changes,$udom,$unum);
7741: return $outcome;
7742: }
7743: } else {
7744: return 'invalid';
7745: }
7746: }
7747:
1.745 raeburn 7748: #------------------------------------------------------Get Marked as Read Only
7749:
7750: sub get_marked_as_readonly {
7751: my ($domain,$user,$what,$group) = @_;
7752: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7753: my @readonly_files;
1.629 banghart 7754: my $cmp1=$what;
7755: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7756: while (my ($file_name,$value) = each(%{$current_permissions})) {
7757: if (defined($group)) {
7758: if ($file_name !~ m-^\Q$group\E/-) {
7759: next;
7760: }
7761: }
1.561 banghart 7762: if (ref($value) eq "ARRAY"){
7763: foreach my $stored_what (@{$value}) {
1.629 banghart 7764: my $cmp2=$stored_what;
1.759 albertel 7765: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7766: $cmp2=join('',@{$stored_what});
1.745 raeburn 7767: }
1.629 banghart 7768: if ($cmp1 eq $cmp2) {
1.561 banghart 7769: push(@readonly_files, $file_name);
1.745 raeburn 7770: last;
1.563 banghart 7771: } elsif (!defined($what)) {
7772: push(@readonly_files, $file_name);
1.745 raeburn 7773: last;
1.561 banghart 7774: }
7775: }
1.745 raeburn 7776: }
1.561 banghart 7777: }
7778: return @readonly_files;
7779: }
1.577 banghart 7780: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7781:
1.577 banghart 7782: sub get_marked_as_readonly_hash {
1.745 raeburn 7783: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7784: my %readonly_files;
1.745 raeburn 7785: while (my ($file_name,$value) = each(%{$current_permissions})) {
7786: if (defined($group)) {
7787: if ($file_name !~ m-^\Q$group\E/-) {
7788: next;
7789: }
7790: }
1.577 banghart 7791: if (ref($value) eq "ARRAY"){
7792: foreach my $stored_what (@{$value}) {
1.745 raeburn 7793: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7794: foreach my $lock_descriptor(@{$stored_what}) {
7795: if ($lock_descriptor eq 'graded') {
7796: $readonly_files{$file_name} = 'graded';
7797: } elsif ($lock_descriptor eq 'handback') {
7798: $readonly_files{$file_name} = 'handback';
7799: } else {
7800: if (!exists($readonly_files{$file_name})) {
7801: $readonly_files{$file_name} = 'locked';
7802: }
7803: }
1.745 raeburn 7804: }
1.750 banghart 7805: }
1.577 banghart 7806: }
7807: }
7808: }
7809: return %readonly_files;
7810: }
1.559 banghart 7811: # ------------------------------------------------------------ Unmark as Read Only
7812:
7813: sub unmark_as_readonly {
1.629 banghart 7814: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7815: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7816: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7817: $file_name = &declutter_portfile($file_name);
1.634 albertel 7818: my $symb_crs = $what;
7819: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7820: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7821: my ($tmp)=keys(%current_permissions);
7822: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7823: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7824: foreach my $file (@readonly_files) {
1.759 albertel 7825: my $clean_file = &declutter_portfile($file);
7826: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7827: my $current_locks = $current_permissions{$file};
1.563 banghart 7828: my @new_locks;
7829: my @del_keys;
7830: if (ref($current_locks) eq "ARRAY"){
7831: foreach my $locker (@{$current_locks}) {
1.632 albertel 7832: my $compare=$locker;
1.749 raeburn 7833: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7834: $compare=join('',@{$locker});
1.746 raeburn 7835: if ($compare ne $symb_crs) {
7836: push(@new_locks, $locker);
7837: }
1.563 banghart 7838: }
7839: }
1.650 albertel 7840: if (scalar(@new_locks) > 0) {
1.563 banghart 7841: $current_permissions{$file} = \@new_locks;
7842: } else {
7843: push(@del_keys, $file);
1.613 albertel 7844: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7845: delete($current_permissions{$file});
1.563 banghart 7846: }
7847: }
1.561 banghart 7848: }
1.613 albertel 7849: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7850: return;
7851: }
1.512 banghart 7852:
1.17 www 7853: # ------------------------------------------------------------ Directory lister
7854:
7855: sub dirlist {
1.955 raeburn 7856: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7857: $uri=~s/^\///;
7858: $uri=~s/\/$//;
1.253 stredwic 7859: my ($udom, $uname);
1.955 raeburn 7860: if ($getuserdir) {
1.253 stredwic 7861: $udom = $userdomain;
7862: $uname = $username;
1.955 raeburn 7863: } else {
7864: (undef,$udom,$uname)=split(/\//,$uri);
7865: if(defined($userdomain)) {
7866: $udom = $userdomain;
7867: }
7868: if(defined($username)) {
7869: $uname = $username;
7870: }
1.253 stredwic 7871: }
1.955 raeburn 7872: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7873:
1.955 raeburn 7874: $dirRoot = $perlvar{'lonDocRoot'};
7875: if (defined($getpropath)) {
7876: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7877: $dirRoot =~ s/\/$//;
1.955 raeburn 7878: } elsif (defined($getuserdir)) {
7879: my $subdir=$uname.'__';
7880: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7881: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7882: ."/$udom/$subdir/$uname";
7883: } elsif (defined($alternateRoot)) {
7884: $dirRoot = $alternateRoot;
1.751 banghart 7885: }
1.253 stredwic 7886:
7887: if($udom) {
7888: if($uname) {
1.955 raeburn 7889: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7890: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7891: .':'.&escape($uname).':'.&escape($udom),
7892: &homeserver($uname,$udom));
7893: if ($listing eq 'unknown_cmd') {
7894: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7895: &homeserver($uname,$udom));
7896: } else {
7897: @listing_results = map { &unescape($_); } split(/:/,$listing);
7898: }
1.605 matthew 7899: if ($listing eq 'unknown_cmd') {
1.800 albertel 7900: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7901: &homeserver($uname,$udom));
1.605 matthew 7902: @listing_results = split(/:/,$listing);
7903: } else {
7904: @listing_results = map { &unescape($_); } split(/:/,$listing);
7905: }
7906: return @listing_results;
1.955 raeburn 7907: } elsif(!$alternateRoot) {
1.800 albertel 7908: my %allusers;
1.841 albertel 7909: my %servers = &get_servers($udom,'library');
1.955 raeburn 7910: foreach my $tryserver (keys(%servers)) {
7911: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7912: &escape($udom),$tryserver);
7913: if ($listing eq 'unknown_cmd') {
7914: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7915: $udom, $tryserver);
7916: } else {
7917: @listing_results = map { &unescape($_); } split(/:/,$listing);
7918: }
1.841 albertel 7919: if ($listing eq 'unknown_cmd') {
7920: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7921: $udom, $tryserver);
7922: @listing_results = split(/:/,$listing);
7923: } else {
7924: @listing_results =
7925: map { &unescape($_); } split(/:/,$listing);
7926: }
7927: if ($listing_results[0] ne 'no_such_dir' &&
7928: $listing_results[0] ne 'empty' &&
7929: $listing_results[0] ne 'con_lost') {
7930: foreach my $line (@listing_results) {
7931: my ($entry) = split(/&/,$line,2);
7932: $allusers{$entry} = 1;
7933: }
7934: }
1.253 stredwic 7935: }
7936: my $alluserstr='';
1.800 albertel 7937: foreach my $user (sort(keys(%allusers))) {
7938: $alluserstr.=$user.'&user:';
1.253 stredwic 7939: }
7940: $alluserstr=~s/:$//;
7941: return split(/:/,$alluserstr);
7942: } else {
1.800 albertel 7943: return ('missing user name');
1.253 stredwic 7944: }
1.955 raeburn 7945: } elsif(!defined($getpropath)) {
1.841 albertel 7946: my @all_domains = sort(&all_domains());
1.955 raeburn 7947: foreach my $domain (@all_domains) {
7948: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7949: }
7950: return @all_domains;
7951: } else {
1.800 albertel 7952: return ('missing domain');
1.275 stredwic 7953: }
7954: }
7955:
7956: # --------------------------------------------- GetFileTimestamp
7957: # This function utilizes dirlist and returns the date stamp for
7958: # when it was last modified. It will also return an error of -1
7959: # if an error occurs
7960:
7961: sub GetFileTimestamp {
1.955 raeburn 7962: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7963: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7964: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7965: my ($fileStat) =
7966: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7967: undef,$getuserdir);
1.275 stredwic 7968: my @stats = split('&', $fileStat);
7969: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7970: # @stats contains first the filename, then the stat output
7971: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7972: } else {
7973: return -1;
1.253 stredwic 7974: }
1.26 www 7975: }
7976:
1.712 albertel 7977: sub stat_file {
7978: my ($uri) = @_;
1.787 albertel 7979: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7980:
1.955 raeburn 7981: my ($udom,$uname,$file);
1.712 albertel 7982: if ($uri =~ m-^/(uploaded|editupload)/-) {
7983: ($udom,$uname,$file) =
1.811 albertel 7984: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7985: $file = 'userfiles/'.$file;
7986: }
7987: if ($uri =~ m-^/res/-) {
7988: ($udom,$uname) =
1.807 albertel 7989: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7990: $file = $uri;
7991: }
7992:
7993: if (!$udom || !$uname || !$file) {
7994: # unable to handle the uri
7995: return ();
7996: }
1.956 raeburn 7997: my $getpropath;
7998: if ($file =~ /^userfiles\//) {
7999: $getpropath = 1;
8000: }
1.955 raeburn 8001: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 8002: my @stats = split('&', $result);
1.721 banghart 8003:
1.712 albertel 8004: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
8005: shift(@stats); #filename is first
8006: return @stats;
8007: }
8008: return ();
8009: }
8010:
1.26 www 8011: # -------------------------------------------------------- Value of a Condition
8012:
1.713 albertel 8013: # gets the value of a specific preevaluated condition
8014: # stored in the string $env{user.state.<cid>}
8015: # or looks up a condition reference in the bighash and if if hasn't
8016: # already been evaluated recurses into docondval to get the value of
8017: # the condition, then memoizing it to
8018: # $env{user.state.<cid>.<condition>}
1.40 www 8019: sub directcondval {
8020: my $number=shift;
1.620 albertel 8021: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8022: &Apache::lonuserstate::evalstate();
8023: }
1.713 albertel 8024: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8025: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8026: } elsif ($number =~ /^_/) {
8027: my $sub_condition;
8028: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8029: &GDBM_READER(),0640)) {
8030: $sub_condition=$bighash{'conditions'.$number};
8031: untie(%bighash);
8032: }
8033: my $value = &docondval($sub_condition);
1.949 raeburn 8034: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8035: return $value;
8036: }
1.620 albertel 8037: if ($env{'user.state.'.$env{'request.course.id'}}) {
8038: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8039: } else {
8040: return 2;
8041: }
8042: }
8043:
1.713 albertel 8044: # get the collection of conditions for this resource
1.26 www 8045: sub condval {
8046: my $condidx=shift;
1.54 www 8047: my $allpathcond='';
1.713 albertel 8048: foreach my $cond (split(/\|/,$condidx)) {
8049: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8050: $allpathcond.=
8051: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8052: }
1.191 harris41 8053: }
1.54 www 8054: $allpathcond=~s/\|$//;
1.713 albertel 8055: return &docondval($allpathcond);
8056: }
8057:
8058: #evaluates an expression of conditions
8059: sub docondval {
8060: my ($allpathcond) = @_;
8061: my $result=0;
8062: if ($env{'request.course.id'}
8063: && defined($allpathcond)) {
8064: my $operand='|';
8065: my @stack;
8066: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8067: if ($chunk eq '(') {
8068: push @stack,($operand,$result);
8069: } elsif ($chunk eq ')') {
8070: my $before=pop @stack;
8071: if (pop @stack eq '&') {
8072: $result=$result>$before?$before:$result;
8073: } else {
8074: $result=$result>$before?$result:$before;
8075: }
8076: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8077: $operand=$chunk;
8078: } else {
8079: my $new=directcondval($chunk);
8080: if ($operand eq '&') {
8081: $result=$result>$new?$new:$result;
8082: } else {
8083: $result=$result>$new?$result:$new;
8084: }
8085: }
8086: }
1.26 www 8087: }
8088: return $result;
1.421 albertel 8089: }
8090:
8091: # ---------------------------------------------------- Devalidate courseresdata
8092:
8093: sub devalidatecourseresdata {
8094: my ($coursenum,$coursedomain)=@_;
8095: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8096: &devalidate_cache_new('courseres',$hashid);
1.28 www 8097: }
8098:
1.763 www 8099:
1.200 www 8100: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8101: #
8102: # Parameters:
8103: # $coursenum - Number of the course.
8104: # $coursedomain - Domain at which the course was created.
8105: # Returns:
8106: # A hash of the course parameters along (I think) with timestamps
8107: # and version info.
1.877 foxr 8108:
1.624 albertel 8109: sub get_courseresdata {
8110: my ($coursenum,$coursedomain)=@_;
1.200 www 8111: my $coursehom=&homeserver($coursenum,$coursedomain);
8112: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8113: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8114: my %dumpreply;
1.417 albertel 8115: unless (defined($cached)) {
1.624 albertel 8116: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8117: $result=\%dumpreply;
1.251 albertel 8118: my ($tmp) = keys(%dumpreply);
8119: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8120: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8121: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8122: return $tmp;
1.416 albertel 8123: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8124: $result=undef;
1.599 albertel 8125: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8126: }
8127: }
1.624 albertel 8128: return $result;
8129: }
8130:
1.633 albertel 8131: sub devalidateuserresdata {
8132: my ($uname,$udom)=@_;
8133: my $hashid="$udom:$uname";
8134: &devalidate_cache_new('userres',$hashid);
8135: }
8136:
1.624 albertel 8137: sub get_userresdata {
8138: my ($uname,$udom)=@_;
8139: #most student don\'t have any data set, check if there is some data
8140: if (&EXT_cache_status($udom,$uname)) { return undef; }
8141:
8142: my $hashid="$udom:$uname";
8143: my ($result,$cached)=&is_cached_new('userres',$hashid);
8144: if (!defined($cached)) {
8145: my %resourcedata=&dump('resourcedata',$udom,$uname);
8146: $result=\%resourcedata;
8147: &do_cache_new('userres',$hashid,$result,600);
8148: }
8149: my ($tmp)=keys(%$result);
8150: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8151: return $result;
8152: }
8153: #error 2 occurs when the .db doesn't exist
8154: if ($tmp!~/error: 2 /) {
1.672 albertel 8155: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8156: " Trying to get resource data for ".
8157: $uname." at ".$udom.": ".
8158: $tmp."</font>");
8159: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8160: #&EXT_cache_set($udom,$uname);
8161: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8162: undef($tmp); # not really an error so don't send it back
1.624 albertel 8163: }
8164: return $tmp;
8165: }
1.879 foxr 8166: #----------------------------------------------- resdata - return resource data
8167: # Purpose:
8168: # Return resource data for either users or for a course.
8169: # Parameters:
8170: # $name - Course/user name.
8171: # $domain - Name of the domain the user/course is registered on.
8172: # $type - Type of thing $name is (must be 'course' or 'user'
8173: # @which - Array of names of resources desired.
8174: # Returns:
8175: # The value of the first reasource in @which that is found in the
8176: # resource hash.
8177: # Exceptional Conditions:
8178: # If the $type passed in is not valid (not the string 'course' or
8179: # 'user', an undefined reference is returned.
8180: # If none of the resources are found, an undef is returned
1.624 albertel 8181: sub resdata {
8182: my ($name,$domain,$type,@which)=@_;
8183: my $result;
8184: if ($type eq 'course') {
8185: $result=&get_courseresdata($name,$domain);
8186: } elsif ($type eq 'user') {
8187: $result=&get_userresdata($name,$domain);
8188: }
8189: if (!ref($result)) { return $result; }
1.251 albertel 8190: foreach my $item (@which) {
1.927 albertel 8191: if (defined($result->{$item->[0]})) {
8192: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8193: }
1.250 albertel 8194: }
1.291 albertel 8195: return undef;
1.200 www 8196: }
8197:
1.379 matthew 8198: #
8199: # EXT resource caching routines
8200: #
8201:
8202: sub clear_EXT_cache_status {
1.383 albertel 8203: &delenv('cache.EXT.');
1.379 matthew 8204: }
8205:
8206: sub EXT_cache_status {
8207: my ($target_domain,$target_user) = @_;
1.383 albertel 8208: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8209: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8210: # We know already the user has no data
8211: return 1;
8212: } else {
8213: return 0;
8214: }
8215: }
8216:
8217: sub EXT_cache_set {
8218: my ($target_domain,$target_user) = @_;
1.383 albertel 8219: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8220: #&appenv({$cachename => time});
1.379 matthew 8221: }
8222:
1.28 www 8223: # --------------------------------------------------------- Value of a Variable
1.58 www 8224: sub EXT {
1.715 albertel 8225:
1.395 albertel 8226: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8227: unless ($varname) { return ''; }
1.218 albertel 8228: #get real user name/domain, courseid and symb
8229: my $courseid;
1.359 albertel 8230: my $publicuser;
1.427 www 8231: if ($symbparm) {
8232: $symbparm=&get_symb_from_alias($symbparm);
8233: }
1.218 albertel 8234: if (!($uname && $udom)) {
1.790 albertel 8235: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8236: if (!$symbparm) { $symbparm=$cursymb; }
8237: } else {
1.620 albertel 8238: $courseid=$env{'request.course.id'};
1.218 albertel 8239: }
1.48 www 8240: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8241: my $rest;
1.320 albertel 8242: if (defined($therest[0])) {
1.48 www 8243: $rest=join('.',@therest);
8244: } else {
8245: $rest='';
8246: }
1.320 albertel 8247:
1.57 www 8248: my $qualifierrest=$qualifier;
8249: if ($rest) { $qualifierrest.='.'.$rest; }
8250: my $spacequalifierrest=$space;
8251: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8252: if ($realm eq 'user') {
1.48 www 8253: # --------------------------------------------------------------- user.resource
8254: if ($space eq 'resource') {
1.651 albertel 8255: if ( (defined($Apache::lonhomework::parsing_a_problem)
8256: || defined($Apache::lonhomework::parsing_a_task))
8257: &&
1.744 albertel 8258: ($symbparm eq &symbread()) ) {
8259: # if we are in the middle of processing the resource the
8260: # get the value we are planning on committing
8261: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8262: return $Apache::lonhomework::results{$qualifierrest};
8263: } else {
8264: return $Apache::lonhomework::history{$qualifierrest};
8265: }
1.335 albertel 8266: } else {
1.359 albertel 8267: my %restored;
1.620 albertel 8268: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8269: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8270: } else {
8271: %restored=&restore($symbparm,$courseid,$udom,$uname);
8272: }
1.335 albertel 8273: return $restored{$qualifierrest};
8274: }
1.48 www 8275: # ----------------------------------------------------------------- user.access
8276: } elsif ($space eq 'access') {
1.218 albertel 8277: # FIXME - not supporting calls for a specific user
1.48 www 8278: return &allowed($qualifier,$rest);
8279: # ------------------------------------------ user.preferences, user.environment
8280: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8281: if (($uname eq $env{'user.name'}) &&
8282: ($udom eq $env{'user.domain'})) {
8283: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8284: } else {
1.359 albertel 8285: my %returnhash;
8286: if (!$publicuser) {
8287: %returnhash=&userenvironment($udom,$uname,
8288: $qualifierrest);
8289: }
1.218 albertel 8290: return $returnhash{$qualifierrest};
8291: }
1.48 www 8292: # ----------------------------------------------------------------- user.course
8293: } elsif ($space eq 'course') {
1.218 albertel 8294: # FIXME - not supporting calls for a specific user
1.620 albertel 8295: return $env{join('.',('request.course',$qualifier))};
1.48 www 8296: # ------------------------------------------------------------------- user.role
8297: } elsif ($space eq 'role') {
1.218 albertel 8298: # FIXME - not supporting calls for a specific user
1.620 albertel 8299: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8300: if ($qualifier eq 'value') {
8301: return $role;
8302: } elsif ($qualifier eq 'extent') {
8303: return $where;
8304: }
8305: # ----------------------------------------------------------------- user.domain
8306: } elsif ($space eq 'domain') {
1.218 albertel 8307: return $udom;
1.48 www 8308: # ------------------------------------------------------------------- user.name
8309: } elsif ($space eq 'name') {
1.218 albertel 8310: return $uname;
1.48 www 8311: # ---------------------------------------------------- Any other user namespace
1.29 www 8312: } else {
1.359 albertel 8313: my %reply;
8314: if (!$publicuser) {
8315: %reply=&get($space,[$qualifierrest],$udom,$uname);
8316: }
8317: return $reply{$qualifierrest};
1.48 www 8318: }
1.236 www 8319: } elsif ($realm eq 'query') {
8320: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8321: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8322: [$spacequalifierrest]);
1.620 albertel 8323: return $env{'form.'.$spacequalifierrest};
1.236 www 8324: } elsif ($realm eq 'request') {
1.48 www 8325: # ------------------------------------------------------------- request.browser
8326: if ($space eq 'browser') {
1.430 www 8327: if ($qualifier eq 'textremote') {
1.676 albertel 8328: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8329: return 1;
8330: } else {
8331: return 0;
8332: }
8333: } else {
1.620 albertel 8334: return $env{'browser.'.$qualifier};
1.430 www 8335: }
1.57 www 8336: # ------------------------------------------------------------ request.filename
8337: } else {
1.620 albertel 8338: return $env{'request.'.$spacequalifierrest};
1.29 www 8339: }
1.28 www 8340: } elsif ($realm eq 'course') {
1.48 www 8341: # ---------------------------------------------------------- course.description
1.620 albertel 8342: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8343: } elsif ($realm eq 'resource') {
1.165 www 8344:
1.620 albertel 8345: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8346: if (!$symbparm) { $symbparm=&symbread(); }
8347: }
1.693 albertel 8348:
8349: if ($space eq 'title') {
8350: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8351: return &gettitle($symbparm);
8352: }
8353:
8354: if ($space eq 'map') {
8355: my ($map) = &decode_symb($symbparm);
8356: return &symbread($map);
8357: }
1.905 albertel 8358: if ($space eq 'filename') {
8359: if ($symbparm) {
8360: return &clutter((&decode_symb($symbparm))[2]);
8361: }
8362: return &hreflocation('',$env{'request.filename'});
8363: }
1.693 albertel 8364:
8365: my ($section, $group, @groups);
1.593 albertel 8366: my ($courselevelm,$courselevel);
1.539 albertel 8367: if ($symbparm && defined($courseid) &&
1.620 albertel 8368: $courseid eq $env{'request.course.id'}) {
1.165 www 8369:
1.218 albertel 8370: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8371:
1.60 www 8372: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8373: my $symbp=$symbparm;
1.735 albertel 8374: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8375:
8376: my $symbparm=$symbp.'.'.$spacequalifierrest;
8377: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8378:
1.620 albertel 8379: if (($env{'user.name'} eq $uname) &&
8380: ($env{'user.domain'} eq $udom)) {
8381: $section=$env{'request.course.sec'};
1.733 raeburn 8382: @groups = split(/:/,$env{'request.course.groups'});
8383: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8384: } else {
1.539 albertel 8385: if (! defined($usection)) {
1.551 albertel 8386: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8387: } else {
8388: $section = $usection;
8389: }
1.733 raeburn 8390: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8391: }
8392:
8393: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8394: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8395: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8396:
1.593 albertel 8397: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8398: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8399: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8400:
1.60 www 8401: # ----------------------------------------------------------- first, check user
1.624 albertel 8402:
8403: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8404: ([$courselevelr,'resource'],
8405: [$courselevelm,'map' ],
8406: [$courselevel, 'course' ]));
1.931 albertel 8407: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8408:
1.594 albertel 8409: # ------------------------------------------------ second, check some of course
1.684 raeburn 8410: my $coursereply;
1.691 raeburn 8411: if (@groups > 0) {
8412: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8413: $mapparm,$spacequalifierrest);
1.927 albertel 8414: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8415: }
1.96 www 8416:
1.684 raeburn 8417: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8418: $env{'course.'.$courseid.'.domain'},
8419: 'course',
8420: ([$seclevelr, 'resource'],
8421: [$seclevelm, 'map' ],
8422: [$seclevel, 'course' ],
8423: [$courselevelr,'resource']));
8424: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8425:
1.60 www 8426: # ------------------------------------------------------ third, check map parms
1.218 albertel 8427: my %parmhash=();
8428: my $thisparm='';
8429: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8430: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8431: &GDBM_READER(),0640)) {
1.218 albertel 8432: $thisparm=$parmhash{$symbparm};
8433: untie(%parmhash);
8434: }
1.927 albertel 8435: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8436: }
1.594 albertel 8437: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8438:
1.218 albertel 8439: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8440: my $filename;
8441: if (!$symbparm) { $symbparm=&symbread(); }
8442: if ($symbparm) {
1.409 www 8443: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8444: } else {
1.620 albertel 8445: $filename=$env{'request.filename'};
1.282 albertel 8446: }
8447: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8448: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8449: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8450: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8451:
1.927 albertel 8452: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8453: if ($symbparm && defined($courseid) &&
1.620 albertel 8454: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8455: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8456: $env{'course.'.$courseid.'.domain'},
8457: 'course',
1.927 albertel 8458: ([$courselevelm,'map' ],
8459: [$courselevel, 'course']));
8460: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8461: }
1.145 www 8462: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8463: unless ($space eq '0') {
1.336 albertel 8464: my @parts=split(/_/,$space);
8465: my $id=pop(@parts);
8466: my $part=join('_',@parts);
8467: if ($part eq '') { $part='0'; }
1.927 albertel 8468: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8469: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8470: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8471: }
1.395 albertel 8472: if ($recurse) { return undef; }
8473: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8474: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8475: # ---------------------------------------------------- Any other user namespace
8476: } elsif ($realm eq 'environment') {
8477: # ----------------------------------------------------------------- environment
1.620 albertel 8478: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8479: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8480: } else {
1.770 albertel 8481: if ($uname eq 'anonymous' && $udom eq '') {
8482: return '';
8483: }
1.219 albertel 8484: my %returnhash=&userenvironment($udom,$uname,
8485: $spacequalifierrest);
8486: return $returnhash{$spacequalifierrest};
8487: }
1.28 www 8488: } elsif ($realm eq 'system') {
1.48 www 8489: # ----------------------------------------------------------------- system.time
8490: if ($space eq 'time') {
8491: return time;
8492: }
1.696 albertel 8493: } elsif ($realm eq 'server') {
8494: # ----------------------------------------------------------------- system.time
8495: if ($space eq 'name') {
8496: return $ENV{'SERVER_NAME'};
8497: }
1.28 www 8498: }
1.48 www 8499: return '';
1.61 www 8500: }
8501:
1.927 albertel 8502: sub get_reply {
8503: my ($reply_value) = @_;
1.940 raeburn 8504: if (ref($reply_value) eq 'ARRAY') {
8505: if (wantarray) {
8506: return @$reply_value;
8507: }
8508: return $reply_value->[0];
8509: } else {
8510: return $reply_value;
1.927 albertel 8511: }
8512: }
8513:
1.691 raeburn 8514: sub check_group_parms {
8515: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8516: my @groupitems = ();
8517: my $resultitem;
1.927 albertel 8518: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8519: foreach my $group (@{$groups}) {
8520: foreach my $level (@levels) {
1.927 albertel 8521: my $item = $courseid.'.['.$group.'].'.$level->[0];
8522: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8523: }
8524: }
8525: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8526: $env{'course.'.$courseid.'.domain'},
8527: 'course',@groupitems);
8528: return $coursereply;
8529: }
8530:
8531: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8532: my ($courseid,@groups) = @_;
8533: @groups = sort(@groups);
1.691 raeburn 8534: return @groups;
8535: }
8536:
1.395 albertel 8537: sub packages_tab_default {
8538: my ($uri,$varname)=@_;
8539: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8540:
8541: my (@extension,@specifics,$do_default);
8542: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8543: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8544: if ($pack_type eq 'default') {
8545: $do_default=1;
8546: } elsif ($pack_type eq 'extension') {
8547: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8548: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8549: # only look at packages defaults for packages that this id is
1.738 albertel 8550: push(@specifics,[$package,$pack_type,$pack_part]);
8551: }
8552: }
8553: # first look for a package that matches the requested part id
8554: foreach my $package (@specifics) {
8555: my (undef,$pack_type,$pack_part)=@{$package};
8556: next if ($pack_part ne $part);
8557: if (defined($packagetab{"$pack_type&$name&default"})) {
8558: return $packagetab{"$pack_type&$name&default"};
8559: }
8560: }
8561: # look for any possible matching non extension_ package
8562: foreach my $package (@specifics) {
8563: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8564: if (defined($packagetab{"$pack_type&$name&default"})) {
8565: return $packagetab{"$pack_type&$name&default"};
8566: }
1.585 albertel 8567: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8568: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8569: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8570: }
8571: }
1.738 albertel 8572: # look for any posible extension_ match
8573: foreach my $package (@extension) {
8574: my ($package,$pack_type)=@{$package};
8575: if (defined($packagetab{"$pack_type&$name&default"})) {
8576: return $packagetab{"$pack_type&$name&default"};
8577: }
8578: if (defined($packagetab{$package."&$name&default"})) {
8579: return $packagetab{$package."&$name&default"};
8580: }
8581: }
8582: # look for a global default setting
8583: if ($do_default && defined($packagetab{"default&$name&default"})) {
8584: return $packagetab{"default&$name&default"};
8585: }
1.395 albertel 8586: return undef;
8587: }
8588:
1.334 albertel 8589: sub add_prefix_and_part {
8590: my ($prefix,$part)=@_;
8591: my $keyroot;
8592: if (defined($prefix) && $prefix !~ /^__/) {
8593: # prefix that has a part already
8594: $keyroot=$prefix;
8595: } elsif (defined($prefix)) {
8596: # prefix that is missing a part
8597: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8598: } else {
8599: # no prefix at all
8600: if (defined($part)) { $keyroot='_'.$part; }
8601: }
8602: return $keyroot;
8603: }
8604:
1.71 www 8605: # ---------------------------------------------------------------- Get metadata
8606:
1.599 albertel 8607: my %metaentry;
1.71 www 8608: sub metadata {
1.176 www 8609: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8610: $uri=&declutter($uri);
1.288 albertel 8611: # if it is a non metadata possible uri return quickly
1.529 albertel 8612: if (($uri eq '') ||
8613: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8614: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.26 raeburn 8615: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 8616: return undef;
8617: }
8618: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8619: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8620: return undef;
1.288 albertel 8621: }
1.73 www 8622: my $filename=$uri;
8623: $uri=~s/\.meta$//;
1.172 www 8624: #
8625: # Is the metadata already cached?
1.177 www 8626: # Look at timestamp of caching
1.172 www 8627: # Everything is cached by the main uri, libraries are never directly cached
8628: #
1.428 albertel 8629: if (!defined($liburi)) {
1.599 albertel 8630: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8631: if (defined($cached)) { return $result->{':'.$what}; }
8632: }
8633: {
1.172 www 8634: #
8635: # Is this a recursive call for a library?
8636: #
1.599 albertel 8637: # if (! exists($metacache{$uri})) {
8638: # $metacache{$uri}={};
8639: # }
1.924 albertel 8640: my $cachetime = 60*60;
1.171 www 8641: if ($liburi) {
8642: $liburi=&declutter($liburi);
8643: $filename=$liburi;
1.401 bowersj2 8644: } else {
1.599 albertel 8645: &devalidate_cache_new('meta',$uri);
8646: undef(%metaentry);
1.401 bowersj2 8647: }
1.140 www 8648: my %metathesekeys=();
1.73 www 8649: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8650: my $metastring;
1.924 albertel 8651: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8652: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8653: $metastring =
1.929 albertel 8654: &Apache::lonnet::ssi_body($which,
1.924 albertel 8655: ('grade_target' => 'meta'));
8656: $cachetime = 1; # only want this cached in the child not long term
1.1056.4.26 raeburn 8657: } elsif (($uri !~ m -^(editupload)/-) &&
8658: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 8659: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8660: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8661: $metastring=&getfile($file);
1.489 albertel 8662: }
1.208 albertel 8663: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8664: my $token;
1.140 www 8665: undef %metathesekeys;
1.71 www 8666: while ($token=$parser->get_token) {
1.339 albertel 8667: if ($token->[0] eq 'S') {
8668: if (defined($token->[2]->{'package'})) {
1.172 www 8669: #
8670: # This is a package - get package info
8671: #
1.339 albertel 8672: my $package=$token->[2]->{'package'};
8673: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8674: if (defined($token->[2]->{'id'})) {
8675: $keyroot.='_'.$token->[2]->{'id'};
8676: }
1.599 albertel 8677: if ($metaentry{':packages'}) {
8678: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8679: } else {
1.599 albertel 8680: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8681: }
1.736 albertel 8682: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8683: my $part=$keyroot;
8684: $part=~s/^\_//;
1.736 albertel 8685: if ($pack_entry=~/^\Q$package\E\&/ ||
8686: $pack_entry=~/^\Q$package\E_0\&/) {
8687: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8688: # ignore package.tab specified default values
8689: # here &package_tab_default() will fetch those
8690: if ($subp eq 'default') { next; }
1.736 albertel 8691: my $value=$packagetab{$pack_entry};
1.432 albertel 8692: my $unikey;
8693: if ($pack =~ /_0$/) {
8694: $unikey='parameter_0_'.$name;
8695: $part=0;
8696: } else {
8697: $unikey='parameter'.$keyroot.'_'.$name;
8698: }
1.339 albertel 8699: if ($subp eq 'display') {
8700: $value.=' [Part: '.$part.']';
8701: }
1.599 albertel 8702: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8703: $metathesekeys{$unikey}=1;
1.599 albertel 8704: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8705: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8706: }
1.599 albertel 8707: if (defined($metaentry{':'.$unikey.'.default'})) {
8708: $metaentry{':'.$unikey}=
8709: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8710: }
1.339 albertel 8711: }
8712: }
8713: } else {
1.172 www 8714: #
8715: # This is not a package - some other kind of start tag
1.339 albertel 8716: #
8717: my $entry=$token->[1];
8718: my $unikey;
8719: if ($entry eq 'import') {
8720: $unikey='';
8721: } else {
8722: $unikey=$entry;
8723: }
8724: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8725:
8726: if (defined($token->[2]->{'id'})) {
8727: $unikey.='_'.$token->[2]->{'id'};
8728: }
1.175 www 8729:
1.339 albertel 8730: if ($entry eq 'import') {
1.175 www 8731: #
8732: # Importing a library here
1.339 albertel 8733: #
8734: if ($depthcount<20) {
8735: my $location=$parser->get_text('/import');
8736: my $dir=$filename;
8737: $dir=~s|[^/]*$||;
8738: $location=&filelocation($dir,$location);
1.736 albertel 8739: my $metadata =
8740: &metadata($uri,'keys', $location,$unikey,
8741: $depthcount+1);
8742: foreach my $meta (split(',',$metadata)) {
8743: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8744: $metathesekeys{$meta}=1;
1.339 albertel 8745: }
8746: }
8747: } else {
8748: if (defined($token->[2]->{'name'})) {
8749: $unikey.='_'.$token->[2]->{'name'};
8750: }
8751: $metathesekeys{$unikey}=1;
1.736 albertel 8752: foreach my $param (@{$token->[3]}) {
8753: $metaentry{':'.$unikey.'.'.$param} =
8754: $token->[2]->{$param};
1.339 albertel 8755: }
8756: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8757: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8758: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8759: # only ws inside the tag, and not in default, so use default
8760: # as value
1.599 albertel 8761: $metaentry{':'.$unikey}=$default;
1.908 albertel 8762: } elsif ( $internaltext =~ /\S/ ) {
8763: # something interesting inside the tag
8764: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8765: } else {
1.908 albertel 8766: # no interesting values, don't set a default
1.339 albertel 8767: }
1.172 www 8768: # end of not-a-package not-a-library import
1.339 albertel 8769: }
1.172 www 8770: # end of not-a-package start tag
1.339 albertel 8771: }
1.172 www 8772: # the next is the end of "start tag"
1.339 albertel 8773: }
8774: }
1.483 albertel 8775: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8776: $extension = lc($extension);
8777: if ($extension eq 'htm') { $extension='html'; }
8778:
1.737 albertel 8779: foreach my $key (keys(%packagetab)) {
1.483 albertel 8780: #no specific packages #how's our extension
8781: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8782: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8783: \%metathesekeys);
8784: }
1.883 albertel 8785:
8786: if (!exists($metaentry{':packages'})
8787: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8788: foreach my $key (keys(%packagetab)) {
1.483 albertel 8789: #no specific packages well let's get default then
8790: if ($key!~/^default&/) { next; }
1.488 albertel 8791: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8792: \%metathesekeys);
8793: }
8794: }
1.338 www 8795: # are there custom rights to evaluate
1.599 albertel 8796: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8797:
1.338 www 8798: #
8799: # Importing a rights file here
1.339 albertel 8800: #
8801: unless ($depthcount) {
1.599 albertel 8802: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8803: my $dir=$filename;
8804: $dir=~s|[^/]*$||;
8805: $location=&filelocation($dir,$location);
1.736 albertel 8806: my $rights_metadata =
8807: &metadata($uri,'keys',$location,'_rights',
8808: $depthcount+1);
8809: foreach my $rights (split(',',$rights_metadata)) {
8810: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8811: $metathesekeys{$rights}=1;
1.339 albertel 8812: }
8813: }
8814: }
1.737 albertel 8815: # uniqifiy package listing
8816: my %seen;
8817: my @uniq_packages =
8818: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8819: $metaentry{':packages'} = join(',',@uniq_packages);
8820:
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.216 www 9005: unless ($ids) {
1.1056.4.21 raeburn 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.1056.4.20 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.803 albertel 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); }
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); }
9435:
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.1056.4.6 raeburn 10099: my %internetdom;
1.1056.4.25 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.1056.4.25 raeburn 10106: chomp($configline);
10107: if ($configline =~ /^\^/) {
10108: if ($configline =~ /^\^([\w.\-]+)/) {
10109: $LC_dns_serv{$1} = 1;
10110: }
10111: next;
10112: }
1.1056.4.6 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.1056.4.6 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.1056.4.2 raeburn 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.1056.4.2 raeburn 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.1056.4.3 raeburn 10241:
10242: sub internet_dom {
10243: &load_hosts_tab() if (!$loaded);
10244:
10245: my ($lonid) = @_;
10246: return $internetdom{$lonid};
10247: }
1.1056.4.27 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.1056.4.3 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:
10403: }
10404:
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);
1.986 foxr 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.1056.4.3 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:
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.1056.4.5 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: }
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.1056.4.3 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.1056.4.3 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.1056.4.1 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.1056.4.13 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.1056.4.13 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.1056.4.13 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.1056.4.16 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.1056.4.13 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>