Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.4.32
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.4.32! raeburn 4: # $Id: lonnet.pm,v 1.1056.4.31 2011/09/28 15:31:05 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 {
1.1056.4.31 raeburn 880: my ($udom,$checkloginvia) = @_;
1.1056.4.3 raeburn 881: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
882: my %servers = &get_servers($udom);
883: my $lowest_load = 30000;
1.1056.4.31 raeburn 884: my ($login_host,$hostname,$portal_path);
1.1056.4.3 raeburn 885: foreach my $lonhost (keys(%servers)) {
1.1056.4.31 raeburn 886: my $loginvia;
887: if ($checkloginvia) {
888: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
889: if ($loginvia) {
890: my ($server,$path) = split(/:/,$loginvia);
891: ($login_host, $lowest_load) =
892: &compare_server_load($lonhost, $login_host, $lowest_load);
893: if ($login_host eq $server) {
894: $portal_path = $path;
895: }
896: } else {
897: ($login_host, $lowest_load) =
898: &compare_server_load($lonhost, $login_host, $lowest_load);
899: if ($login_host eq $lonhost) {
900: $portal_path = '';
901: }
902: }
903: } else {
1.1056.4.3 raeburn 904: ($login_host, $lowest_load) =
1.1056.4.31 raeburn 905: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1056.4.3 raeburn 906: }
907: }
908: if ($login_host ne '') {
1.1056.4.31 raeburn 909: $hostname = &hostname($login_host);
1.1056.4.3 raeburn 910: }
911: return ($login_host,$hostname);
912: }
913:
1.202 matthew 914: # --------------------------------------------- Try to change a user's password
915:
916: sub changepass {
1.799 raeburn 917: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 918: $currentpass = &escape($currentpass);
919: $newpass = &escape($newpass);
1.1030 raeburn 920: my $lonhost = $perlvar{'lonHostID'};
921: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 922: $server);
923: if (! $answer) {
924: &logthis("No reply on password change request to $server ".
925: "by $uname in domain $udom.");
926: } elsif ($answer =~ "^ok") {
927: &logthis("$uname in $udom successfully changed their password ".
928: "on $server.");
929: } elsif ($answer =~ "^pwchange_failure") {
930: &logthis("$uname in $udom was unable to change their password ".
931: "on $server. The action was blocked by either lcpasswd ".
932: "or pwchange");
933: } elsif ($answer =~ "^non_authorized") {
934: &logthis("$uname in $udom did not get their password correct when ".
935: "attempting to change it on $server.");
936: } elsif ($answer =~ "^auth_mode_error") {
937: &logthis("$uname in $udom attempted to change their password despite ".
938: "not being locally or internally authenticated on $server.");
939: } elsif ($answer =~ "^unknown_user") {
940: &logthis("$uname in $udom attempted to change their password ".
941: "on $server but were unable to because $server is not ".
942: "their home server.");
943: } elsif ($answer =~ "^refused") {
944: &logthis("$server refused to change $uname in $udom password because ".
945: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 946: } elsif ($answer =~ "invalid_client") {
947: &logthis("$server refused to change $uname in $udom password because ".
948: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 949: }
950: return $answer;
1.1 albertel 951: }
952:
1.169 harris41 953: # ----------------------- Try to determine user's current authentication scheme
954:
955: sub queryauthenticate {
956: my ($uname,$udom)=@_;
1.456 albertel 957: my $uhome=&homeserver($uname,$udom);
958: if (!$uhome) {
959: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
960: return 'no_host';
961: }
962: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
963: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
964: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 965: }
1.456 albertel 966: return $answer;
1.169 harris41 967: }
968:
1.1 albertel 969: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 970:
1.1 albertel 971: sub authenticate {
1.1056.4.3 raeburn 972: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 973: $upass=&escape($upass);
974: $uname= &LONCAPA::clean_username($uname);
1.836 www 975: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 976: my $newhome;
1.836 www 977: if ((!$uhome) || ($uhome eq 'no_host')) {
978: # Maybe the machine was offline and only re-appeared again recently?
979: &reconlonc();
980: # One more
1.952 raeburn 981: $uhome=&homeserver($uname,$udom,1);
982: if (($uhome eq 'no_host') && $checkdefauth) {
983: if (defined(&domain($udom,'primary'))) {
984: $newhome=&domain($udom,'primary');
985: }
986: if ($newhome ne '') {
987: $uhome = $newhome;
988: }
989: }
1.836 www 990: if ((!$uhome) || ($uhome eq 'no_host')) {
991: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 992: return 'no_host';
993: }
1.1 albertel 994: }
1.1056.4.3 raeburn 995: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 996: if ($answer eq 'authorized') {
1.952 raeburn 997: if ($newhome) {
998: &logthis("User $uname at $udom authorized by $uhome, but needs account");
999: return 'no_account_on_host';
1000: } else {
1001: &logthis("User $uname at $udom authorized by $uhome");
1002: return $uhome;
1003: }
1.471 albertel 1004: }
1005: if ($answer eq 'non_authorized') {
1006: &logthis("User $uname at $udom rejected by $uhome");
1007: return 'no_host';
1.9 www 1008: }
1.471 albertel 1009: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1010: return 'no_host';
1011: }
1012:
1.1056.4.3 raeburn 1013: sub can_host_session {
1014: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1015: my $canhost = 1;
1016: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1017: if (ref($remotesessions) eq 'HASH') {
1018: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1019: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1020: $canhost = 0;
1021: } else {
1022: $canhost = 1;
1023: }
1024: }
1025: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1026: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1027: $canhost = 1;
1028: } else {
1029: $canhost = 0;
1030: }
1031: }
1032: if ($canhost) {
1033: if ($remotesessions->{'version'} ne '') {
1034: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1035: if ($reqmajor ne '' && $reqminor ne '') {
1036: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1037: my $major = $1;
1038: my $minor = $2;
1039: if (($major < $reqmajor ) ||
1040: (($major == $reqmajor) && ($minor < $reqminor))) {
1041: $canhost = 0;
1042: }
1043: } else {
1044: $canhost = 0;
1045: }
1046: }
1047: }
1048: }
1049: }
1050: if ($canhost) {
1051: if (ref($hostedsessions) eq 'HASH') {
1.1056.4.28 raeburn 1052: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1053: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.3 raeburn 1054: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1056.4.28 raeburn 1055: if (($uint_dom ne '') &&
1056: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1056.4.3 raeburn 1057: $canhost = 0;
1058: } else {
1059: $canhost = 1;
1060: }
1061: }
1062: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1056.4.28 raeburn 1063: if (($uint_dom ne '') &&
1064: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1056.4.3 raeburn 1065: $canhost = 1;
1066: } else {
1067: $canhost = 0;
1068: }
1069: }
1070: }
1071: }
1072: return $canhost;
1073: }
1074:
1.1056.4.8 raeburn 1075: sub spare_can_host {
1076: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1077: my $canhost=1;
1078: my @intdoms;
1079: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1080: if (ref($internet_names) eq 'ARRAY') {
1081: @intdoms = @{$internet_names};
1082: }
1083: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1084: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1085: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1086: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1087: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1088: $canhost = &can_host_session($udom,$try_server,$remoterev,
1089: $remotesessions,
1090: $defdomdefaults{'hostedsessions'});
1091: }
1092: return $canhost;
1093: }
1094:
1.1 albertel 1095: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1096:
1.599 albertel 1097: my %homecache;
1.1 albertel 1098: sub homeserver {
1.230 stredwic 1099: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1100: my $index="$uname:$udom";
1.426 albertel 1101:
1.599 albertel 1102: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1103:
1104: my %servers = &get_servers($udom,'library');
1105: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1106: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1107: exists($badServerCache{$tryserver}));
1.841 albertel 1108:
1109: my $answer=reply("home:$udom:$uname",$tryserver);
1110: if ($answer eq 'found') {
1111: delete($badServerCache{$tryserver});
1112: return $homecache{$index}=$tryserver;
1113: } elsif ($answer eq 'no_host') {
1114: $badServerCache{$tryserver}=1;
1115: }
1.1 albertel 1116: }
1117: return 'no_host';
1.70 www 1118: }
1119:
1120: # ------------------------------------- Find the usernames behind a list of IDs
1121:
1122: sub idget {
1123: my ($udom,@ids)=@_;
1124: my %returnhash=();
1125:
1.841 albertel 1126: my %servers = &get_servers($udom,'library');
1127: foreach my $tryserver (keys(%servers)) {
1128: my $idlist=join('&',@ids);
1129: $idlist=~tr/A-Z/a-z/;
1130: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1131: my @answer=();
1132: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1133: @answer=split(/\&/,$reply);
1134: } ;
1135: my $i;
1136: for ($i=0;$i<=$#ids;$i++) {
1137: if ($answer[$i]) {
1138: $returnhash{$ids[$i]}=$answer[$i];
1139: }
1140: }
1141: }
1.70 www 1142: return %returnhash;
1143: }
1144:
1145: # ------------------------------------- Find the IDs behind a list of usernames
1146:
1147: sub idrget {
1148: my ($udom,@unames)=@_;
1149: my %returnhash=();
1.800 albertel 1150: foreach my $uname (@unames) {
1151: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1152: }
1.70 www 1153: return %returnhash;
1154: }
1155:
1156: # ------------------------------- Store away a list of names and associated IDs
1157:
1158: sub idput {
1159: my ($udom,%ids)=@_;
1160: my %servers=();
1.800 albertel 1161: foreach my $uname (keys(%ids)) {
1162: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1163: my $uhom=&homeserver($uname,$udom);
1.70 www 1164: if ($uhom ne 'no_host') {
1.800 albertel 1165: my $id=&escape($ids{$uname});
1.70 www 1166: $id=~tr/A-Z/a-z/;
1.800 albertel 1167: my $esc_unam=&escape($uname);
1.70 www 1168: if ($servers{$uhom}) {
1.800 albertel 1169: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1170: } else {
1.800 albertel 1171: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1172: }
1173: }
1.191 harris41 1174: }
1.800 albertel 1175: foreach my $server (keys(%servers)) {
1176: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1177: }
1.344 www 1178: }
1179:
1.1023 raeburn 1180: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1181: sub dump_dom {
1.1023 raeburn 1182: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1183: if (!$udom) {
1184: $udom=$env{'user.domain'};
1185: }
1186: my %returnhash;
1.1023 raeburn 1187: if ($udom) {
1188: my $uname = &get_domainconfiguser($udom);
1189: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1190: }
1191: return %returnhash;
1192: }
1193:
1.1023 raeburn 1194: # ------------------------------------------ get items from domain db files
1.806 raeburn 1195:
1196: sub get_dom {
1.860 raeburn 1197: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1198: my $items='';
1199: foreach my $item (@$storearr) {
1200: $items.=&escape($item).'&';
1201: }
1202: $items=~s/\&$//;
1.860 raeburn 1203: if (!$udom) {
1204: $udom=$env{'user.domain'};
1205: if (defined(&domain($udom,'primary'))) {
1206: $uhome=&domain($udom,'primary');
1207: } else {
1.874 albertel 1208: undef($uhome);
1.860 raeburn 1209: }
1210: } else {
1211: if (!$uhome) {
1212: if (defined(&domain($udom,'primary'))) {
1213: $uhome=&domain($udom,'primary');
1214: }
1215: }
1216: }
1217: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1218: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1219: my %returnhash;
1.875 albertel 1220: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1221: return %returnhash;
1222: }
1.806 raeburn 1223: my @pairs=split(/\&/,$rep);
1224: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1225: return @pairs;
1226: }
1227: my $i=0;
1228: foreach my $item (@$storearr) {
1229: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1230: $i++;
1231: }
1232: return %returnhash;
1233: } else {
1.880 banghart 1234: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1235: }
1236: }
1237:
1238: # -------------------------------------------- put items in domain db files
1239:
1240: sub put_dom {
1.860 raeburn 1241: my ($namespace,$storehash,$udom,$uhome)=@_;
1242: if (!$udom) {
1243: $udom=$env{'user.domain'};
1244: if (defined(&domain($udom,'primary'))) {
1245: $uhome=&domain($udom,'primary');
1246: } else {
1.874 albertel 1247: undef($uhome);
1.860 raeburn 1248: }
1249: } else {
1250: if (!$uhome) {
1251: if (defined(&domain($udom,'primary'))) {
1252: $uhome=&domain($udom,'primary');
1253: }
1254: }
1255: }
1256: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1257: my $items='';
1258: foreach my $item (keys(%$storehash)) {
1259: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1260: }
1261: $items=~s/\&$//;
1262: return &reply("putdom:$udom:$namespace:$items",$uhome);
1263: } else {
1.860 raeburn 1264: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1265: }
1266: }
1267:
1.1023 raeburn 1268: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1269: sub newput_dom {
1.1023 raeburn 1270: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1271: my $result;
1272: if (!$udom) {
1273: $udom=$env{'user.domain'};
1274: }
1.1023 raeburn 1275: if ($udom) {
1276: my $uname = &get_domainconfiguser($udom);
1277: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1278: }
1279: return $result;
1280: }
1281:
1.1023 raeburn 1282: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1283: sub del_dom {
1.1023 raeburn 1284: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1285: if (ref($storearr) eq 'ARRAY') {
1286: if (!$udom) {
1287: $udom=$env{'user.domain'};
1288: }
1.1023 raeburn 1289: if ($udom) {
1290: my $uname = &get_domainconfiguser($udom);
1291: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1292: }
1293: }
1294: }
1295:
1.1023 raeburn 1296: # ----------------------------------construct domainconfig user for a domain
1297: sub get_domainconfiguser {
1298: my ($udom) = @_;
1299: return $udom.'-domainconfig';
1300: }
1301:
1.837 raeburn 1302: sub retrieve_inst_usertypes {
1303: my ($udom) = @_;
1304: my (%returnhash,@order);
1.989 raeburn 1305: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1306: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1307: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1308: %returnhash = %{$domdefs{'inststatustypes'}};
1309: @order = @{$domdefs{'inststatusorder'}};
1310: } else {
1311: if (defined(&domain($udom,'primary'))) {
1312: my $uhome=&domain($udom,'primary');
1313: my $rep=&reply("inst_usertypes:$udom",$uhome);
1314: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1315: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1316: return (\%returnhash,\@order);
1317: }
1318: my ($hashitems,$orderitems) = split(/:/,$rep);
1319: my @pairs=split(/\&/,$hashitems);
1320: foreach my $item (@pairs) {
1321: my ($key,$value)=split(/=/,$item,2);
1322: $key = &unescape($key);
1323: next if ($key =~ /^error: 2 /);
1324: $returnhash{$key}=&thaw_unescape($value);
1325: }
1326: my @esc_order = split(/\&/,$orderitems);
1327: foreach my $item (@esc_order) {
1328: push(@order,&unescape($item));
1329: }
1330: } else {
1331: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1332: }
1333: }
1334: return (\%returnhash,\@order);
1335: }
1336:
1.868 raeburn 1337: sub is_domainimage {
1338: my ($url) = @_;
1339: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1340: if (&domain($1) ne '') {
1341: return '1';
1342: }
1343: }
1344: return;
1345: }
1346:
1.899 raeburn 1347: sub inst_directory_query {
1348: my ($srch) = @_;
1349: my $udom = $srch->{'srchdomain'};
1350: my %results;
1351: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1352: my $outcome;
1.899 raeburn 1353: if ($homeserver ne '') {
1.904 albertel 1354: my $queryid=&reply("querysend:instdirsearch:".
1355: &escape($srch->{'srchby'}).':'.
1356: &escape($srch->{'srchterm'}).':'.
1357: &escape($srch->{'srchtype'}),$homeserver);
1358: my $host=&hostname($homeserver);
1359: if ($queryid !~/^\Q$host\E\_/) {
1360: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1361: return;
1362: }
1363: my $response = &get_query_reply($queryid);
1364: my $maxtries = 5;
1365: my $tries = 1;
1366: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1367: $response = &get_query_reply($queryid);
1368: $tries ++;
1369: }
1370:
1371: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1372: if ($response eq 'unavailable') {
1373: $outcome = $response;
1374: } else {
1375: $outcome = 'ok';
1376: my @matches = split(/\n/,$response);
1377: foreach my $match (@matches) {
1378: my ($key,$value) = split(/=/,$match);
1379: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1380: }
1.899 raeburn 1381: }
1382: }
1383: }
1.909 raeburn 1384: return ($outcome,%results);
1.899 raeburn 1385: }
1386:
1387: sub usersearch {
1388: my ($srch) = @_;
1389: my $dom = $srch->{'srchdomain'};
1390: my %results;
1391: my %libserv = &all_library();
1392: my $query = 'usersearch';
1393: foreach my $tryserver (keys(%libserv)) {
1394: if (&host_domain($tryserver) eq $dom) {
1395: my $host=&hostname($tryserver);
1396: my $queryid=
1.911 raeburn 1397: &reply("querysend:".&escape($query).':'.
1398: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1399: &escape($srch->{'srchtype'}).':'.
1400: &escape($srch->{'srchterm'}),$tryserver);
1401: if ($queryid !~/^\Q$host\E\_/) {
1402: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1403: next;
1.899 raeburn 1404: }
1405: my $reply = &get_query_reply($queryid);
1406: my $maxtries = 1;
1407: my $tries = 1;
1408: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1409: $reply = &get_query_reply($queryid);
1410: $tries ++;
1411: }
1412: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1413: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1414: } else {
1.911 raeburn 1415: my @matches;
1416: if ($reply =~ /\n/) {
1417: @matches = split(/\n/,$reply);
1418: } else {
1419: @matches = split(/\&/,$reply);
1420: }
1.899 raeburn 1421: foreach my $match (@matches) {
1422: my ($uname,$udom,%userhash);
1.911 raeburn 1423: foreach my $entry (split(/:/,$match)) {
1424: my ($key,$value) =
1425: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1426: $userhash{$key} = $value;
1427: if ($key eq 'username') {
1428: $uname = $value;
1429: } elsif ($key eq 'domain') {
1430: $udom = $value;
1.911 raeburn 1431: }
1.899 raeburn 1432: }
1433: $results{$uname.':'.$udom} = \%userhash;
1434: }
1435: }
1436: }
1437: }
1438: return %results;
1439: }
1440:
1.912 raeburn 1441: sub get_instuser {
1442: my ($udom,$uname,$id) = @_;
1443: my $homeserver = &domain($udom,'primary');
1444: my ($outcome,%results);
1445: if ($homeserver ne '') {
1446: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1447: &escape($id).':'.&escape($udom),$homeserver);
1448: my $host=&hostname($homeserver);
1449: if ($queryid !~/^\Q$host\E\_/) {
1450: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1451: return;
1452: }
1453: my $response = &get_query_reply($queryid);
1454: my $maxtries = 5;
1455: my $tries = 1;
1456: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1457: $response = &get_query_reply($queryid);
1458: $tries ++;
1459: }
1460: if (!&error($response) && $response ne 'refused') {
1461: if ($response eq 'unavailable') {
1462: $outcome = $response;
1463: } else {
1464: $outcome = 'ok';
1465: my @matches = split(/\n/,$response);
1466: foreach my $match (@matches) {
1467: my ($key,$value) = split(/=/,$match);
1468: $results{&unescape($key)} = &thaw_unescape($value);
1469: }
1470: }
1471: }
1472: }
1473: my %userinfo;
1474: if (ref($results{$uname}) eq 'HASH') {
1475: %userinfo = %{$results{$uname}};
1476: }
1477: return ($outcome,%userinfo);
1478: }
1479:
1480: sub inst_rulecheck {
1.923 raeburn 1481: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1482: my %returnhash;
1483: if ($udom ne '') {
1484: if (ref($rules) eq 'ARRAY') {
1485: @{$rules} = map {&escape($_);} (@{$rules});
1486: my $rulestr = join(':',@{$rules});
1487: my $homeserver=&domain($udom,'primary');
1488: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1489: my $response;
1490: if ($item eq 'username') {
1491: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1492: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1493: $homeserver));
1.923 raeburn 1494: } elsif ($item eq 'id') {
1495: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1496: ':'.&escape($id).':'.$rulestr,
1497: $homeserver));
1.945 raeburn 1498: } elsif ($item eq 'selfcreate') {
1499: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1500: &escape($udom).':'.&escape($uname).
1501: ':'.$rulestr,$homeserver));
1.923 raeburn 1502: }
1.912 raeburn 1503: if ($response ne 'refused') {
1504: my @pairs=split(/\&/,$response);
1505: foreach my $item (@pairs) {
1506: my ($key,$value)=split(/=/,$item,2);
1507: $key = &unescape($key);
1508: next if ($key =~ /^error: 2 /);
1509: $returnhash{$key}=&thaw_unescape($value);
1510: }
1511: }
1512: }
1513: }
1514: }
1515: return %returnhash;
1516: }
1517:
1518: sub inst_userrules {
1.923 raeburn 1519: my ($udom,$check) = @_;
1.912 raeburn 1520: my (%ruleshash,@ruleorder);
1521: if ($udom ne '') {
1522: my $homeserver=&domain($udom,'primary');
1523: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1524: my $response;
1525: if ($check eq 'id') {
1526: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1527: $homeserver);
1.943 raeburn 1528: } elsif ($check eq 'email') {
1529: $response=&reply('instemailrules:'.&escape($udom),
1530: $homeserver);
1.923 raeburn 1531: } else {
1532: $response=&reply('instuserrules:'.&escape($udom),
1533: $homeserver);
1534: }
1.912 raeburn 1535: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1536: ($response ne 'unknown_cmd') &&
1.912 raeburn 1537: ($response ne 'no_such_host')) {
1538: my ($hashitems,$orderitems) = split(/:/,$response);
1539: my @pairs=split(/\&/,$hashitems);
1540: foreach my $item (@pairs) {
1541: my ($key,$value)=split(/=/,$item,2);
1542: $key = &unescape($key);
1543: next if ($key =~ /^error: 2 /);
1544: $ruleshash{$key}=&thaw_unescape($value);
1545: }
1546: my @esc_order = split(/\&/,$orderitems);
1547: foreach my $item (@esc_order) {
1548: push(@ruleorder,&unescape($item));
1549: }
1550: }
1551: }
1552: }
1553: return (\%ruleshash,\@ruleorder);
1554: }
1555:
1.976 raeburn 1556: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1557:
1558: sub get_domain_defaults {
1559: my ($domain) = @_;
1560: my $cachetime = 60*60*24;
1561: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1562: if (defined($cached)) {
1563: if (ref($result) eq 'HASH') {
1564: return %{$result};
1565: }
1566: }
1567: my %domdefaults;
1568: my %domconfig =
1.989 raeburn 1569: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1570: 'requestcourses','inststatus',
1.1056.4.3 raeburn 1571: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1572: if (ref($domconfig{'defaults'}) eq 'HASH') {
1573: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1574: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1575: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1576: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1577: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1578: } else {
1579: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1580: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1581: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1582: }
1.976 raeburn 1583: if (ref($domconfig{'quotas'}) eq 'HASH') {
1584: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1585: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1586: } else {
1587: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1588: }
1589: my @usertools = ('aboutme','blog','portfolio');
1590: foreach my $item (@usertools) {
1591: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1592: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1593: }
1594: }
1595: }
1.985 raeburn 1596: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1597: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1598: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1599: }
1600: }
1.989 raeburn 1601: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1602: foreach my $item ('inststatustypes','inststatusorder') {
1603: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1604: }
1605: }
1.1047 raeburn 1606: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1607: foreach my $item ('canuse_pdfforms') {
1608: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1609: }
1610: }
1.1056.4.3 raeburn 1611: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1612: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1613: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1614: }
1615: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1616: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1617: }
1618: }
1.943 raeburn 1619: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1620: $cachetime);
1621: return %domdefaults;
1622: }
1623:
1.344 www 1624: # --------------------------------------------------- Assign a key to a student
1625:
1626: sub assign_access_key {
1.364 www 1627: #
1628: # a valid key looks like uname:udom#comments
1629: # comments are being appended
1630: #
1.498 www 1631: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1632: $kdom=
1.620 albertel 1633: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1634: $knum=
1.620 albertel 1635: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1636: $cdom=
1.620 albertel 1637: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1638: $cnum=
1.620 albertel 1639: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1640: $udom=$env{'user.name'} unless (defined($udom));
1641: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1642: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1643: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1644: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1645: # assigned to this person
1646: # - this should not happen,
1.345 www 1647: # unless something went wrong
1648: # the first time around
1649: # ready to assign
1.364 www 1650: $logentry=$1.'; '.$logentry;
1.496 www 1651: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1652: $kdom,$knum) eq 'ok') {
1.345 www 1653: # key now belongs to user
1.346 www 1654: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1655: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1656: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1657: return 'ok';
1658: } else {
1659: return
1660: 'error: Count not permanently assign key, will need to be re-entered later.';
1661: }
1662: } else {
1663: return 'error: Could not assign key, try again later.';
1664: }
1.364 www 1665: } elsif (!$existing{$ckey}) {
1.345 www 1666: # the key does not exist
1667: return 'error: The key does not exist';
1668: } else {
1669: # the key is somebody else's
1670: return 'error: The key is already in use';
1671: }
1.344 www 1672: }
1673:
1.364 www 1674: # ------------------------------------------ put an additional comment on a key
1675:
1676: sub comment_access_key {
1677: #
1678: # a valid key looks like uname:udom#comments
1679: # comments are being appended
1680: #
1681: my ($ckey,$cdom,$cnum,$logentry)=@_;
1682: $cdom=
1.620 albertel 1683: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1684: $cnum=
1.620 albertel 1685: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1686: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1687: if ($existing{$ckey}) {
1688: $existing{$ckey}.='; '.$logentry;
1689: # ready to assign
1.367 www 1690: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1691: $cdom,$cnum) eq 'ok') {
1692: return 'ok';
1693: } else {
1694: return 'error: Count not store comment.';
1695: }
1696: } else {
1697: # the key does not exist
1698: return 'error: The key does not exist';
1699: }
1700: }
1701:
1.344 www 1702: # ------------------------------------------------------ Generate a set of keys
1703:
1704: sub generate_access_keys {
1.364 www 1705: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1706: $cdom=
1.620 albertel 1707: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1708: $cnum=
1.620 albertel 1709: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1710: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1711: unless (($cdom) && ($cnum)) { return 0; }
1712: if ($number>10000) { return 0; }
1713: sleep(2); # make sure don't get same seed twice
1714: srand(time()^($$+($$<<15))); # from "Programming Perl"
1715: my $total=0;
1716: for (my $i=1;$i<=$number;$i++) {
1717: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1718: sprintf("%lx",int(100000*rand)).'-'.
1719: sprintf("%lx",int(100000*rand));
1720: $newkey=~s/1/g/g; # folks mix up 1 and l
1721: $newkey=~s/0/h/g; # and also 0 and O
1722: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1723: if ($existing{$newkey}) {
1724: $i--;
1725: } else {
1.364 www 1726: if (&put('accesskeys',
1727: { $newkey => '# generated '.localtime().
1.620 albertel 1728: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1729: '; '.$logentry },
1730: $cdom,$cnum) eq 'ok') {
1.344 www 1731: $total++;
1732: }
1733: }
1734: }
1.620 albertel 1735: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1736: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1737: return $total;
1738: }
1739:
1740: # ------------------------------------------------------- Validate an accesskey
1741:
1742: sub validate_access_key {
1743: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1744: $cdom=
1.620 albertel 1745: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1746: $cnum=
1.620 albertel 1747: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1748: $udom=$env{'user.domain'} unless (defined($udom));
1749: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1750: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1751: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1752: }
1753:
1754: # ------------------------------------- Find the section of student in a course
1.652 albertel 1755: sub devalidate_getsection_cache {
1756: my ($udom,$unam,$courseid)=@_;
1757: my $hashid="$udom:$unam:$courseid";
1758: &devalidate_cache_new('getsection',$hashid);
1759: }
1.298 matthew 1760:
1.815 albertel 1761: sub courseid_to_courseurl {
1762: my ($courseid) = @_;
1763: #already url style courseid
1764: return $courseid if ($courseid =~ m{^/});
1765:
1766: if (exists($env{'course.'.$courseid.'.num'})) {
1767: my $cnum = $env{'course.'.$courseid.'.num'};
1768: my $cdom = $env{'course.'.$courseid.'.domain'};
1769: return "/$cdom/$cnum";
1770: }
1771:
1772: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1773: if (exists($courseinfo{'num'})) {
1774: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1775: }
1776:
1777: return undef;
1778: }
1779:
1.298 matthew 1780: sub getsection {
1781: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1782: my $cachetime=1800;
1.551 albertel 1783:
1784: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1785: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1786: if (defined($cached)) { return $result; }
1787:
1.298 matthew 1788: my %Pending;
1789: my %Expired;
1790: #
1791: # Each role can either have not started yet (pending), be active,
1792: # or have expired.
1793: #
1794: # If there is an active role, we are done.
1795: #
1796: # If there is more than one role which has not started yet,
1797: # choose the one which will start sooner
1798: # If there is one role which has not started yet, return it.
1799: #
1800: # If there is more than one expired role, choose the one which ended last.
1801: # If there is a role which has expired, return it.
1802: #
1.815 albertel 1803: $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 1804: my $extra = &freeze_escape({'skipcheck' => 1});
1805: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1806: foreach my $key (keys(%roleshash)) {
1.479 albertel 1807: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1808: my $section=$1;
1809: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1810: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1811: my $now=time;
1.548 albertel 1812: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1813: $Expired{$end}=$section;
1814: next;
1815: }
1.548 albertel 1816: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1817: $Pending{$start}=$section;
1818: next;
1819: }
1.599 albertel 1820: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1821: }
1822: #
1823: # Presumedly there will be few matching roles from the above
1824: # loop and the sorting time will be negligible.
1825: if (scalar(keys(%Pending))) {
1826: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1827: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1828: }
1829: if (scalar(keys(%Expired))) {
1830: my @sorted = sort {$a <=> $b} keys(%Expired);
1831: my $time = pop(@sorted);
1.599 albertel 1832: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1833: }
1.599 albertel 1834: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1835: }
1.70 www 1836:
1.599 albertel 1837: sub save_cache {
1838: &purge_remembered();
1.722 albertel 1839: #&Apache::loncommon::validate_page();
1.620 albertel 1840: undef(%env);
1.780 albertel 1841: undef($env_loaded);
1.599 albertel 1842: }
1.452 albertel 1843:
1.599 albertel 1844: my $to_remember=-1;
1845: my %remembered;
1846: my %accessed;
1847: my $kicks=0;
1848: my $hits=0;
1.849 albertel 1849: sub make_key {
1850: my ($name,$id) = @_;
1.872 albertel 1851: if (length($id) > 65
1852: && length(&escape($id)) > 200) {
1853: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1854: }
1.849 albertel 1855: return &escape($name.':'.$id);
1856: }
1857:
1.599 albertel 1858: sub devalidate_cache_new {
1859: my ($name,$id,$debug) = @_;
1860: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1861: $id=&make_key($name,$id);
1.599 albertel 1862: $memcache->delete($id);
1863: delete($remembered{$id});
1864: delete($accessed{$id});
1865: }
1866:
1867: sub is_cached_new {
1868: my ($name,$id,$debug) = @_;
1.849 albertel 1869: $id=&make_key($name,$id);
1.599 albertel 1870: if (exists($remembered{$id})) {
1871: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1872: $accessed{$id}=[&gettimeofday()];
1873: $hits++;
1874: return ($remembered{$id},1);
1875: }
1876: my $value = $memcache->get($id);
1877: if (!(defined($value))) {
1878: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1879: return (undef,undef);
1.416 albertel 1880: }
1.599 albertel 1881: if ($value eq '__undef__') {
1882: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1883: $value=undef;
1884: }
1885: &make_room($id,$value,$debug);
1886: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1887: return ($value,1);
1888: }
1889:
1890: sub do_cache_new {
1891: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1892: $id=&make_key($name,$id);
1.599 albertel 1893: my $setvalue=$value;
1894: if (!defined($setvalue)) {
1895: $setvalue='__undef__';
1896: }
1.623 albertel 1897: if (!defined($time) ) {
1898: $time=600;
1899: }
1.599 albertel 1900: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1901: my $result = $memcache->set($id,$setvalue,$time);
1902: if (! $result) {
1.872 albertel 1903: &logthis("caching of id -> $id failed");
1.910 albertel 1904: $memcache->disconnect_all();
1.872 albertel 1905: }
1.600 albertel 1906: # need to make a copy of $value
1.919 albertel 1907: &make_room($id,$value,$debug);
1.599 albertel 1908: return $value;
1909: }
1910:
1911: sub make_room {
1912: my ($id,$value,$debug)=@_;
1.919 albertel 1913:
1914: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1915: : $value;
1.599 albertel 1916: if ($to_remember<0) { return; }
1917: $accessed{$id}=[&gettimeofday()];
1918: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1919: my $to_kick;
1920: my $max_time=0;
1921: foreach my $other (keys(%accessed)) {
1922: if (&tv_interval($accessed{$other}) > $max_time) {
1923: $to_kick=$other;
1924: $max_time=&tv_interval($accessed{$other});
1925: }
1926: }
1927: delete($remembered{$to_kick});
1928: delete($accessed{$to_kick});
1929: $kicks++;
1930: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1931: return;
1932: }
1933:
1.599 albertel 1934: sub purge_remembered {
1.604 albertel 1935: #&logthis("Tossing ".scalar(keys(%remembered)));
1936: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1937: undef(%remembered);
1938: undef(%accessed);
1.428 albertel 1939: }
1.70 www 1940: # ------------------------------------- Read an entry from a user's environment
1941:
1942: sub userenvironment {
1943: my ($udom,$unam,@what)=@_;
1.976 raeburn 1944: my $items;
1945: foreach my $item (@what) {
1946: $items.=&escape($item).'&';
1947: }
1948: $items=~s/\&$//;
1.70 www 1949: my %returnhash=();
1.1009 raeburn 1950: my $uhome = &homeserver($unam,$udom);
1951: unless ($uhome eq 'no_host') {
1952: my @answer=split(/\&/,
1953: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1954: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1955: return %returnhash;
1956: }
1.1009 raeburn 1957: my $i;
1958: for ($i=0;$i<=$#what;$i++) {
1959: $returnhash{$what[$i]}=&unescape($answer[$i]);
1960: }
1.70 www 1961: }
1962: return %returnhash;
1.1 albertel 1963: }
1964:
1.617 albertel 1965: # ---------------------------------------------------------- Get a studentphoto
1966: sub studentphoto {
1967: my ($udom,$unam,$ext) = @_;
1968: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1969: if (defined($env{'request.course.id'})) {
1.708 raeburn 1970: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1971: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1972: return(&retrievestudentphoto($udom,$unam,$ext));
1973: } else {
1974: my ($result,$perm_reqd)=
1.707 albertel 1975: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1976: if ($result eq 'ok') {
1977: if (!($perm_reqd eq 'yes')) {
1978: return(&retrievestudentphoto($udom,$unam,$ext));
1979: }
1980: }
1981: }
1982: }
1983: } else {
1984: my ($result,$perm_reqd) =
1.707 albertel 1985: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1986: if ($result eq 'ok') {
1987: if (!($perm_reqd eq 'yes')) {
1988: return(&retrievestudentphoto($udom,$unam,$ext));
1989: }
1990: }
1991: }
1992: return '/adm/lonKaputt/lonlogo_broken.gif';
1993: }
1994:
1995: sub retrievestudentphoto {
1996: my ($udom,$unam,$ext,$type) = @_;
1997: my $home=&Apache::lonnet::homeserver($unam,$udom);
1998: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1999: if ($ret eq 'ok') {
2000: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2001: if ($type eq 'thumbnail') {
2002: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2003: }
2004: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2005: return $tokenurl;
2006: } else {
2007: if ($type eq 'thumbnail') {
2008: return '/adm/lonKaputt/genericstudent_tn.gif';
2009: } else {
2010: return '/adm/lonKaputt/lonlogo_broken.gif';
2011: }
1.617 albertel 2012: }
2013: }
2014:
1.263 www 2015: # -------------------------------------------------------------------- New chat
2016:
2017: sub chatsend {
1.724 raeburn 2018: my ($newentry,$anon,$group)=@_;
1.620 albertel 2019: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2020: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2021: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2022: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2023: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2024: &escape($newentry)).':'.$group,$chome);
1.292 www 2025: }
2026:
2027: # ------------------------------------------ Find current version of a resource
2028:
2029: sub getversion {
2030: my $fname=&clutter(shift);
2031: unless ($fname=~/^\/res\//) { return -1; }
2032: return ¤tversion(&filelocation('',$fname));
2033: }
2034:
2035: sub currentversion {
2036: my $fname=shift;
1.599 albertel 2037: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 2038: if (defined($cached)) { return $result; }
1.292 www 2039: my $author=$fname;
2040: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2041: my ($udom,$uname)=split(/\//,$author);
2042: my $home=homeserver($uname,$udom);
2043: if ($home eq 'no_host') {
2044: return -1;
2045: }
2046: my $answer=reply("currentversion:$fname",$home);
2047: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2048: return -1;
2049: }
1.599 albertel 2050: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 2051: }
2052:
1.1 albertel 2053: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2054:
1.1 albertel 2055: sub subscribe {
2056: my $fname=shift;
1.761 raeburn 2057: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2058: $fname=~s/[\n\r]//g;
1.1 albertel 2059: my $author=$fname;
2060: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2061: my ($udom,$uname)=split(/\//,$author);
2062: my $home=homeserver($uname,$udom);
1.335 albertel 2063: if ($home eq 'no_host') {
2064: return 'not_found';
1.1 albertel 2065: }
2066: my $answer=reply("sub:$fname",$home);
1.64 www 2067: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2068: $answer.=' by '.$home;
2069: }
1.1 albertel 2070: return $answer;
2071: }
2072:
1.8 www 2073: # -------------------------------------------------------------- Replicate file
2074:
2075: sub repcopy {
2076: my $filename=shift;
1.23 www 2077: $filename=~s/\/+/\//g;
1.607 raeburn 2078: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2079: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2080: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2081: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2082: return &repcopy_userfile($filename);
2083: }
1.532 albertel 2084: $filename=~s/[\n\r]//g;
1.8 www 2085: my $transname="$filename.in.transfer";
1.828 www 2086: # FIXME: this should flock
1.607 raeburn 2087: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2088: my $remoteurl=subscribe($filename);
1.64 www 2089: if ($remoteurl =~ /^con_lost by/) {
2090: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2091: return 'unavailable';
1.8 www 2092: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2093: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2094: return 'not_found';
1.64 www 2095: } elsif ($remoteurl =~ /^rejected by/) {
2096: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2097: return 'forbidden';
1.20 www 2098: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2099: return 'ok';
1.8 www 2100: } else {
1.290 www 2101: my $author=$filename;
2102: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2103: my ($udom,$uname)=split(/\//,$author);
2104: my $home=homeserver($uname,$udom);
2105: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2106: my @parts=split(/\//,$filename);
2107: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2108: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2109: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2110: return 'bad_request';
1.8 www 2111: }
2112: my $count;
2113: for ($count=5;$count<$#parts;$count++) {
2114: $path.="/$parts[$count]";
2115: if ((-e $path)!=1) {
2116: mkdir($path,0777);
2117: }
2118: }
2119: my $ua=new LWP::UserAgent;
2120: my $request=new HTTP::Request('GET',"$remoteurl");
2121: my $response=$ua->request($request,$transname);
2122: if ($response->is_error()) {
2123: unlink($transname);
2124: my $message=$response->status_line;
1.672 albertel 2125: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2126: ." LWP get: $message: $filename</font>");
1.607 raeburn 2127: return 'unavailable';
1.8 www 2128: } else {
1.16 www 2129: if ($remoteurl!~/\.meta$/) {
2130: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2131: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2132: if ($mresponse->is_error()) {
2133: unlink($filename.'.meta');
2134: &logthis(
1.672 albertel 2135: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2136: }
2137: }
1.8 www 2138: rename($transname,$filename);
1.607 raeburn 2139: return 'ok';
1.8 www 2140: }
1.290 www 2141: }
1.8 www 2142: }
1.330 www 2143: }
2144:
2145: # ------------------------------------------------ Get server side include body
2146: sub ssi_body {
1.381 albertel 2147: my ($filelink,%form)=@_;
1.606 matthew 2148: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2149: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2150: }
1.953 www 2151: my $output='';
2152: my $response;
1.980 raeburn 2153: if ($filelink=~/^https?\:/) {
1.954 raeburn 2154: ($output,$response)=&externalssi($filelink);
1.953 www 2155: } else {
1.1004 droeschl 2156: $filelink .= $filelink=~/\?/ ? '&' : '?';
2157: $filelink .= 'inhibitmenu=yes';
1.953 www 2158: ($output,$response)=&ssi($filelink,%form);
2159: }
1.778 albertel 2160: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2161: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2162: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2163: if (wantarray) {
2164: return ($output, $response);
2165: } else {
2166: return $output;
2167: }
1.8 www 2168: }
2169:
1.15 www 2170: # --------------------------------------------------------- Server Side Include
2171:
1.782 albertel 2172: sub absolute_url {
2173: my ($host_name) = @_;
2174: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2175: if ($host_name eq '') {
2176: $host_name = $ENV{'SERVER_NAME'};
2177: }
2178: return $protocol.$host_name;
2179: }
2180:
1.942 foxr 2181: #
2182: # Server side include.
2183: # Parameters:
2184: # fn Possibly encrypted resource name/id.
2185: # form Hash that describes how the rendering should be done
2186: # and other things.
1.944 foxr 2187: # Returns:
1.950 raeburn 2188: # Scalar context: The content of the response.
2189: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2190: #
1.15 www 2191: sub ssi {
2192:
1.944 foxr 2193: my ($fn,%form)=@_;
1.15 www 2194: my $ua=new LWP::UserAgent;
1.23 www 2195: my $request;
1.711 albertel 2196:
2197: $form{'no_update_last_known'}=1;
1.895 albertel 2198: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2199: if (%form) {
1.782 albertel 2200: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2201: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2202: } else {
1.782 albertel 2203: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2204: }
2205:
1.15 www 2206: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2207: my $response=$ua->request($request);
2208:
1.944 foxr 2209: if (wantarray) {
2210: return ($response->content, $response);
2211: } else {
2212: return $response->content;
1.942 foxr 2213: }
1.324 www 2214: }
2215:
2216: sub externalssi {
2217: my ($url)=@_;
2218: my $ua=new LWP::UserAgent;
2219: my $request=new HTTP::Request('GET',$url);
2220: my $response=$ua->request($request);
1.954 raeburn 2221: if (wantarray) {
2222: return ($response->content, $response);
2223: } else {
2224: return $response->content;
2225: }
1.15 www 2226: }
1.254 www 2227:
1.492 albertel 2228: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2229:
2230: sub allowuploaded {
2231: my ($srcurl,$url)=@_;
2232: $url=&clutter(&declutter($url));
2233: my $dir=$url;
2234: $dir=~s/\/[^\/]+$//;
2235: my %httpref=();
2236: my $httpurl=&hreflocation('',$url);
2237: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2238: &Apache::lonnet::appenv(\%httpref);
1.254 www 2239: }
1.477 raeburn 2240:
1.478 albertel 2241: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2242: # input: action, courseID, current domain, intended
1.637 raeburn 2243: # path to file, source of file, instruction to parse file for objects,
2244: # ref to hash for embedded objects,
2245: # ref to hash for codebase of java objects.
1.1056.4.16 raeburn 2246: # reference to scalar to accommodate mime type determined
2247: # from File::MMagic if $parser = parse.
1.637 raeburn 2248: #
1.485 raeburn 2249: # output: url to file (if action was uploaddoc),
2250: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2251: #
1.478 albertel 2252: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2253: # course.
1.477 raeburn 2254: #
1.478 albertel 2255: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2256: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2257: # course's home server.
1.477 raeburn 2258: #
1.478 albertel 2259: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2260: # be copied from $source (current location) to
2261: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2262: # and will then be copied to
2263: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2264: # course's home server.
1.485 raeburn 2265: #
1.481 raeburn 2266: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2267: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2268: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2269: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2270: # in course's home server.
1.637 raeburn 2271: #
1.477 raeburn 2272:
2273: sub process_coursefile {
1.1056.4.16 raeburn 2274: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2275: $mimetype)=@_;
1.477 raeburn 2276: my $fetchresult;
1.638 albertel 2277: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2278: if ($action eq 'propagate') {
1.638 albertel 2279: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2280: $home);
1.481 raeburn 2281: } else {
1.477 raeburn 2282: my $fpath = '';
2283: my $fname = $file;
1.478 albertel 2284: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2285: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2286: my $filepath = &build_filepath($fpath);
1.481 raeburn 2287: if ($action eq 'copy') {
2288: if ($source eq '') {
2289: $fetchresult = 'no source file';
2290: return $fetchresult;
2291: } else {
2292: my $destination = $filepath.'/'.$fname;
2293: rename($source,$destination);
2294: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2295: $home);
1.481 raeburn 2296: }
2297: } elsif ($action eq 'uploaddoc') {
2298: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2299: print $fh $env{'form.'.$source};
1.481 raeburn 2300: close($fh);
1.637 raeburn 2301: if ($parser eq 'parse') {
1.1024 raeburn 2302: my $mm = new File::MMagic;
1.1056.4.16 raeburn 2303: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2304: if ($type eq 'text/html') {
1.1024 raeburn 2305: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2306: unless ($parse_result eq 'ok') {
2307: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2308: }
1.637 raeburn 2309: }
1.1056.4.16 raeburn 2310: if (ref($mimetype)) {
2311: $$mimetype = $type;
2312: }
1.637 raeburn 2313: }
1.477 raeburn 2314: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2315: $home);
1.481 raeburn 2316: if ($fetchresult eq 'ok') {
2317: return '/uploaded/'.$fpath.'/'.$fname;
2318: } else {
2319: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2320: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2321: return '/adm/notfound.html';
2322: }
1.477 raeburn 2323: }
2324: }
1.485 raeburn 2325: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2326: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2327: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2328: }
2329: return $fetchresult;
2330: }
2331:
1.637 raeburn 2332: sub build_filepath {
2333: my ($fpath) = @_;
2334: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2335: unless ($fpath eq '') {
2336: my @parts=split('/',$fpath);
2337: foreach my $part (@parts) {
2338: $filepath.= '/'.$part;
2339: if ((-e $filepath)!=1) {
2340: mkdir($filepath,0777);
2341: }
2342: }
2343: }
2344: return $filepath;
2345: }
2346:
2347: sub store_edited_file {
1.638 albertel 2348: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2349: my $file = $primary_url;
2350: $file =~ s#^/uploaded/$docudom/$docuname/##;
2351: my $fpath = '';
2352: my $fname = $file;
2353: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2354: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2355: my $filepath = &build_filepath($fpath);
2356: open(my $fh,'>'.$filepath.'/'.$fname);
2357: print $fh $content;
2358: close($fh);
1.638 albertel 2359: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2360: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2361: $home);
1.637 raeburn 2362: if ($$fetchresult eq 'ok') {
2363: return '/uploaded/'.$fpath.'/'.$fname;
2364: } else {
1.638 albertel 2365: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2366: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2367: return '/adm/notfound.html';
2368: }
2369: }
2370:
1.531 albertel 2371: sub clean_filename {
1.831 albertel 2372: my ($fname,$args)=@_;
1.315 www 2373: # Replace Windows backslashes by forward slashes
1.257 www 2374: $fname=~s/\\/\//g;
1.831 albertel 2375: if (!$args->{'keep_path'}) {
2376: # Get rid of everything but the actual filename
2377: $fname=~s/^.*\/([^\/]+)$/$1/;
2378: }
1.315 www 2379: # Replace spaces by underscores
2380: $fname=~s/\s+/\_/g;
2381: # Replace all other weird characters by nothing
1.831 albertel 2382: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2383: # Replace all .\d. sequences with _\d. so they no longer look like version
2384: # numbers
2385: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2386: return $fname;
2387: }
1.1051 raeburn 2388: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2389: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2390: # image with the same aspect ratio as the original, but with dimensions which do
2391: # not exceed $resizewidth and $resizeheight.
2392:
1.984 neumanie 2393: sub resizeImage {
1.1051 raeburn 2394: my ($img_path,$resizewidth,$resizeheight) = @_;
2395: my $ima = Image::Magick->new;
2396: my $resized;
2397: if (-e $img_path) {
2398: $ima->Read($img_path);
2399: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2400: my $width = $ima->Get('width');
2401: my $height = $ima->Get('height');
2402: if ($width > $resizewidth) {
2403: my $factor = $width/$resizewidth;
2404: my $newheight = $height/$factor;
2405: $ima->Scale(width=>$resizewidth,height=>$newheight);
2406: $resized = 1;
2407: }
2408: }
2409: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2410: my $width = $ima->Get('width');
2411: my $height = $ima->Get('height');
2412: if ($height > $resizeheight) {
2413: my $factor = $height/$resizeheight;
2414: my $newwidth = $width/$factor;
2415: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2416: $resized = 1;
2417: }
2418: }
2419: if ($resized) {
2420: $ima->Write($img_path);
2421: }
2422: }
2423: return;
1.977 amueller 2424: }
2425:
1.608 albertel 2426: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2427: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13 raeburn 2428: # the desired filename is in $env{"form.$formname.filename"}
2429: # $context - possible values: coursedoc, existingfile, overwrite,
2430: # canceloverwrite, or ''.
2431: # if 'coursedoc': upload to the current course
2432: # if 'existingfile': write file to tmp/overwrites directory
2433: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2434: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2435: # $subdir - directory in userfile to store the file into
1.858 raeburn 2436: # $parser - instruction to parse file for objects ($parser = parse)
2437: # $allfiles - reference to hash for embedded objects
2438: # $codebase - reference to hash for codebase of java objects
2439: # $desuname - username for permanent storage of uploaded file
2440: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2441: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2442: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2443: # $resizewidth - width (pixels) to which to resize uploaded image
2444: # $resizeheight - height (pixels) to which to resize uploaded image
1.1056.4.16 raeburn 2445: # $mimetype - reference to scalar to accommodate mime type determined
2446: # from File::MMagic if $parser = parse.
1.858 raeburn 2447: #
1.686 albertel 2448: # output: url of file in userspace, or error: <message>
2449: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2450:
1.531 albertel 2451: sub userfileupload {
1.1056.4.13 raeburn 2452: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1056.4.16 raeburn 2453: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2454: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2455: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2456: $fname=&clean_filename($fname);
1.1056.4.13 raeburn 2457: # See if there is anything left
1.257 www 2458: unless ($fname) { return 'error: no uploaded file'; }
1.1056.4.13 raeburn 2459: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2460: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2461: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2462: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2463: my $now = time;
1.1056.4.13 raeburn 2464: my $filepath;
2465: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2466: $filepath = 'tmp/helprequests/'.$now;
2467: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2468: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2469: '_'.$env{'user.domain'}.'/pending';
2470: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2471: my ($docuname,$docudom);
2472: if ($destudom) {
2473: $docudom = $destudom;
2474: } else {
2475: $docudom = $env{'user.domain'};
2476: }
2477: if ($destuname) {
2478: $docuname = $destuname;
2479: } else {
2480: $docuname = $env{'user.name'};
2481: }
2482: if (exists($env{'form.group'})) {
2483: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2484: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2485: }
2486: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2487: if ($context eq 'canceloverwrite') {
2488: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2489: if (-e $tempfile) {
2490: my @info = stat($tempfile);
2491: if ($info[9] eq $env{'form.timestamp'}) {
2492: unlink($tempfile);
2493: }
2494: }
2495: return;
1.523 raeburn 2496: }
2497: }
1.1056.4.13 raeburn 2498: # Create the directory if not present
1.741 raeburn 2499: my @parts=split(/\//,$filepath);
2500: my $fullpath = $perlvar{'lonDaemons'};
2501: for (my $i=0;$i<@parts;$i++) {
2502: $fullpath .= '/'.$parts[$i];
2503: if ((-e $fullpath)!=1) {
2504: mkdir($fullpath,0777);
2505: }
2506: }
2507: open(my $fh,'>'.$fullpath.'/'.$fname);
2508: print $fh $env{'form.'.$formname};
2509: close($fh);
1.1056.4.13 raeburn 2510: if ($context eq 'existingfile') {
2511: my @info = stat($fullpath.'/'.$fname);
2512: return ($fullpath.'/'.$fname,$info[9]);
2513: } else {
2514: return $fullpath.'/'.$fname;
2515: }
1.523 raeburn 2516: }
1.995 raeburn 2517: if ($subdir eq 'scantron') {
2518: $fname = 'scantron_orig_'.$fname;
1.1056.4.14 raeburn 2519: } else {
1.995 raeburn 2520: $fname="$subdir/$fname";
2521: }
1.1056.4.13 raeburn 2522: if ($context eq 'coursedoc') {
1.638 albertel 2523: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2524: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2525: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2526: return &finishuserfileupload($docuname,$docudom,
2527: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2528: $codebase,$thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2529: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2530: } else {
1.620 albertel 2531: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2532: return &process_coursefile('uploaddoc',$docuname,$docudom,
2533: $fname,$formname,$parser,
1.1056.4.16 raeburn 2534: $allfiles,$codebase,$mimetype);
1.481 raeburn 2535: }
1.719 banghart 2536: } elsif (defined($destuname)) {
2537: my $docuname=$destuname;
2538: my $docudom=$destudom;
1.860 raeburn 2539: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2540: $parser,$allfiles,$codebase,
1.1051 raeburn 2541: $thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2542: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2543: } else {
1.638 albertel 2544: my $docuname=$env{'user.name'};
2545: my $docudom=$env{'user.domain'};
1.714 raeburn 2546: if (exists($env{'form.group'})) {
2547: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2548: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2549: }
1.860 raeburn 2550: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2551: $parser,$allfiles,$codebase,
1.1051 raeburn 2552: $thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2553: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2554: }
1.271 www 2555: }
2556:
2557: sub finishuserfileupload {
1.860 raeburn 2558: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.16 raeburn 2559: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2560: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2561: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2562:
1.860 raeburn 2563: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2564: $file=$fname;
2565: if ($fname=~m|/|) {
2566: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2567: $path.=$fnamepath.'/';
2568: }
1.259 www 2569: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2570: my $count;
2571: for ($count=4;$count<=$#parts;$count++) {
2572: $filepath.="/$parts[$count]";
2573: if ((-e $filepath)!=1) {
2574: mkdir($filepath,0777);
2575: }
2576: }
1.984 neumanie 2577:
1.258 www 2578: # Save the file
2579: {
1.701 albertel 2580: if (!open(FH,'>'.$filepath.'/'.$file)) {
2581: &logthis('Failed to create '.$filepath.'/'.$file);
2582: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2583: return '/adm/notfound.html';
2584: }
1.1056.4.13 raeburn 2585: if ($context eq 'overwrite') {
2586: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2587: my $target = $filepath.'/'.$file;
2588: if (-e $source) {
2589: my @info = stat($source);
2590: if ($info[9] eq $env{'form.timestamp'}) {
2591: unless (&File::Copy::move($source,$target)) {
2592: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2593: return "Moving from $source failed";
2594: }
2595: } else {
2596: return "Temporary file: $source had unexpected date/time for last modification";
2597: }
2598: } else {
2599: return "Temporary file: $source missing";
2600: }
2601: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2602: &logthis('Failed to write to '.$filepath.'/'.$file);
2603: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2604: return '/adm/notfound.html';
2605: }
1.570 albertel 2606: close(FH);
1.1051 raeburn 2607: if ($resizewidth && $resizeheight) {
2608: my $mm = new File::MMagic;
2609: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2610: if ($mime_type =~ m{^image/}) {
2611: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2612: }
1.977 amueller 2613: }
1.258 www 2614: }
1.637 raeburn 2615: if ($parser eq 'parse') {
1.1024 raeburn 2616: my $mm = new File::MMagic;
1.1056.4.16 raeburn 2617: my $type = $mm->checktype_filename($filepath.'/'.$file);
2618: if ($type eq 'text/html') {
1.1024 raeburn 2619: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2620: $allfiles,$codebase);
2621: unless ($parse_result eq 'ok') {
2622: &logthis('Failed to parse '.$filepath.$file.
2623: ' for embedded media: '.$parse_result);
2624: }
1.637 raeburn 2625: }
1.1056.4.16 raeburn 2626: if (ref($mimetype)) {
2627: $$mimetype = $type;
2628: }
1.637 raeburn 2629: }
1.860 raeburn 2630: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2631: my $input = $filepath.'/'.$file;
2632: my $output = $filepath.'/'.'tn-'.$file;
2633: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2634: system("convert -sample $thumbsize $input $output");
2635: if (-e $filepath.'/'.'tn-'.$file) {
2636: $fetchthumb = 1;
2637: }
2638: }
1.858 raeburn 2639:
1.259 www 2640: # Notify homeserver to grep it
2641: #
1.984 neumanie 2642: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2643: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2644: if ($fetchresult eq 'ok') {
1.860 raeburn 2645: if ($fetchthumb) {
2646: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2647: if ($thumbresult ne 'ok') {
2648: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2649: $docuhome.': '.$thumbresult);
2650: }
2651: }
1.259 www 2652: #
1.258 www 2653: # Return the URL to it
1.494 albertel 2654: return '/uploaded/'.$path.$file;
1.263 www 2655: } else {
1.494 albertel 2656: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2657: ': '.$fetchresult);
1.263 www 2658: return '/adm/notfound.html';
1.858 raeburn 2659: }
1.493 albertel 2660: }
2661:
1.637 raeburn 2662: sub extract_embedded_items {
1.961 raeburn 2663: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2664: my @state = ();
2665: my %javafiles = (
2666: codebase => '',
2667: code => '',
2668: archive => ''
2669: );
2670: my %mediafiles = (
2671: src => '',
2672: movie => '',
2673: );
1.648 raeburn 2674: my $p;
2675: if ($content) {
2676: $p = HTML::LCParser->new($content);
2677: } else {
1.961 raeburn 2678: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2679: }
1.641 albertel 2680: while (my $t=$p->get_token()) {
1.640 albertel 2681: if ($t->[0] eq 'S') {
2682: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2683: push(@state, $tagname);
1.648 raeburn 2684: if (lc($tagname) eq 'allow') {
2685: &add_filetype($allfiles,$attr->{'src'},'src');
2686: }
1.640 albertel 2687: if (lc($tagname) eq 'img') {
2688: &add_filetype($allfiles,$attr->{'src'},'src');
2689: }
1.886 albertel 2690: if (lc($tagname) eq 'a') {
2691: &add_filetype($allfiles,$attr->{'href'},'href');
2692: }
1.645 raeburn 2693: if (lc($tagname) eq 'script') {
2694: if ($attr->{'archive'} =~ /\.jar$/i) {
2695: &add_filetype($allfiles,$attr->{'archive'},'archive');
2696: } else {
2697: &add_filetype($allfiles,$attr->{'src'},'src');
2698: }
2699: }
2700: if (lc($tagname) eq 'link') {
2701: if (lc($attr->{'rel'}) eq 'stylesheet') {
2702: &add_filetype($allfiles,$attr->{'href'},'href');
2703: }
2704: }
1.640 albertel 2705: if (lc($tagname) eq 'object' ||
2706: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2707: foreach my $item (keys(%javafiles)) {
2708: $javafiles{$item} = '';
2709: }
2710: }
2711: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2712: my $name = lc($attr->{'name'});
2713: foreach my $item (keys(%javafiles)) {
2714: if ($name eq $item) {
2715: $javafiles{$item} = $attr->{'value'};
2716: last;
2717: }
2718: }
2719: foreach my $item (keys(%mediafiles)) {
2720: if ($name eq $item) {
2721: &add_filetype($allfiles, $attr->{'value'}, 'value');
2722: last;
2723: }
2724: }
2725: }
2726: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2727: foreach my $item (keys(%javafiles)) {
2728: if ($attr->{$item}) {
2729: $javafiles{$item} = $attr->{$item};
2730: last;
2731: }
2732: }
2733: foreach my $item (keys(%mediafiles)) {
2734: if ($attr->{$item}) {
2735: &add_filetype($allfiles,$attr->{$item},$item);
2736: last;
2737: }
2738: }
2739: }
2740: } elsif ($t->[0] eq 'E') {
2741: my ($tagname) = ($t->[1]);
2742: if ($javafiles{'codebase'} ne '') {
2743: $javafiles{'codebase'} .= '/';
2744: }
2745: if (lc($tagname) eq 'applet' ||
2746: lc($tagname) eq 'object' ||
2747: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2748: ) {
2749: foreach my $item (keys(%javafiles)) {
2750: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2751: my $file=$javafiles{'codebase'}.$javafiles{$item};
2752: &add_filetype($allfiles,$file,$item);
2753: }
2754: }
2755: }
2756: pop @state;
2757: }
2758: }
1.637 raeburn 2759: return 'ok';
2760: }
2761:
1.639 albertel 2762: sub add_filetype {
2763: my ($allfiles,$file,$type)=@_;
2764: if (exists($allfiles->{$file})) {
2765: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2766: push(@{$allfiles->{$file}}, &escape($type));
2767: }
2768: } else {
2769: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2770: }
2771: }
2772:
1.493 albertel 2773: sub removeuploadedurl {
1.984 neumanie 2774: my ($url)=@_;
2775: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2776: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2777: }
2778:
2779: sub removeuserfile {
2780: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2781: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2782: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2783: if ($result eq 'ok') {
1.798 raeburn 2784: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2785: my $metafile = $fname.'.meta';
2786: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2787: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2788: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2789: my $sqlresult =
1.823 albertel 2790: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2791: 'portfolio_metadata',$group,
2792: 'delete');
1.798 raeburn 2793: }
2794: }
2795: return $result;
1.257 www 2796: }
1.15 www 2797:
1.530 albertel 2798: sub mkdiruserfile {
2799: my ($docuname,$docudom,$dir)=@_;
2800: my $home=&homeserver($docuname,$docudom);
2801: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2802: }
2803:
1.531 albertel 2804: sub renameuserfile {
2805: my ($docuname,$docudom,$old,$new)=@_;
2806: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2807: my $result = &reply("renameuserfile:$docudom:$docuname:".
2808: &escape("$old").':'.&escape("$new"),$home);
2809: if ($result eq 'ok') {
2810: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2811: my $oldmeta = $old.'.meta';
2812: my $newmeta = $new.'.meta';
2813: my $metaresult =
2814: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2815: my $url = "/uploaded/$docudom/$docuname/$old";
2816: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2817: my $sqlresult =
1.823 albertel 2818: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2819: 'portfolio_metadata',$group,
2820: 'delete');
1.798 raeburn 2821: }
2822: }
2823: return $result;
1.531 albertel 2824: }
2825:
1.14 www 2826: # ------------------------------------------------------------------------- Log
2827:
2828: sub log {
2829: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2830: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2831: }
2832:
2833: # ------------------------------------------------------------------ Course Log
1.352 www 2834: #
2835: # This routine flushes several buffers of non-mission-critical nature
2836: #
1.157 www 2837:
2838: sub flushcourselogs {
1.352 www 2839: &logthis('Flushing log buffers');
2840: #
2841: # course logs
2842: # This is a log of all transactions in a course, which can be used
2843: # for data mining purposes
2844: #
2845: # It also collects the courseid database, which lists last transaction
2846: # times and course titles for all courseids
2847: #
2848: my %courseidbuffer=();
1.921 raeburn 2849: foreach my $crsid (keys(%courselogs)) {
1.352 www 2850: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2851: &escape($courselogs{$crsid}),
2852: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2853: delete $courselogs{$crsid};
2854: } else {
2855: &logthis('Failed to flush log buffer for '.$crsid);
2856: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2857: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2858: " exceeded maximum size, deleting.</font>");
2859: delete $courselogs{$crsid};
2860: }
1.352 www 2861: }
1.920 raeburn 2862: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2863: 'description' => $coursedescrbuf{$crsid},
2864: 'inst_code' => $courseinstcodebuf{$crsid},
2865: 'type' => $coursetypebuf{$crsid},
2866: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2867: };
1.191 harris41 2868: }
1.352 www 2869: #
2870: # Write course id database (reverse lookup) to homeserver of courses
2871: # Is used in pickcourse
2872: #
1.840 albertel 2873: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2874: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2875: $courseidbuffer{$crs_home},
2876: $crs_home,'timeonly');
1.352 www 2877: }
2878: #
2879: # File accesses
2880: # Writes to the dynamic metadata of resources to get hit counts, etc.
2881: #
1.449 matthew 2882: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2883: if ($entry =~ /___count$/) {
2884: my ($dom,$name);
1.807 albertel 2885: ($dom,$name,undef)=
1.811 albertel 2886: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2887: if (! defined($dom) || $dom eq '' ||
2888: ! defined($name) || $name eq '') {
1.620 albertel 2889: my $cid = $env{'request.course.id'};
2890: $dom = $env{'request.'.$cid.'.domain'};
2891: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2892: }
1.450 matthew 2893: my $value = $accesshash{$entry};
2894: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2895: my %temphash=($url => $value);
1.449 matthew 2896: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2897: if ($result eq 'ok') {
2898: delete $accesshash{$entry};
2899: } elsif ($result eq 'unknown_cmd') {
2900: # Target server has old code running on it.
1.450 matthew 2901: my %temphash=($entry => $value);
1.449 matthew 2902: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2903: delete $accesshash{$entry};
2904: }
2905: }
2906: } else {
1.811 albertel 2907: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2908: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2909: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2910: delete $accesshash{$entry};
2911: }
1.185 www 2912: }
1.191 harris41 2913: }
1.352 www 2914: #
2915: # Roles
2916: # Reverse lookup of user roles for course faculty/staff and co-authorship
2917: #
1.800 albertel 2918: foreach my $entry (keys(%userrolehash)) {
1.351 www 2919: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2920: split(/\:/,$entry);
2921: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2922: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2923: $rudom,$runame) eq 'ok') {
2924: delete $userrolehash{$entry};
2925: }
2926: }
1.662 raeburn 2927: #
2928: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2929: #
2930: my %domrolebuffer = ();
1.1000 raeburn 2931: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2932: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2933: if ($domrolebuffer{$rudom}) {
2934: $domrolebuffer{$rudom}.='&'.&escape($entry).
2935: '='.&escape($domainrolehash{$entry});
2936: } else {
2937: $domrolebuffer{$rudom}.=&escape($entry).
2938: '='.&escape($domainrolehash{$entry});
2939: }
2940: delete $domainrolehash{$entry};
2941: }
2942: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2943: my %servers = &get_servers($dom,'library');
2944: foreach my $tryserver (keys(%servers)) {
2945: unless (&reply('domroleput:'.$dom.':'.
2946: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2947: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2948: }
1.662 raeburn 2949: }
2950: }
1.186 www 2951: $dumpcount++;
1.157 www 2952: }
2953:
2954: sub courselog {
2955: my $what=shift;
1.158 www 2956: $what=time.':'.$what;
1.620 albertel 2957: unless ($env{'request.course.id'}) { return ''; }
2958: $coursedombuf{$env{'request.course.id'}}=
2959: $env{'course.'.$env{'request.course.id'}.'.domain'};
2960: $coursenumbuf{$env{'request.course.id'}}=
2961: $env{'course.'.$env{'request.course.id'}.'.num'};
2962: $coursehombuf{$env{'request.course.id'}}=
2963: $env{'course.'.$env{'request.course.id'}.'.home'};
2964: $coursedescrbuf{$env{'request.course.id'}}=
2965: $env{'course.'.$env{'request.course.id'}.'.description'};
2966: $courseinstcodebuf{$env{'request.course.id'}}=
2967: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2968: $courseownerbuf{$env{'request.course.id'}}=
2969: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2970: $coursetypebuf{$env{'request.course.id'}}=
2971: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2972: if (defined $courselogs{$env{'request.course.id'}}) {
2973: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2974: } else {
1.620 albertel 2975: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2976: }
1.620 albertel 2977: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2978: &flushcourselogs();
2979: }
1.158 www 2980: }
2981:
2982: sub courseacclog {
2983: my $fnsymb=shift;
1.620 albertel 2984: unless ($env{'request.course.id'}) { return ''; }
2985: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2986: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2987: $what.=':POST';
1.583 matthew 2988: # FIXME: Probably ought to escape things....
1.800 albertel 2989: foreach my $key (keys(%env)) {
2990: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2991: my $formitem = $1;
2992: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2993: $what.=':'.$formitem.'='.$env{$key};
2994: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2995: $what.=':'.$formitem.'='.$env{$key};
2996: }
1.158 www 2997: }
1.191 harris41 2998: }
1.583 matthew 2999: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3000: # FIXME: We should not be depending on a form parameter that someone
3001: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3002: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3003: $what.= ':POST';
3004: # FIXME: Probably ought to escape things....
3005: foreach my $element ('courseexp','crsfulltext','crsrelated',
3006: 'crsdiscuss') {
1.620 albertel 3007: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3008: }
3009: }
1.158 www 3010: }
3011: &courselog($what);
1.149 www 3012: }
3013:
1.185 www 3014: sub countacc {
3015: my $url=&declutter(shift);
1.458 matthew 3016: return if (! defined($url) || $url eq '');
1.620 albertel 3017: unless ($env{'request.course.id'}) { return ''; }
3018: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 3019: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3020: $accesshash{$key}++;
1.185 www 3021: }
1.349 www 3022:
1.361 www 3023: sub linklog {
3024: my ($from,$to)=@_;
3025: $from=&declutter($from);
3026: $to=&declutter($to);
3027: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3028: $accesshash{$to.'___'.$from.'___goto'}=1;
3029: }
3030:
1.349 www 3031: sub userrolelog {
3032: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3033: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3034: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3035: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3036: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3037: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3038: $userrolehash
3039: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3040: =$tend.':'.$tstart;
1.662 raeburn 3041: }
1.898 albertel 3042: if (($env{'request.role'} =~ /dc\./) &&
3043: (($trole=~/^au/) || ($trole=~/^in/) ||
3044: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3045: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3046: ($trole=~/^co/))) {
1.898 albertel 3047: $userrolehash
3048: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3049: =$tend.':'.$tstart;
3050: }
1.662 raeburn 3051: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3052: ($trole=~/^li/) || ($trole=~/^li/) ||
3053: ($trole=~/^au/) || ($trole=~/^dg/) ||
3054: ($trole=~/^sc/)) {
3055: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3056: $domainrolehash
3057: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3058: = $tend.':'.$tstart;
3059: }
1.351 www 3060: }
3061:
1.957 raeburn 3062: sub courserolelog {
3063: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3064: if (($trole eq 'cc') || ($trole eq 'in') ||
3065: ($trole eq 'ep') || ($trole eq 'ad') ||
3066: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3067: ($trole=~/^cr/) || ($trole eq 'gr') ||
3068: ($trole eq 'co')) {
1.957 raeburn 3069: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3070: my $cdom = $1;
3071: my $cnum = $2;
3072: my $sec = $3;
3073: my $namespace = 'rolelog';
3074: my %storehash = (
3075: role => $trole,
3076: start => $tstart,
3077: end => $tend,
3078: selfenroll => $selfenroll,
3079: context => $context,
3080: );
3081: if ($trole eq 'gr') {
3082: $namespace = 'groupslog';
3083: $storehash{'group'} = $sec;
3084: } else {
3085: $storehash{'section'} = $sec;
3086: }
3087: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3088: if (($trole ne 'st') || ($sec ne '')) {
3089: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3090: }
1.957 raeburn 3091: }
3092: }
3093: return;
3094: }
3095:
1.351 www 3096: sub get_course_adv_roles {
1.948 raeburn 3097: my ($cid,$codes) = @_;
1.620 albertel 3098: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3099: my %coursehash=&coursedescription($cid);
1.988 raeburn 3100: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3101: my %nothide=();
1.800 albertel 3102: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3103: if ($user !~ /:/) {
3104: $nothide{join(':',split(/[\@]/,$user))}=1;
3105: } else {
3106: $nothide{$user}=1;
3107: }
1.470 www 3108: }
1.351 www 3109: my %returnhash=();
3110: my %dumphash=
3111: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3112: my $now=time;
1.997 raeburn 3113: my %privileged;
1.1000 raeburn 3114: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3115: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3116: if (($tstart) && ($tstart<0)) { next; }
3117: if (($tend) && ($tend<$now)) { next; }
3118: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3119: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3120: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3121: unless (ref($privileged{$domain}) eq 'HASH') {
3122: my %dompersonnel =
1.998 raeburn 3123: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3124: $privileged{$domain} = {};
3125: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3126: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3127: foreach my $user (keys(%{$dompersonnel{$server}})) {
3128: my ($trole,$uname,$udom) = split(/:/,$user);
3129: $privileged{$udom}{$uname} = 1;
3130: }
3131: }
3132: }
3133: }
3134: if ((exists($privileged{$domain}{$username})) &&
3135: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3136: if ($role eq 'cr') { next; }
1.948 raeburn 3137: if ($codes) {
3138: if ($section) { $role .= ':'.$section; }
3139: if ($returnhash{$role}) {
3140: $returnhash{$role}.=','.$username.':'.$domain;
3141: } else {
3142: $returnhash{$role}=$username.':'.$domain;
3143: }
1.351 www 3144: } else {
1.988 raeburn 3145: my $key=&plaintext($role,$crstype);
1.973 bisitz 3146: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3147: if ($returnhash{$key}) {
3148: $returnhash{$key}.=','.$username.':'.$domain;
3149: } else {
3150: $returnhash{$key}=$username.':'.$domain;
3151: }
1.351 www 3152: }
1.948 raeburn 3153: }
1.400 www 3154: return %returnhash;
3155: }
3156:
3157: sub get_my_roles {
1.937 raeburn 3158: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3159: unless (defined($uname)) { $uname=$env{'user.name'}; }
3160: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3161: my (%dumphash,%nothide);
1.858 raeburn 3162: if ($context eq 'userroles') {
1.1056.4.10 raeburn 3163: my $extra = &freeze_escape({'skipcheck' => 1});
3164: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3165: } else {
3166: %dumphash=
1.400 www 3167: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3168: if ($hidepriv) {
3169: my %coursehash=&coursedescription($udom.'_'.$uname);
3170: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3171: if ($user !~ /:/) {
3172: $nothide{join(':',split(/[\@]/,$user))} = 1;
3173: } else {
3174: $nothide{$user} = 1;
3175: }
3176: }
3177: }
1.858 raeburn 3178: }
1.400 www 3179: my %returnhash=();
3180: my $now=time;
1.999 raeburn 3181: my %privileged;
1.800 albertel 3182: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3183: my ($role,$tend,$tstart);
3184: if ($context eq 'userroles') {
3185: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3186: } else {
3187: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3188: }
1.400 www 3189: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3190: my $status = 'active';
1.939 raeburn 3191: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3192: $status = 'previous';
3193: }
3194: if (($tstart) && ($now<$tstart)) {
3195: $status = 'future';
3196: }
3197: if (ref($types) eq 'ARRAY') {
3198: if (!grep(/^\Q$status\E$/,@{$types})) {
3199: next;
3200: }
3201: } else {
3202: if ($status ne 'active') {
3203: next;
3204: }
3205: }
1.867 raeburn 3206: my ($rolecode,$username,$domain,$section,$area);
3207: if ($context eq 'userroles') {
3208: ($area,$rolecode) = split(/_/,$entry);
3209: (undef,$domain,$username,$section) = split(/\//,$area);
3210: } else {
3211: ($role,$username,$domain,$section) = split(/\:/,$entry);
3212: }
1.832 raeburn 3213: if (ref($roledoms) eq 'ARRAY') {
3214: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3215: next;
3216: }
3217: }
3218: if (ref($roles) eq 'ARRAY') {
3219: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3220: if ($role =~ /^cr\//) {
3221: if (!grep(/^cr$/,@{$roles})) {
3222: next;
3223: }
3224: } else {
3225: next;
3226: }
1.832 raeburn 3227: }
1.867 raeburn 3228: }
1.937 raeburn 3229: if ($hidepriv) {
1.999 raeburn 3230: if ($context eq 'userroles') {
3231: if ((&privileged($username,$domain)) &&
3232: (!$nothide{$username.':'.$domain})) {
3233: next;
3234: }
3235: } else {
3236: unless (ref($privileged{$domain}) eq 'HASH') {
3237: my %dompersonnel =
3238: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3239: $privileged{$domain} = {};
3240: if (keys(%dompersonnel)) {
3241: foreach my $server (keys(%dompersonnel)) {
3242: if (ref($dompersonnel{$server}) eq 'HASH') {
3243: foreach my $user (keys(%{$dompersonnel{$server}})) {
3244: my ($trole,$uname,$udom) = split(/:/,$user);
3245: $privileged{$udom}{$uname} = $trole;
3246: }
3247: }
3248: }
3249: }
3250: }
3251: if (exists($privileged{$domain}{$username})) {
3252: if (!$nothide{$username.':'.$domain}) {
3253: next;
3254: }
3255: }
1.937 raeburn 3256: }
3257: }
1.933 raeburn 3258: if ($withsec) {
3259: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3260: $tstart.':'.$tend;
3261: } else {
3262: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3263: }
1.832 raeburn 3264: }
1.373 www 3265: return %returnhash;
1.399 www 3266: }
3267:
3268: # ----------------------------------------------------- Frontpage Announcements
3269: #
3270: #
3271:
3272: sub postannounce {
3273: my ($server,$text)=@_;
1.844 albertel 3274: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3275: unless ($text=~/\w/) { $text=''; }
3276: return &reply('setannounce:'.&escape($text),$server);
3277: }
3278:
3279: sub getannounce {
1.448 albertel 3280:
3281: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3282: my $announcement='';
1.800 albertel 3283: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3284: close($fh);
1.399 www 3285: if ($announcement=~/\w/) {
3286: return
3287: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3288: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3289: } else {
3290: return '';
3291: }
3292: } else {
3293: return '';
3294: }
1.351 www 3295: }
1.353 www 3296:
3297: # ---------------------------------------------------------- Course ID routines
3298: # Deal with domain's nohist_courseid.db files
3299: #
3300:
3301: sub courseidput {
1.921 raeburn 3302: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3303: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3304: my $outcome;
3305: if ($caller eq 'timeonly') {
3306: my $cids = '';
3307: foreach my $item (keys(%$storehash)) {
3308: $cids.=&escape($item).'&';
3309: }
3310: $cids=~s/\&$//;
3311: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3312: $coursehome);
3313: } else {
3314: my $items = '';
3315: foreach my $item (keys(%$storehash)) {
3316: $items.= &escape($item).'='.
3317: &freeze_escape($$storehash{$item}).'&';
3318: }
3319: $items=~s/\&$//;
3320: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3321: $coursehome);
1.918 raeburn 3322: }
3323: if ($outcome eq 'unknown_cmd') {
3324: my $what;
3325: foreach my $cid (keys(%$storehash)) {
3326: $what .= &escape($cid).'=';
1.921 raeburn 3327: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3328: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3329: }
3330: $what =~ s/\:$/&/;
3331: }
3332: $what =~ s/\&$//;
3333: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3334: } else {
3335: return $outcome;
3336: }
1.353 www 3337: }
3338:
3339: sub courseiddump {
1.921 raeburn 3340: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3341: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3342: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3 raeburn 3343: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3344: my $as_hash = 1;
3345: my %returnhash;
3346: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3347: my %libserv = &all_library();
3348: foreach my $tryserver (keys(%libserv)) {
3349: if ( ( $hostidflag == 1
3350: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3351: || (!defined($hostidflag)) ) {
3352:
1.918 raeburn 3353: if (($domfilter eq '') ||
3354: (&host_domain($tryserver) eq $domfilter)) {
3355: my $rep =
3356: &reply('courseiddump:'.&host_domain($tryserver).':'.
3357: $sincefilter.':'.&escape($descfilter).':'.
3358: &escape($instcodefilter).':'.&escape($ownerfilter).
3359: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3360: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3361: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3362: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3363: &escape($cc_clone).':'.$cloneonly.':'.
3364: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3 raeburn 3365: &escape($creationcontext).':'.$domcloner,
3366: $tryserver);
1.918 raeburn 3367: my @pairs=split(/\&/,$rep);
3368: foreach my $item (@pairs) {
3369: my ($key,$value)=split(/\=/,$item,2);
3370: $key = &unescape($key);
3371: next if ($key =~ /^error: 2 /);
3372: my $result = &thaw_unescape($value);
3373: if (ref($result) eq 'HASH') {
3374: $returnhash{$key}=$result;
3375: } else {
1.921 raeburn 3376: my @responses = split(/:/,$value);
3377: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3378: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3379: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3380: }
1.1008 raeburn 3381: }
1.353 www 3382: }
3383: }
3384: }
3385: }
3386: return %returnhash;
3387: }
3388:
1.1055 raeburn 3389: sub courselastaccess {
3390: my ($cdom,$cnum,$hostidref) = @_;
3391: my %returnhash;
3392: if ($cdom && $cnum) {
3393: my $chome = &homeserver($cnum,$cdom);
3394: if ($chome ne 'no_host') {
3395: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3396: &extract_lastaccess(\%returnhash,$rep);
3397: }
3398: } else {
3399: if (!$cdom) { $cdom=''; }
3400: my %libserv = &all_library();
3401: foreach my $tryserver (keys(%libserv)) {
3402: if (ref($hostidref) eq 'ARRAY') {
3403: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3404: }
3405: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3406: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3407: &extract_lastaccess(\%returnhash,$rep);
3408: }
3409: }
3410: }
3411: return %returnhash;
3412: }
3413:
3414: sub extract_lastaccess {
3415: my ($returnhash,$rep) = @_;
3416: if (ref($returnhash) eq 'HASH') {
3417: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3418: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3419: $rep eq '') {
3420: my @pairs=split(/\&/,$rep);
3421: foreach my $item (@pairs) {
3422: my ($key,$value)=split(/\=/,$item,2);
3423: $key = &unescape($key);
3424: next if ($key =~ /^error: 2 /);
3425: $returnhash->{$key} = &thaw_unescape($value);
3426: }
3427: }
3428: }
3429: return;
3430: }
3431:
1.658 raeburn 3432: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3433:
3434: sub dcmailput {
1.685 raeburn 3435: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3436: my $status = &Apache::lonnet::critical(
1.740 www 3437: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3438: &escape($message),$server);
1.662 raeburn 3439: return $status;
3440: }
3441:
1.658 raeburn 3442: sub dcmaildump {
3443: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3444: my %returnhash=();
1.846 albertel 3445:
3446: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3447: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3448: &escape($enddate).':';
3449: my @esc_senders=map { &escape($_)} @$senders;
3450: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3451: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3452: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3453: if (($key) && ($value)) {
3454: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3455: }
3456: }
3457: }
3458: return %returnhash;
3459: }
1.662 raeburn 3460: # ---------------------------------------------------------- Domain roles
3461:
3462: sub get_domain_roles {
3463: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3464: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3465: $startdate = '.';
3466: }
1.1018 raeburn 3467: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3468: $enddate = '.';
3469: }
1.922 raeburn 3470: my $rolelist;
3471: if (ref($roles) eq 'ARRAY') {
3472: $rolelist = join(':',@{$roles});
3473: }
1.662 raeburn 3474: my %personnel = ();
1.841 albertel 3475:
3476: my %servers = &get_servers($dom,'library');
3477: foreach my $tryserver (keys(%servers)) {
3478: %{$personnel{$tryserver}}=();
3479: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3480: &escape($startdate).':'.
3481: &escape($enddate).':'.
3482: &escape($rolelist), $tryserver))) {
3483: my ($key,$value) = split(/\=/,$line,2);
3484: if (($key) && ($value)) {
3485: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3486: }
3487: }
1.662 raeburn 3488: }
3489: return %personnel;
3490: }
1.658 raeburn 3491:
1.149 www 3492: # ----------------------------------------------------------- Check out an item
3493:
1.504 albertel 3494: sub get_first_access {
3495: my ($type,$argsymb)=@_;
1.790 albertel 3496: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3497: if ($argsymb) { $symb=$argsymb; }
3498: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3499: if ($type eq 'course') {
3500: $res='course';
3501: } elsif ($type eq 'map') {
1.588 albertel 3502: $res=&symbread($map);
3503: } else {
3504: $res=$symb;
3505: }
3506: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3507: return $times{"$courseid\0$res"};
1.504 albertel 3508: }
3509:
3510: sub set_first_access {
3511: my ($type)=@_;
1.790 albertel 3512: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3513: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3514: if ($type eq 'course') {
3515: $res='course';
3516: } elsif ($type eq 'map') {
1.588 albertel 3517: $res=&symbread($map);
3518: } else {
3519: $res=$symb;
3520: }
3521: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3522: if (!$firstaccess) {
1.588 albertel 3523: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3524: }
3525: return 'already_set';
1.504 albertel 3526: }
3527:
1.149 www 3528: sub checkout {
3529: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3530: my $now=time;
3531: my $lonhost=$perlvar{'lonHostID'};
3532: my $infostr=&escape(
1.234 www 3533: 'CHECKOUTTOKEN&'.
1.149 www 3534: $tuname.'&'.
3535: $tudom.'&'.
3536: $tcrsid.'&'.
3537: $symb.'&'.
3538: $now.'&'.$ENV{'REMOTE_ADDR'});
3539: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3540: if ($token=~/^error\:/) {
1.672 albertel 3541: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3542: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3543: "</font>");
3544: return '';
3545: }
3546:
1.149 www 3547: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3548: $token=~tr/a-z/A-Z/;
3549:
1.153 www 3550: my %infohash=('resource.0.outtoken' => $token,
3551: 'resource.0.checkouttime' => $now,
3552: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3553:
3554: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3555: return '';
1.151 www 3556: } else {
1.672 albertel 3557: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3558: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3559: "</font>");
1.149 www 3560: }
3561:
3562: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3563: &escape('Checkout '.$infostr.' - '.
3564: $token)) ne 'ok') {
3565: return '';
1.151 www 3566: } else {
1.672 albertel 3567: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3568: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3569: "</font>");
1.149 www 3570: }
1.151 www 3571: return $token;
1.149 www 3572: }
3573:
3574: # ------------------------------------------------------------ Check in an item
3575:
3576: sub checkin {
3577: my $token=shift;
1.150 www 3578: my $now=time;
3579: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3580: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3581: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3582: $dtoken=~s/\W/\_/g;
1.234 www 3583: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3584: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3585:
1.154 www 3586: unless (($tuname) && ($tudom)) {
3587: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3588: return '';
3589: }
3590:
3591: unless (&allowed('mgr',$tcrsid)) {
3592: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3593: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3594: return '';
3595: }
3596:
1.153 www 3597: my %infohash=('resource.0.intoken' => $token,
3598: 'resource.0.checkintime' => $now,
3599: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3600:
3601: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3602: return '';
3603: }
3604:
3605: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3606: &escape('Checkin - '.$token)) ne 'ok') {
3607: return '';
3608: }
3609:
3610: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3611: }
3612:
3613: # --------------------------------------------- Set Expire Date for Spreadsheet
3614:
3615: sub expirespread {
3616: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3617: my $cid=$env{'request.course.id'};
1.110 www 3618: if ($cid) {
3619: my $now=time;
3620: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3621: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3622: $env{'course.'.$cid.'.num'}.
1.110 www 3623: ':nohist_expirationdates:'.
3624: &escape($key).'='.$now,
1.620 albertel 3625: $env{'course.'.$cid.'.home'})
1.110 www 3626: }
3627: return 'ok';
1.14 www 3628: }
3629:
1.109 www 3630: # ----------------------------------------------------- Devalidate Spreadsheets
3631:
3632: sub devalidate {
1.325 www 3633: my ($symb,$uname,$udom)=@_;
1.620 albertel 3634: my $cid=$env{'request.course.id'};
1.109 www 3635: if ($cid) {
1.391 matthew 3636: # delete the stored spreadsheets for
3637: # - the student level sheet of this user in course's homespace
3638: # - the assessment level sheet for this resource
3639: # for this user in user's homespace
1.553 albertel 3640: # - current conditional state info
1.325 www 3641: my $key=$uname.':'.$udom.':';
1.109 www 3642: my $status=
1.299 matthew 3643: &del('nohist_calculatedsheets',
1.391 matthew 3644: [$key.'studentcalc:'],
1.620 albertel 3645: $env{'course.'.$cid.'.domain'},
3646: $env{'course.'.$cid.'.num'})
1.133 albertel 3647: .' '.
3648: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3649: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3650: unless ($status eq 'ok ok') {
3651: &logthis('Could not devalidate spreadsheet '.
1.325 www 3652: $uname.' at '.$udom.' for '.
1.109 www 3653: $symb.': '.$status);
1.133 albertel 3654: }
1.553 albertel 3655: &delenv('user.state.'.$cid);
1.109 www 3656: }
3657: }
3658:
1.265 albertel 3659: sub get_scalar {
3660: my ($string,$end) = @_;
3661: my $value;
3662: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3663: $value = $1;
3664: } elsif ($$string =~ s/^([^&]*?)&//) {
3665: $value = $1;
3666: }
3667: return &unescape($value);
3668: }
3669:
3670: sub array2str {
3671: my (@array) = @_;
3672: my $result=&arrayref2str(\@array);
3673: $result=~s/^__ARRAY_REF__//;
3674: $result=~s/__END_ARRAY_REF__$//;
3675: return $result;
3676: }
3677:
1.204 albertel 3678: sub arrayref2str {
3679: my ($arrayref) = @_;
1.265 albertel 3680: my $result='__ARRAY_REF__';
1.204 albertel 3681: foreach my $elem (@$arrayref) {
1.265 albertel 3682: if(ref($elem) eq 'ARRAY') {
3683: $result.=&arrayref2str($elem).'&';
3684: } elsif(ref($elem) eq 'HASH') {
3685: $result.=&hashref2str($elem).'&';
3686: } elsif(ref($elem)) {
3687: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3688: } else {
3689: $result.=&escape($elem).'&';
3690: }
3691: }
3692: $result=~s/\&$//;
1.265 albertel 3693: $result .= '__END_ARRAY_REF__';
1.204 albertel 3694: return $result;
3695: }
3696:
1.168 albertel 3697: sub hash2str {
1.204 albertel 3698: my (%hash) = @_;
3699: my $result=&hashref2str(\%hash);
1.265 albertel 3700: $result=~s/^__HASH_REF__//;
3701: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3702: return $result;
3703: }
3704:
3705: sub hashref2str {
3706: my ($hashref)=@_;
1.265 albertel 3707: my $result='__HASH_REF__';
1.800 albertel 3708: foreach my $key (sort(keys(%$hashref))) {
3709: if (ref($key) eq 'ARRAY') {
3710: $result.=&arrayref2str($key).'=';
3711: } elsif (ref($key) eq 'HASH') {
3712: $result.=&hashref2str($key).'=';
3713: } elsif (ref($key)) {
1.265 albertel 3714: $result.='=';
1.800 albertel 3715: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3716: } else {
1.1056.4.32! raeburn 3717: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3718: }
3719:
1.800 albertel 3720: if(ref($hashref->{$key}) eq 'ARRAY') {
3721: $result.=&arrayref2str($hashref->{$key}).'&';
3722: } elsif(ref($hashref->{$key}) eq 'HASH') {
3723: $result.=&hashref2str($hashref->{$key}).'&';
3724: } elsif(ref($hashref->{$key})) {
1.265 albertel 3725: $result.='&';
1.800 albertel 3726: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3727: } else {
1.800 albertel 3728: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3729: }
3730: }
1.168 albertel 3731: $result=~s/\&$//;
1.265 albertel 3732: $result .= '__END_HASH_REF__';
1.168 albertel 3733: return $result;
3734: }
3735:
3736: sub str2hash {
1.265 albertel 3737: my ($string)=@_;
3738: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3739: return %$hash;
3740: }
3741:
3742: sub str2hashref {
1.168 albertel 3743: my ($string) = @_;
1.265 albertel 3744:
3745: my %hash;
3746:
3747: if($string !~ /^__HASH_REF__/) {
3748: if (! ($string eq '' || !defined($string))) {
3749: $hash{'error'}='Not hash reference';
3750: }
3751: return (\%hash, $string);
3752: }
3753:
3754: $string =~ s/^__HASH_REF__//;
3755:
3756: while($string !~ /^__END_HASH_REF__/) {
3757: #key
3758: my $key='';
3759: if($string =~ /^__HASH_REF__/) {
3760: ($key, $string)=&str2hashref($string);
3761: if(defined($key->{'error'})) {
3762: $hash{'error'}='Bad data';
3763: return (\%hash, $string);
3764: }
3765: } elsif($string =~ /^__ARRAY_REF__/) {
3766: ($key, $string)=&str2arrayref($string);
3767: if($key->[0] eq 'Array reference error') {
3768: $hash{'error'}='Bad data';
3769: return (\%hash, $string);
3770: }
3771: } else {
3772: $string =~ s/^(.*?)=//;
1.267 albertel 3773: $key=&unescape($1);
1.265 albertel 3774: }
3775: $string =~ s/^=//;
3776:
3777: #value
3778: my $value='';
3779: if($string =~ /^__HASH_REF__/) {
3780: ($value, $string)=&str2hashref($string);
3781: if(defined($value->{'error'})) {
3782: $hash{'error'}='Bad data';
3783: return (\%hash, $string);
3784: }
3785: } elsif($string =~ /^__ARRAY_REF__/) {
3786: ($value, $string)=&str2arrayref($string);
3787: if($value->[0] eq 'Array reference error') {
3788: $hash{'error'}='Bad data';
3789: return (\%hash, $string);
3790: }
3791: } else {
3792: $value=&get_scalar(\$string,'__END_HASH_REF__');
3793: }
3794: $string =~ s/^&//;
3795:
3796: $hash{$key}=$value;
1.204 albertel 3797: }
1.265 albertel 3798:
3799: $string =~ s/^__END_HASH_REF__//;
3800:
3801: return (\%hash, $string);
1.204 albertel 3802: }
3803:
3804: sub str2array {
1.265 albertel 3805: my ($string)=@_;
3806: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3807: return @$array;
3808: }
3809:
3810: sub str2arrayref {
1.204 albertel 3811: my ($string) = @_;
1.265 albertel 3812: my @array;
3813:
3814: if($string !~ /^__ARRAY_REF__/) {
3815: if (! ($string eq '' || !defined($string))) {
3816: $array[0]='Array reference error';
3817: }
3818: return (\@array, $string);
3819: }
3820:
3821: $string =~ s/^__ARRAY_REF__//;
3822:
3823: while($string !~ /^__END_ARRAY_REF__/) {
3824: my $value='';
3825: if($string =~ /^__HASH_REF__/) {
3826: ($value, $string)=&str2hashref($string);
3827: if(defined($value->{'error'})) {
3828: $array[0] ='Array reference error';
3829: return (\@array, $string);
3830: }
3831: } elsif($string =~ /^__ARRAY_REF__/) {
3832: ($value, $string)=&str2arrayref($string);
3833: if($value->[0] eq 'Array reference error') {
3834: $array[0] ='Array reference error';
3835: return (\@array, $string);
3836: }
3837: } else {
3838: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3839: }
3840: $string =~ s/^&//;
3841:
3842: push(@array, $value);
1.191 harris41 3843: }
1.265 albertel 3844:
3845: $string =~ s/^__END_ARRAY_REF__//;
3846:
3847: return (\@array, $string);
1.168 albertel 3848: }
3849:
1.167 albertel 3850: # -------------------------------------------------------------------Temp Store
3851:
1.168 albertel 3852: sub tmpreset {
3853: my ($symb,$namespace,$domain,$stuname) = @_;
3854: if (!$symb) {
3855: $symb=&symbread();
1.620 albertel 3856: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3857: }
3858: $symb=escape($symb);
3859:
1.620 albertel 3860: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3861: $namespace=~s/\//\_/g;
3862: $namespace=~s/\W//g;
3863:
1.620 albertel 3864: if (!$domain) { $domain=$env{'user.domain'}; }
3865: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3866: if ($domain eq 'public' && $stuname eq 'public') {
3867: $stuname=$ENV{'REMOTE_ADDR'};
3868: }
1.168 albertel 3869: my $path=$perlvar{'lonDaemons'}.'/tmp';
3870: my %hash;
3871: if (tie(%hash,'GDBM_File',
3872: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3873: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3874: foreach my $key (keys(%hash)) {
1.180 albertel 3875: if ($key=~ /:$symb/) {
1.168 albertel 3876: delete($hash{$key});
3877: }
3878: }
3879: }
3880: }
3881:
1.167 albertel 3882: sub tmpstore {
1.168 albertel 3883: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3884:
3885: if (!$symb) {
3886: $symb=&symbread();
1.620 albertel 3887: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3888: }
3889: $symb=escape($symb);
3890:
3891: if (!$namespace) {
3892: # I don't think we would ever want to store this for a course.
3893: # it seems this will only be used if we don't have a course.
1.620 albertel 3894: #$namespace=$env{'request.course.id'};
1.168 albertel 3895: #if (!$namespace) {
1.620 albertel 3896: $namespace=$env{'request.state'};
1.168 albertel 3897: #}
3898: }
3899: $namespace=~s/\//\_/g;
3900: $namespace=~s/\W//g;
1.620 albertel 3901: if (!$domain) { $domain=$env{'user.domain'}; }
3902: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3903: if ($domain eq 'public' && $stuname eq 'public') {
3904: $stuname=$ENV{'REMOTE_ADDR'};
3905: }
1.168 albertel 3906: my $now=time;
3907: my %hash;
3908: my $path=$perlvar{'lonDaemons'}.'/tmp';
3909: if (tie(%hash,'GDBM_File',
3910: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3911: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3912: $hash{"version:$symb"}++;
3913: my $version=$hash{"version:$symb"};
3914: my $allkeys='';
3915: foreach my $key (keys(%$storehash)) {
3916: $allkeys.=$key.':';
1.591 albertel 3917: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3918: }
3919: $hash{"$version:$symb:timestamp"}=$now;
3920: $allkeys.='timestamp';
3921: $hash{"$version:keys:$symb"}=$allkeys;
3922: if (untie(%hash)) {
3923: return 'ok';
3924: } else {
3925: return "error:$!";
3926: }
3927: } else {
3928: return "error:$!";
3929: }
3930: }
1.167 albertel 3931:
1.168 albertel 3932: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3933:
1.168 albertel 3934: sub tmprestore {
3935: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3936:
1.168 albertel 3937: if (!$symb) {
3938: $symb=&symbread();
1.620 albertel 3939: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3940: }
3941: $symb=escape($symb);
3942:
1.620 albertel 3943: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3944:
1.620 albertel 3945: if (!$domain) { $domain=$env{'user.domain'}; }
3946: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3947: if ($domain eq 'public' && $stuname eq 'public') {
3948: $stuname=$ENV{'REMOTE_ADDR'};
3949: }
1.168 albertel 3950: my %returnhash;
3951: $namespace=~s/\//\_/g;
3952: $namespace=~s/\W//g;
3953: my %hash;
3954: my $path=$perlvar{'lonDaemons'}.'/tmp';
3955: if (tie(%hash,'GDBM_File',
3956: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3957: &GDBM_READER(),0640)) {
1.168 albertel 3958: my $version=$hash{"version:$symb"};
3959: $returnhash{'version'}=$version;
3960: my $scope;
3961: for ($scope=1;$scope<=$version;$scope++) {
3962: my $vkeys=$hash{"$scope:keys:$symb"};
3963: my @keys=split(/:/,$vkeys);
3964: my $key;
3965: $returnhash{"$scope:keys"}=$vkeys;
3966: foreach $key (@keys) {
1.591 albertel 3967: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3968: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3969: }
3970: }
1.168 albertel 3971: if (!(untie(%hash))) {
3972: return "error:$!";
3973: }
3974: } else {
3975: return "error:$!";
3976: }
3977: return %returnhash;
1.167 albertel 3978: }
3979:
1.9 www 3980: # ----------------------------------------------------------------------- Store
3981:
3982: sub store {
1.124 www 3983: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3984: my $home='';
3985:
1.168 albertel 3986: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3987:
1.213 www 3988: $symb=&symbclean($symb);
1.122 albertel 3989: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3990:
1.620 albertel 3991: if (!$domain) { $domain=$env{'user.domain'}; }
3992: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3993:
3994: &devalidate($symb,$stuname,$domain);
1.109 www 3995:
3996: $symb=escape($symb);
1.187 www 3997: if (!$namespace) {
1.620 albertel 3998: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3999: return '';
4000: }
4001: }
1.620 albertel 4002: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4003:
4004: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4005: $$storehash{'host'}=$perlvar{'lonHostID'};
4006:
1.12 www 4007: my $namevalue='';
1.800 albertel 4008: foreach my $key (keys(%$storehash)) {
4009: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4010: }
1.12 www 4011: $namevalue=~s/\&$//;
1.187 www 4012: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4013: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4014: }
4015:
1.47 www 4016: # -------------------------------------------------------------- Critical Store
4017:
4018: sub cstore {
1.124 www 4019: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4020: my $home='';
4021:
1.168 albertel 4022: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4023:
1.213 www 4024: $symb=&symbclean($symb);
1.122 albertel 4025: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4026:
1.620 albertel 4027: if (!$domain) { $domain=$env{'user.domain'}; }
4028: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4029:
4030: &devalidate($symb,$stuname,$domain);
1.109 www 4031:
4032: $symb=escape($symb);
1.187 www 4033: if (!$namespace) {
1.620 albertel 4034: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4035: return '';
4036: }
4037: }
1.620 albertel 4038: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4039:
4040: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4041: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4042:
1.47 www 4043: my $namevalue='';
1.800 albertel 4044: foreach my $key (keys(%$storehash)) {
4045: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4046: }
1.47 www 4047: $namevalue=~s/\&$//;
1.187 www 4048: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4049: return critical
4050: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4051: }
4052:
1.9 www 4053: # --------------------------------------------------------------------- Restore
4054:
4055: sub restore {
1.124 www 4056: my ($symb,$namespace,$domain,$stuname) = @_;
4057: my $home='';
4058:
1.168 albertel 4059: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4060:
1.122 albertel 4061: if (!$symb) {
4062: unless ($symb=escape(&symbread())) { return ''; }
4063: } else {
1.213 www 4064: $symb=&escape(&symbclean($symb));
1.122 albertel 4065: }
1.188 www 4066: if (!$namespace) {
1.620 albertel 4067: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4068: return '';
4069: }
4070: }
1.620 albertel 4071: if (!$domain) { $domain=$env{'user.domain'}; }
4072: if (!$stuname) { $stuname=$env{'user.name'}; }
4073: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4074: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4075:
1.12 www 4076: my %returnhash=();
1.800 albertel 4077: foreach my $line (split(/\&/,$answer)) {
4078: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4079: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4080: }
1.75 www 4081: my $version;
4082: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4083: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4084: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4085: }
1.75 www 4086: }
1.13 www 4087: return %returnhash;
1.34 www 4088: }
4089:
4090: # ---------------------------------------------------------- Course Description
4091:
4092: sub coursedescription {
1.731 albertel 4093: my ($courseid,$args)=@_;
1.34 www 4094: $courseid=~s/^\///;
1.49 www 4095: $courseid=~s/\_/\//g;
1.34 www 4096: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4097: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4098: my $normalid=$cdomain.'_'.$cnum;
4099: # need to always cache even if we get errors otherwise we keep
4100: # trying and trying and trying to get the course description.
4101: my %envhash=();
4102: my %returnhash=();
1.731 albertel 4103:
4104: my $expiretime=600;
4105: if ($env{'request.course.id'} eq $normalid) {
4106: $expiretime=120;
4107: }
4108:
4109: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4110: if (!$args->{'freshen_cache'}
4111: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4112: foreach my $key (keys(%env)) {
4113: next if ($key !~ /^\Q$prefix\E(.*)/);
4114: my ($setting) = $1;
4115: $returnhash{$setting} = $env{$key};
4116: }
4117: return %returnhash;
4118: }
4119:
4120: # get the data agin
4121: if (!$args->{'one_time'}) {
4122: $envhash{'course.'.$normalid.'.last_cache'}=time;
4123: }
1.811 albertel 4124:
1.34 www 4125: if ($chome ne 'no_host') {
1.302 albertel 4126: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4127: if (!exists($returnhash{'con_lost'})) {
4128: $returnhash{'home'}= $chome;
4129: $returnhash{'domain'} = $cdomain;
4130: $returnhash{'num'} = $cnum;
1.741 raeburn 4131: if (!defined($returnhash{'type'})) {
4132: $returnhash{'type'} = 'Course';
4133: }
1.130 albertel 4134: while (my ($name,$value) = each %returnhash) {
1.53 www 4135: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4136: }
1.270 www 4137: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4138: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4139: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4140: $envhash{'course.'.$normalid.'.home'}=$chome;
4141: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4142: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4143: }
4144: }
1.731 albertel 4145: if (!$args->{'one_time'}) {
1.949 raeburn 4146: &appenv(\%envhash);
1.731 albertel 4147: }
1.302 albertel 4148: return %returnhash;
1.461 www 4149: }
4150:
1.1056.4.5 raeburn 4151: sub update_released_required {
4152: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4153: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4154: $cid = $env{'request.course.id'};
4155: $cdom = $env{'course.'.$cid.'.domain'};
4156: $cnum = $env{'course.'.$cid.'.num'};
4157: $chome = $env{'course.'.$cid.'.home'};
4158: }
4159: if ($needsrelease) {
4160: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4161: my $needsupdate;
4162: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4163: $needsupdate = 1;
4164: } else {
4165: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4166: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4167: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4168: $needsupdate = 1;
4169: }
4170: }
4171: if ($needsupdate) {
4172: my %needshash = (
4173: 'internal.releaserequired' => $needsrelease,
4174: );
4175: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4176: if ($putresult eq 'ok') {
4177: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4178: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4179: if (ref($crsinfo{$cid}) eq 'HASH') {
4180: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4181: &courseidput($cdom,\%crsinfo,$chome,'notime');
4182: }
4183: }
4184: }
4185: }
4186: return;
4187: }
4188:
1.461 www 4189: # -------------------------------------------------See if a user is privileged
4190:
4191: sub privileged {
4192: my ($username,$domain)=@_;
4193: my $rolesdump=&reply("dump:$domain:$username:roles",
4194: &homeserver($username,$domain));
1.1033 raeburn 4195: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4196: ($rolesdump =~ /^error:/)) {
4197: return 0;
4198: }
1.461 www 4199: my $now=time;
4200: if ($rolesdump ne '') {
1.800 albertel 4201: foreach my $entry (split(/&/,$rolesdump)) {
4202: if ($entry!~/^rolesdef_/) {
4203: my ($area,$role)=split(/=/,$entry);
1.461 www 4204: $area=~s/\_\w\w$//;
4205: my ($trole,$tend,$tstart)=split(/_/,$role);
4206: if (($trole eq 'dc') || ($trole eq 'su')) {
4207: my $active=1;
4208: if ($tend) {
4209: if ($tend<$now) { $active=0; }
4210: }
4211: if ($tstart) {
4212: if ($tstart>$now) { $active=0; }
4213: }
4214: if ($active) { return 1; }
4215: }
4216: }
4217: }
4218: }
4219: return 0;
1.9 www 4220: }
1.1 albertel 4221:
1.103 harris41 4222: # -------------------------------------------------------- Get user privileges
1.11 www 4223:
4224: sub rolesinit {
4225: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4226: my $now=time;
4227: my %userroles = ('user.login.time' => $now);
1.1056.4.10 raeburn 4228: my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3 raeburn 4229: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4230: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1056.4.3 raeburn 4231: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4232: return \%userroles;
4233: }
1.11 www 4234: my %allroles=();
1.678 raeburn 4235: my %allgroups=();
4236: my $group_privs;
1.11 www 4237:
4238: if ($rolesdump ne '') {
1.800 albertel 4239: foreach my $entry (split(/&/,$rolesdump)) {
4240: if ($entry!~/^rolesdef_/) {
4241: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4242: $area=~s/\_\w\w$//;
1.678 raeburn 4243: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4244: if ($role=~/^cr/) {
1.807 albertel 4245: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4246: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4247: ($tend,$tstart)=split('_',$trest);
4248: } else {
4249: $trole=$role;
4250: }
1.678 raeburn 4251: } elsif ($role =~ m|^gr/|) {
4252: ($trole,$tend,$tstart) = split(/_/,$role);
4253: ($trole,$group_privs) = split(/\//,$trole);
4254: $group_privs = &unescape($group_privs);
1.587 albertel 4255: } else {
4256: ($trole,$tend,$tstart)=split(/_/,$role);
4257: }
1.743 albertel 4258: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4259: $username);
4260: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4261: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4262: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4263: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4264: my $spec=$trole.'.'.$area;
4265: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4266: if ($trole =~ /^cr\//) {
1.567 raeburn 4267: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4268: } elsif ($trole eq 'gr') {
4269: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4270: } else {
1.567 raeburn 4271: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4272: }
1.12 www 4273: }
1.662 raeburn 4274: }
1.191 harris41 4275: }
1.743 albertel 4276: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4277: $userroles{'user.adv'} = $adv;
4278: $userroles{'user.author'} = $author;
1.620 albertel 4279: $env{'user.adv'}=$adv;
1.11 www 4280: }
1.743 albertel 4281: return \%userroles;
1.11 www 4282: }
4283:
1.567 raeburn 4284: sub set_arearole {
4285: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4286: # log the associated role with the area
4287: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4288: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4289: }
4290:
4291: sub custom_roleprivs {
4292: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4293: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4294: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4295: if (&hostname($homsvr) ne '') {
1.567 raeburn 4296: my ($rdummy,$roledef)=
4297: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4298: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4299: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4300: if (defined($syspriv)) {
1.1043 raeburn 4301: if ($trest =~ /^$match_community$/) {
4302: $syspriv =~ s/bre\&S//;
4303: }
1.567 raeburn 4304: $$allroles{'cm./'}.=':'.$syspriv;
4305: $$allroles{$spec.'./'}.=':'.$syspriv;
4306: }
4307: if ($tdomain ne '') {
4308: if (defined($dompriv)) {
4309: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4310: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4311: }
4312: if (($trest ne '') && (defined($coursepriv))) {
4313: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4314: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4315: }
4316: }
4317: }
4318: }
4319: }
4320:
1.678 raeburn 4321: sub group_roleprivs {
4322: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4323: my $access = 1;
4324: my $now = time;
4325: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4326: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4327: if ($access) {
1.811 albertel 4328: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4329: $$allgroups{$course}{$group} .=':'.$group_privs;
4330: }
4331: }
1.567 raeburn 4332:
4333: sub standard_roleprivs {
4334: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4335: if (defined($pr{$trole.':s'})) {
4336: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4337: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4338: }
4339: if ($tdomain ne '') {
4340: if (defined($pr{$trole.':d'})) {
4341: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4342: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4343: }
4344: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4345: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4346: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4347: }
4348: }
4349: }
4350:
4351: sub set_userprivs {
1.1056.4.2 raeburn 4352: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4353: my $author=0;
4354: my $adv=0;
1.678 raeburn 4355: my %grouproles = ();
4356: if (keys(%{$allgroups}) > 0) {
1.1056.4.2 raeburn 4357: my @groupkeys;
1.1000 raeburn 4358: foreach my $role (keys(%{$allroles})) {
1.1056.4.2 raeburn 4359: push(@groupkeys,$role);
4360: }
4361: if (ref($groups_roles) eq 'HASH') {
4362: foreach my $key (keys(%{$groups_roles})) {
4363: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4364: push(@groupkeys,$key);
4365: }
4366: }
4367: }
4368: if (@groupkeys > 0) {
4369: foreach my $role (@groupkeys) {
4370: my ($trole,$area,$sec,$extendedarea);
4371: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4372: $trole = $1;
4373: $area = $2;
4374: $sec = $3;
4375: $extendedarea = $area.$sec;
4376: if (exists($$allgroups{$area})) {
4377: foreach my $group (keys(%{$$allgroups{$area}})) {
4378: my $spec = $trole.'.'.$extendedarea;
4379: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4380: $$allgroups{$area}{$group};
1.1056.4.2 raeburn 4381: }
1.678 raeburn 4382: }
4383: }
4384: }
4385: }
4386: }
1.800 albertel 4387: foreach my $group (keys(%grouproles)) {
4388: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4389: }
1.800 albertel 4390: foreach my $role (keys(%{$allroles})) {
4391: my %thesepriv;
1.941 raeburn 4392: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4393: foreach my $item (split(/:/,$$allroles{$role})) {
4394: if ($item ne '') {
4395: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4396: if ($restrictions eq '') {
4397: $thesepriv{$privilege}='F';
4398: } elsif ($thesepriv{$privilege} ne 'F') {
4399: $thesepriv{$privilege}.=$restrictions;
4400: }
4401: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4402: }
4403: }
4404: my $thesestr='';
1.800 albertel 4405: foreach my $priv (keys(%thesepriv)) {
4406: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4407: }
4408: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4409: }
4410: return ($author,$adv);
4411: }
4412:
1.994 raeburn 4413: sub role_status {
1.1002 raeburn 4414: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4415: my @pwhere = ();
4416: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4417: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4418: unless (!defined($$role) || $$role eq '') {
4419: $$where=join('.',@pwhere);
4420: $$trolecode=$$role.'.'.$$where;
4421: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4422: $$tstatus='is';
4423: if ($$tstart && $$tstart>$then) {
4424: $$tstatus='future';
1.1034 raeburn 4425: if ($$tstart<$now) {
4426: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4427: if (($$where ne '') && ($$role ne '')) {
1.1056.4.2 raeburn 4428: my (%allroles,%allgroups,$group_privs,
4429: %groups_roles,@rolecodes);
1.1002 raeburn 4430: my %userroles = (
4431: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4432: );
1.1056.4.2 raeburn 4433: @rolecodes = ('cm');
1.1002 raeburn 4434: my $spec=$$role.'.'.$$where;
4435: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4436: if ($$role =~ /^cr\//) {
4437: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2 raeburn 4438: push(@rolecodes,'cr');
1.1002 raeburn 4439: } elsif ($$role eq 'gr') {
1.1056.4.2 raeburn 4440: push(@rolecodes,$$role);
1.1002 raeburn 4441: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4442: $env{'user.name'});
1.1056.4.2 raeburn 4443: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4444: (undef,my $group_privs) = split(/\//,$trole);
4445: $group_privs = &unescape($group_privs);
4446: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2 raeburn 4447: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4448: if (keys(%course_roles) > 0) {
4449: my ($tnum) = ($trest =~ /^($match_courseid)/);
4450: if ($tdomain ne '' && $tnum ne '') {
4451: foreach my $key (keys(%course_roles)) {
4452: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4453: my $crsrole = $1;
4454: my $crssec = $2;
4455: if ($crsrole =~ /^cr/) {
4456: unless (grep(/^cr$/,@rolecodes)) {
4457: push(@rolecodes,'cr');
4458: }
4459: } else {
4460: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4461: push(@rolecodes,$crsrole);
4462: }
4463: }
4464: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4465: if ($crssec ne '') {
4466: $rolekey .= '/'.$crssec;
4467: }
4468: $rolekey .= './';
4469: $groups_roles{$rolekey} = \@rolecodes;
4470: }
4471: }
4472: }
4473: }
1.1002 raeburn 4474: } else {
1.1056.4.2 raeburn 4475: push(@rolecodes,$$role);
1.1002 raeburn 4476: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4477: }
1.1056.4.2 raeburn 4478: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4479: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4480: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4481: }
4482: }
1.1034 raeburn 4483: $$tstatus = 'is';
1.1002 raeburn 4484: }
1.994 raeburn 4485: }
4486: if ($$tend) {
4487: if ($$tend<$then) {
4488: $$tstatus='expired';
4489: } elsif ($$tend<$now) {
4490: $$tstatus='will_not';
4491: }
4492: }
4493: }
4494: }
4495: }
4496:
4497: sub check_adhoc_privs {
1.1056.4.12 raeburn 4498: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4499: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4500: if ($env{$cckey}) {
4501: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4502: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4503: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12 raeburn 4504: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4505: }
4506: } else {
1.1056.4.12 raeburn 4507: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4508: }
4509: }
4510:
4511: sub set_adhoc_privileges {
4512: # role can be cc or ca
1.1056.4.12 raeburn 4513: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4514: my $area = '/'.$dcdom.'/'.$pickedcourse;
4515: my $spec = $role.'.'.$area;
4516: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4517: $env{'user.name'});
4518: my %ccrole = ();
4519: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4520: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4521: &appenv(\%userroles,[$role,'cm']);
4522: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12 raeburn 4523: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4524: &appenv( {'request.role' => $spec,
4525: 'request.role.domain' => $dcdom,
4526: 'request.course.sec' => ''
4527: }
4528: );
4529: my $tadv=0;
4530: if (&allowed('adv') eq 'F') { $tadv=1; }
4531: &appenv({'request.role.adv' => $tadv});
4532: }
1.994 raeburn 4533: }
4534:
1.12 www 4535: # --------------------------------------------------------------- get interface
4536:
4537: sub get {
1.131 albertel 4538: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4539: my $items='';
1.800 albertel 4540: foreach my $item (@$storearr) {
4541: $items.=&escape($item).'&';
1.191 harris41 4542: }
1.12 www 4543: $items=~s/\&$//;
1.620 albertel 4544: if (!$udomain) { $udomain=$env{'user.domain'}; }
4545: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4546: my $uhome=&homeserver($uname,$udomain);
4547:
1.133 albertel 4548: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4549: my @pairs=split(/\&/,$rep);
1.273 albertel 4550: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4551: return @pairs;
4552: }
1.15 www 4553: my %returnhash=();
1.42 www 4554: my $i=0;
1.800 albertel 4555: foreach my $item (@$storearr) {
4556: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4557: $i++;
1.191 harris41 4558: }
1.15 www 4559: return %returnhash;
1.27 www 4560: }
4561:
4562: # --------------------------------------------------------------- del interface
4563:
4564: sub del {
1.133 albertel 4565: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4566: my $items='';
1.800 albertel 4567: foreach my $item (@$storearr) {
4568: $items.=&escape($item).'&';
1.191 harris41 4569: }
1.984 neumanie 4570:
1.27 www 4571: $items=~s/\&$//;
1.620 albertel 4572: if (!$udomain) { $udomain=$env{'user.domain'}; }
4573: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4574: my $uhome=&homeserver($uname,$udomain);
4575: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4576: }
4577:
4578: # -------------------------------------------------------------- dump interface
4579:
4580: sub dump {
1.1056.4.10 raeburn 4581: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4582: if (!$udomain) { $udomain=$env{'user.domain'}; }
4583: if (!$uname) { $uname=$env{'user.name'}; }
4584: my $uhome=&homeserver($uname,$udomain);
4585: if ($regexp) {
4586: $regexp=&escape($regexp);
4587: } else {
4588: $regexp='.';
4589: }
1.1056.4.10 raeburn 4590: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4591: my @pairs=split(/\&/,$rep);
4592: my %returnhash=();
4593: foreach my $item (@pairs) {
4594: my ($key,$value)=split(/=/,$item,2);
4595: $key = &unescape($key);
4596: next if ($key =~ /^error: 2 /);
4597: $returnhash{$key}=&thaw_unescape($value);
4598: }
4599: return %returnhash;
1.407 www 4600: }
4601:
1.717 albertel 4602: # --------------------------------------------------------- dumpstore interface
4603:
4604: sub dumpstore {
4605: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4606: if (!$udomain) { $udomain=$env{'user.domain'}; }
4607: if (!$uname) { $uname=$env{'user.name'}; }
4608: my $uhome=&homeserver($uname,$udomain);
4609: if ($regexp) {
4610: $regexp=&escape($regexp);
4611: } else {
4612: $regexp='.';
4613: }
4614: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4615: my @pairs=split(/\&/,$rep);
4616: my %returnhash=();
4617: foreach my $item (@pairs) {
4618: my ($key,$value)=split(/=/,$item,2);
4619: next if ($key =~ /^error: 2 /);
4620: $returnhash{$key}=&thaw_unescape($value);
4621: }
4622: return %returnhash;
1.717 albertel 4623: }
4624:
1.407 www 4625: # -------------------------------------------------------------- keys interface
4626:
4627: sub getkeys {
4628: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4629: if (!$udomain) { $udomain=$env{'user.domain'}; }
4630: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4631: my $uhome=&homeserver($uname,$udomain);
4632: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4633: my @keyarray=();
1.800 albertel 4634: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4635: next if ($key =~ /^error: 2 /);
1.800 albertel 4636: push(@keyarray,&unescape($key));
1.407 www 4637: }
4638: return @keyarray;
1.318 matthew 4639: }
4640:
1.319 matthew 4641: # --------------------------------------------------------------- currentdump
4642: sub currentdump {
1.328 matthew 4643: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4644: $courseid = $env{'request.course.id'} if (! defined($courseid));
4645: $sdom = $env{'user.domain'} if (! defined($sdom));
4646: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4647: my $uhome = &homeserver($sname,$sdom);
4648: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4649: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4650: #
1.318 matthew 4651: my %returnhash=();
1.319 matthew 4652: #
4653: if ($rep eq "unknown_cmd") {
4654: # an old lond will not know currentdump
4655: # Do a dump and make it look like a currentdump
1.822 albertel 4656: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4657: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4658: my %hash = @tmp;
4659: @tmp=();
1.424 matthew 4660: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4661: } else {
4662: my @pairs=split(/\&/,$rep);
1.800 albertel 4663: foreach my $pair (@pairs) {
4664: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4665: my ($symb,$param) = split(/:/,$key);
4666: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4667: &thaw_unescape($value);
1.319 matthew 4668: }
1.191 harris41 4669: }
1.12 www 4670: return %returnhash;
1.424 matthew 4671: }
4672:
4673: sub convert_dump_to_currentdump{
4674: my %hash = %{shift()};
4675: my %returnhash;
4676: # Code ripped from lond, essentially. The only difference
4677: # here is the unescaping done by lonnet::dump(). Conceivably
4678: # we might run in to problems with parameter names =~ /^v\./
4679: while (my ($key,$value) = each(%hash)) {
4680: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4681: $symb = &unescape($symb);
4682: $param = &unescape($param);
1.424 matthew 4683: next if ($v eq 'version' || $symb eq 'keys');
4684: next if (exists($returnhash{$symb}) &&
4685: exists($returnhash{$symb}->{$param}) &&
4686: $returnhash{$symb}->{'v.'.$param} > $v);
4687: $returnhash{$symb}->{$param}=$value;
4688: $returnhash{$symb}->{'v.'.$param}=$v;
4689: }
4690: #
4691: # Remove all of the keys in the hashes which keep track of
4692: # the version of the parameter.
4693: while (my ($symb,$param_hash) = each(%returnhash)) {
4694: # use a foreach because we are going to delete from the hash.
4695: foreach my $key (keys(%$param_hash)) {
4696: delete($param_hash->{$key}) if ($key =~ /^v\./);
4697: }
4698: }
4699: return \%returnhash;
1.12 www 4700: }
4701:
1.627 albertel 4702: # ------------------------------------------------------ critical inc interface
4703:
4704: sub cinc {
4705: return &inc(@_,'critical');
4706: }
4707:
1.449 matthew 4708: # --------------------------------------------------------------- inc interface
4709:
4710: sub inc {
1.627 albertel 4711: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4712: if (!$udomain) { $udomain=$env{'user.domain'}; }
4713: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4714: my $uhome=&homeserver($uname,$udomain);
4715: my $items='';
4716: if (! ref($store)) {
4717: # got a single value, so use that instead
4718: $items = &escape($store).'=&';
4719: } elsif (ref($store) eq 'SCALAR') {
4720: $items = &escape($$store).'=&';
4721: } elsif (ref($store) eq 'ARRAY') {
4722: $items = join('=&',map {&escape($_);} @{$store});
4723: } elsif (ref($store) eq 'HASH') {
4724: while (my($key,$value) = each(%{$store})) {
4725: $items.= &escape($key).'='.&escape($value).'&';
4726: }
4727: }
4728: $items=~s/\&$//;
1.627 albertel 4729: if ($critical) {
4730: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4731: } else {
4732: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4733: }
1.449 matthew 4734: }
4735:
1.12 www 4736: # --------------------------------------------------------------- put interface
4737:
4738: sub put {
1.134 albertel 4739: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4740: if (!$udomain) { $udomain=$env{'user.domain'}; }
4741: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4742: my $uhome=&homeserver($uname,$udomain);
1.12 www 4743: my $items='';
1.800 albertel 4744: foreach my $item (keys(%$storehash)) {
4745: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4746: }
1.12 www 4747: $items=~s/\&$//;
1.134 albertel 4748: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4749: }
4750:
1.631 albertel 4751: # ------------------------------------------------------------ newput interface
4752:
4753: sub newput {
4754: my ($namespace,$storehash,$udomain,$uname)=@_;
4755: if (!$udomain) { $udomain=$env{'user.domain'}; }
4756: if (!$uname) { $uname=$env{'user.name'}; }
4757: my $uhome=&homeserver($uname,$udomain);
4758: my $items='';
4759: foreach my $key (keys(%$storehash)) {
4760: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4761: }
4762: $items=~s/\&$//;
4763: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4764: }
4765:
4766: # --------------------------------------------------------- putstore interface
4767:
1.524 raeburn 4768: sub putstore {
1.715 albertel 4769: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4770: if (!$udomain) { $udomain=$env{'user.domain'}; }
4771: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4772: my $uhome=&homeserver($uname,$udomain);
4773: my $items='';
1.715 albertel 4774: foreach my $key (keys(%$storehash)) {
4775: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4776: }
1.715 albertel 4777: $items=~s/\&$//;
1.716 albertel 4778: my $esc_symb=&escape($symb);
4779: my $esc_v=&escape($version);
1.715 albertel 4780: my $reply =
1.716 albertel 4781: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4782: $uhome);
4783: if ($reply eq 'unknown_cmd') {
1.716 albertel 4784: # gfall back to way things use to be done
1.715 albertel 4785: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4786: $uname);
1.524 raeburn 4787: }
1.715 albertel 4788: return $reply;
4789: }
4790:
4791: sub old_putstore {
1.716 albertel 4792: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4793: if (!$udomain) { $udomain=$env{'user.domain'}; }
4794: if (!$uname) { $uname=$env{'user.name'}; }
4795: my $uhome=&homeserver($uname,$udomain);
4796: my %newstorehash;
1.800 albertel 4797: foreach my $item (keys(%$storehash)) {
4798: my $key = $version.':'.&escape($symb).':'.$item;
4799: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4800: }
4801: my $items='';
4802: my %allitems = ();
1.800 albertel 4803: foreach my $item (keys(%newstorehash)) {
4804: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4805: my $key = $1.':keys:'.$2;
4806: $allitems{$key} .= $3.':';
4807: }
1.800 albertel 4808: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4809: }
1.800 albertel 4810: foreach my $item (keys(%allitems)) {
4811: $allitems{$item} =~ s/\:$//;
4812: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4813: }
4814: $items=~s/\&$//;
4815: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4816: }
4817:
1.47 www 4818: # ------------------------------------------------------ critical put interface
4819:
4820: sub cput {
1.134 albertel 4821: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4822: if (!$udomain) { $udomain=$env{'user.domain'}; }
4823: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4824: my $uhome=&homeserver($uname,$udomain);
1.47 www 4825: my $items='';
1.800 albertel 4826: foreach my $item (keys(%$storehash)) {
4827: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4828: }
1.47 www 4829: $items=~s/\&$//;
1.134 albertel 4830: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4831: }
4832:
4833: # -------------------------------------------------------------- eget interface
4834:
4835: sub eget {
1.133 albertel 4836: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4837: my $items='';
1.800 albertel 4838: foreach my $item (@$storearr) {
4839: $items.=&escape($item).'&';
1.191 harris41 4840: }
1.12 www 4841: $items=~s/\&$//;
1.620 albertel 4842: if (!$udomain) { $udomain=$env{'user.domain'}; }
4843: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4844: my $uhome=&homeserver($uname,$udomain);
4845: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4846: my @pairs=split(/\&/,$rep);
4847: my %returnhash=();
1.42 www 4848: my $i=0;
1.800 albertel 4849: foreach my $item (@$storearr) {
4850: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4851: $i++;
1.191 harris41 4852: }
1.12 www 4853: return %returnhash;
4854: }
4855:
1.667 albertel 4856: # ------------------------------------------------------------ tmpput interface
4857: sub tmpput {
1.802 raeburn 4858: my ($storehash,$server,$context)=@_;
1.667 albertel 4859: my $items='';
1.800 albertel 4860: foreach my $item (keys(%$storehash)) {
4861: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4862: }
4863: $items=~s/\&$//;
1.802 raeburn 4864: if (defined($context)) {
4865: $items .= ':'.&escape($context);
4866: }
1.667 albertel 4867: return &reply("tmpput:$items",$server);
4868: }
4869:
4870: # ------------------------------------------------------------ tmpget interface
4871: sub tmpget {
1.688 albertel 4872: my ($token,$server)=@_;
4873: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4874: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4875: my %returnhash;
4876: foreach my $item (split(/\&/,$rep)) {
4877: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4878: next if ($key =~ /^error: 2 /);
1.667 albertel 4879: $returnhash{&unescape($key)}=&thaw_unescape($value);
4880: }
4881: return %returnhash;
4882: }
4883:
1.688 albertel 4884: # ------------------------------------------------------------ tmpget interface
4885: sub tmpdel {
4886: my ($token,$server)=@_;
4887: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4888: return &reply("tmpdel:$token",$server);
4889: }
4890:
1.765 albertel 4891: # -------------------------------------------------- portfolio access checking
4892:
4893: sub portfolio_access {
1.766 albertel 4894: my ($requrl) = @_;
1.765 albertel 4895: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4896: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4897: if ($result) {
4898: my %setters;
4899: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4900: my ($startblock,$endblock) =
4901: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4902: if ($startblock && $endblock) {
4903: return 'B';
4904: }
4905: } else {
4906: my ($startblock,$endblock) =
4907: &Apache::loncommon::blockcheck(\%setters,'port');
4908: if ($startblock && $endblock) {
4909: return 'B';
4910: }
4911: }
4912: }
1.765 albertel 4913: if ($result eq 'ok') {
1.766 albertel 4914: return 'F';
1.765 albertel 4915: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4916: return 'A';
1.765 albertel 4917: }
1.766 albertel 4918: return '';
1.765 albertel 4919: }
4920:
4921: sub get_portfolio_access {
1.767 albertel 4922: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4923:
4924: if (!ref($access_hash)) {
4925: my $current_perms = &get_portfile_permissions($udom,$unum);
4926: my %access_controls = &get_access_controls($current_perms,$group,
4927: $file_name);
4928: $access_hash = $access_controls{$file_name};
4929: }
4930:
1.765 albertel 4931: my ($public,$guest,@domains,@users,@courses,@groups);
4932: my $now = time;
4933: if (ref($access_hash) eq 'HASH') {
4934: foreach my $key (keys(%{$access_hash})) {
4935: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4936: if ($start > $now) {
4937: next;
4938: }
4939: if ($end && $end<$now) {
4940: next;
4941: }
4942: if ($scope eq 'public') {
4943: $public = $key;
4944: last;
4945: } elsif ($scope eq 'guest') {
4946: $guest = $key;
4947: } elsif ($scope eq 'domains') {
4948: push(@domains,$key);
4949: } elsif ($scope eq 'users') {
4950: push(@users,$key);
4951: } elsif ($scope eq 'course') {
4952: push(@courses,$key);
4953: } elsif ($scope eq 'group') {
4954: push(@groups,$key);
4955: }
4956: }
4957: if ($public) {
4958: return 'ok';
4959: }
4960: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4961: if ($guest) {
4962: return $guest;
4963: }
4964: } else {
4965: if (@domains > 0) {
4966: foreach my $domkey (@domains) {
4967: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4968: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4969: return 'ok';
4970: }
4971: }
4972: }
4973: }
4974: if (@users > 0) {
4975: foreach my $userkey (@users) {
1.865 raeburn 4976: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4977: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4978: if (ref($item) eq 'HASH') {
4979: if (($item->{'uname'} eq $env{'user.name'}) &&
4980: ($item->{'udom'} eq $env{'user.domain'})) {
4981: return 'ok';
4982: }
4983: }
4984: }
4985: }
1.765 albertel 4986: }
4987: }
4988: my %roleshash;
4989: my @courses_and_groups = @courses;
4990: push(@courses_and_groups,@groups);
4991: if (@courses_and_groups > 0) {
4992: my (%allgroups,%allroles);
4993: my ($start,$end,$role,$sec,$group);
4994: foreach my $envkey (%env) {
1.1056.4.1 raeburn 4995: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4996: my $cid = $2.'_'.$3;
4997: if ($1 eq 'gr') {
4998: $group = $4;
4999: $allgroups{$cid}{$group} = $env{$envkey};
5000: } else {
5001: if ($4 eq '') {
5002: $sec = 'none';
5003: } else {
5004: $sec = $4;
5005: }
5006: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5007: }
1.811 albertel 5008: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5009: my $cid = $2.'_'.$3;
5010: if ($4 eq '') {
5011: $sec = 'none';
5012: } else {
5013: $sec = $4;
5014: }
5015: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5016: }
5017: }
5018: if (keys(%allroles) == 0) {
5019: return;
5020: }
5021: foreach my $key (@courses_and_groups) {
5022: my %content = %{$$access_hash{$key}};
5023: my $cnum = $content{'number'};
5024: my $cdom = $content{'domain'};
5025: my $cid = $cdom.'_'.$cnum;
5026: if (!exists($allroles{$cid})) {
5027: next;
5028: }
5029: foreach my $role_id (keys(%{$content{'roles'}})) {
5030: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5031: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5032: my @status = @{$content{'roles'}{$role_id}{'access'}};
5033: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5034: foreach my $role (keys(%{$allroles{$cid}})) {
5035: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5036: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5037: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5038: if (grep/^all$/,@sections) {
5039: return 'ok';
5040: } else {
5041: if (grep/^$sec$/,@sections) {
5042: return 'ok';
5043: }
5044: }
5045: }
5046: }
5047: if (keys(%{$allgroups{$cid}}) == 0) {
5048: if (grep/^none$/,@groups) {
5049: return 'ok';
5050: }
5051: } else {
5052: if (grep/^all$/,@groups) {
5053: return 'ok';
5054: }
5055: foreach my $group (keys(%{$allgroups{$cid}})) {
5056: if (grep/^$group$/,@groups) {
5057: return 'ok';
5058: }
5059: }
5060: }
5061: }
5062: }
5063: }
5064: }
5065: }
5066: if ($guest) {
5067: return $guest;
5068: }
5069: }
5070: }
5071: return;
5072: }
5073:
5074: sub course_group_datechecker {
5075: my ($dates,$now,$status) = @_;
5076: my ($start,$end) = split(/\./,$dates);
5077: if (!$start && !$end) {
5078: return 'ok';
5079: }
5080: if (grep/^active$/,@{$status}) {
5081: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5082: return 'ok';
5083: }
5084: }
5085: if (grep/^previous$/,@{$status}) {
5086: if ($end > $now ) {
5087: return 'ok';
5088: }
5089: }
5090: if (grep/^future$/,@{$status}) {
5091: if ($start > $now) {
5092: return 'ok';
5093: }
5094: }
5095: return;
5096: }
5097:
5098: sub parse_portfolio_url {
5099: my ($url) = @_;
5100:
5101: my ($type,$udom,$unum,$group,$file_name);
5102:
1.823 albertel 5103: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5104: $type = 1;
5105: $udom = $1;
5106: $unum = $2;
5107: $file_name = $3;
1.823 albertel 5108: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5109: $type = 2;
5110: $udom = $1;
5111: $unum = $2;
5112: $group = $3;
5113: $file_name = $3.'/'.$4;
5114: }
5115: if (wantarray) {
5116: return ($type,$udom,$unum,$file_name,$group);
5117: }
5118: return $type;
5119: }
5120:
5121: sub is_portfolio_url {
5122: my ($url) = @_;
5123: return scalar(&parse_portfolio_url($url));
5124: }
5125:
1.798 raeburn 5126: sub is_portfolio_file {
5127: my ($file) = @_;
1.820 raeburn 5128: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5129: return 1;
5130: }
5131: return;
5132: }
5133:
1.976 raeburn 5134: sub usertools_access {
1.1056.4.9 raeburn 5135: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985 raeburn 5136: my ($access,%tools);
5137: if ($context eq '') {
5138: $context = 'tools';
5139: }
5140: if ($context eq 'requestcourses') {
5141: %tools = (
5142: official => 1,
5143: unofficial => 1,
1.1006 raeburn 5144: community => 1,
1.985 raeburn 5145: );
5146: } else {
5147: %tools = (
5148: aboutme => 1,
5149: blog => 1,
5150: portfolio => 1,
5151: );
5152: }
1.976 raeburn 5153: return if (!defined($tools{$tool}));
5154:
5155: if ((!defined($udom)) || (!defined($uname))) {
5156: $udom = $env{'user.domain'};
5157: $uname = $env{'user.name'};
5158: }
5159:
1.978 raeburn 5160: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5161: if ($action ne 'reload') {
1.985 raeburn 5162: if ($context eq 'requestcourses') {
5163: return $env{'environment.canrequest.'.$tool};
5164: } else {
5165: return $env{'environment.availabletools.'.$tool};
5166: }
5167: }
1.976 raeburn 5168: }
5169:
5170: my ($toolstatus,$inststatus);
5171:
1.985 raeburn 5172: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5173: ($action ne 'reload')) {
5174: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5175: $inststatus = $env{'environment.inststatus'};
5176: } else {
1.1056.4.9 raeburn 5177: if (ref($userenvref) eq 'HASH') {
5178: $toolstatus = $userenvref->{$context.'.'.$tool};
5179: $inststatus = $userenvref->{'inststatus'};
5180: } else {
5181: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5182: $toolstatus = $userenv{$context.'.'.$tool};
5183: $inststatus = $userenv{'inststatus'};
5184: }
1.976 raeburn 5185: }
5186:
5187: if ($toolstatus ne '') {
5188: if ($toolstatus) {
5189: $access = 1;
5190: } else {
5191: $access = 0;
5192: }
5193: return $access;
5194: }
5195:
1.1056.4.9 raeburn 5196: my ($is_adv,%domdef);
5197: if (ref($is_advref) eq 'HASH') {
5198: $is_adv = $is_advref->{'is_adv'};
5199: } else {
5200: $is_adv = &is_advanced_user($udom,$uname);
5201: }
5202: if (ref($domdefref) eq 'HASH') {
5203: %domdef = %{$domdefref};
5204: } else {
5205: %domdef = &get_domain_defaults($udom);
5206: }
1.976 raeburn 5207: if (ref($domdef{$tool}) eq 'HASH') {
5208: if ($is_adv) {
5209: if ($domdef{$tool}{'_LC_adv'} ne '') {
5210: if ($domdef{$tool}{'_LC_adv'}) {
5211: $access = 1;
5212: } else {
5213: $access = 0;
5214: }
5215: return $access;
5216: }
5217: }
5218: if ($inststatus ne '') {
5219: my ($hasaccess,$hasnoaccess);
5220: foreach my $affiliation (split(/:/,$inststatus)) {
5221: if ($domdef{$tool}{$affiliation} ne '') {
5222: if ($domdef{$tool}{$affiliation}) {
5223: $hasaccess = 1;
5224: } else {
5225: $hasnoaccess = 1;
5226: }
5227: }
5228: }
5229: if ($hasaccess || $hasnoaccess) {
5230: if ($hasaccess) {
5231: $access = 1;
5232: } elsif ($hasnoaccess) {
5233: $access = 0;
5234: }
5235: return $access;
5236: }
5237: } else {
5238: if ($domdef{$tool}{'default'} ne '') {
5239: if ($domdef{$tool}{'default'}) {
5240: $access = 1;
5241: } elsif ($domdef{$tool}{'default'} == 0) {
5242: $access = 0;
5243: }
5244: return $access;
5245: }
5246: }
5247: } else {
1.985 raeburn 5248: if ($context eq 'tools') {
5249: $access = 1;
5250: } else {
5251: $access = 0;
5252: }
1.976 raeburn 5253: return $access;
5254: }
5255: }
5256:
1.1050 raeburn 5257: sub is_course_owner {
5258: my ($cdom,$cnum,$udom,$uname) = @_;
5259: if (($udom eq '') || ($uname eq '')) {
5260: $udom = $env{'user.domain'};
5261: $uname = $env{'user.name'};
5262: }
5263: unless (($udom eq '') || ($uname eq '')) {
5264: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5265: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5266: return 1;
5267: } else {
5268: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5269: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5270: return 1;
5271: }
5272: }
5273: }
5274: }
5275: return;
5276: }
5277:
1.976 raeburn 5278: sub is_advanced_user {
5279: my ($udom,$uname) = @_;
1.1056.4.10 raeburn 5280: if ($udom ne '' && $uname ne '') {
5281: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5282: return $env{'user.adv'};
5283: }
5284: }
1.976 raeburn 5285: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5286: my %allroles;
5287: my $is_adv;
5288: foreach my $role (keys(%roleshash)) {
5289: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5290: my $area = '/'.$tdomain.'/'.$trest;
5291: if ($sec ne '') {
5292: $area .= '/'.$sec;
5293: }
5294: if (($area ne '') && ($trole ne '')) {
5295: my $spec=$trole.'.'.$area;
5296: if ($trole =~ /^cr\//) {
5297: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5298: } elsif ($trole ne 'gr') {
5299: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5300: }
5301: }
5302: }
5303: foreach my $role (keys(%allroles)) {
5304: last if ($is_adv);
5305: foreach my $item (split(/:/,$allroles{$role})) {
5306: if ($item ne '') {
5307: my ($privilege,$restrictions)=split(/&/,$item);
5308: if ($privilege eq 'adv') {
5309: $is_adv = 1;
5310: last;
5311: }
5312: }
5313: }
5314: }
5315: return $is_adv;
5316: }
1.798 raeburn 5317:
1.1035 raeburn 5318: sub check_can_request {
1.1036 raeburn 5319: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5320: my $canreq = 0;
5321: my ($types,$typename) = &Apache::loncommon::course_types();
5322: my @options = ('approval','validate','autolimit');
5323: my $optregex = join('|',@options);
5324: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5325: foreach my $type (@{$types}) {
5326: if (&usertools_access($env{'user.name'},
5327: $env{'user.domain'},
5328: $type,undef,'requestcourses')) {
5329: $canreq ++;
1.1036 raeburn 5330: if (ref($request_domains) eq 'HASH') {
5331: push(@{$request_domains->{$type}},$env{'user.domain'});
5332: }
1.1035 raeburn 5333: if ($dom eq $env{'user.domain'}) {
5334: $can_request->{$type} = 1;
5335: }
5336: }
5337: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5338: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5339: if (@curr > 0) {
1.1036 raeburn 5340: foreach my $item (@curr) {
5341: if (ref($request_domains) eq 'HASH') {
5342: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5343: if ($otherdom ne '') {
5344: if (ref($request_domains->{$type}) eq 'ARRAY') {
5345: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5346: push(@{$request_domains->{$type}},$otherdom);
5347: }
5348: } else {
5349: push(@{$request_domains->{$type}},$otherdom);
5350: }
5351: }
5352: }
5353: }
5354: unless($dom eq $env{'user.domain'}) {
5355: $canreq ++;
1.1035 raeburn 5356: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5357: $can_request->{$type} = 1;
5358: }
5359: }
5360: }
5361: }
5362: }
5363: }
5364: return $canreq;
5365: }
5366:
1.341 www 5367: # ---------------------------------------------- Custom access rule evaluation
5368:
5369: sub customaccess {
5370: my ($priv,$uri)=@_;
1.807 albertel 5371: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5372: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5373: $udom = &LONCAPA::clean_domain($udom);
5374: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5375: my $access=0;
1.800 albertel 5376: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5377: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5378: if ($type eq 'user') {
5379: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5380: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5381: if ($tdom) {
5382: if ($tdom ne $env{'user.domain'}) { next; }
5383: }
1.896 albertel 5384: if ($tuname) {
5385: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5386: }
5387: $access=($effect eq 'allow');
5388: last;
5389: }
5390: } else {
5391: if ($role) {
5392: if ($role ne $urole) { next; }
5393: }
5394: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5395: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5396: if ($tdom) {
5397: if ($tdom ne $udom) { next; }
5398: }
5399: if ($tcrs) {
5400: if ($tcrs ne $ucrs) { next; }
5401: }
5402: if ($tsec) {
5403: if ($tsec ne $usec) { next; }
5404: }
5405: $access=($effect eq 'allow');
5406: last;
5407: }
5408: if ($realm eq '' && $role eq '') {
5409: $access=($effect eq 'allow');
5410: }
1.402 bowersj2 5411: }
1.341 www 5412: }
5413: return $access;
5414: }
5415:
1.103 harris41 5416: # ------------------------------------------------- Check for a user privilege
1.12 www 5417:
5418: sub allowed {
1.810 raeburn 5419: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5420: my $ver_orguri=$uri;
1.439 www 5421: $uri=&deversion($uri);
1.152 www 5422: my $orguri=$uri;
1.52 www 5423: $uri=&declutter($uri);
1.809 raeburn 5424:
1.810 raeburn 5425: if ($priv eq 'evb') {
5426: # Evade communication block restrictions for specified role in a course
5427: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5428: return $1;
5429: } else {
5430: return;
5431: }
5432: }
5433:
1.620 albertel 5434: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5435: # Free bre access to adm and meta resources
1.775 albertel 5436: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5437: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5438: && ($priv eq 'bre')) {
1.14 www 5439: return 'F';
1.159 www 5440: }
5441:
1.545 banghart 5442: # Free bre access to user's own portfolio contents
1.714 raeburn 5443: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5444: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5445: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5446: my %setters;
5447: my ($startblock,$endblock) =
5448: &Apache::loncommon::blockcheck(\%setters,'port');
5449: if ($startblock && $endblock) {
5450: return 'B';
5451: } else {
5452: return 'F';
5453: }
1.545 banghart 5454: }
5455:
1.762 raeburn 5456: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5457: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5458: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5459: if (exists($env{'request.course.id'})) {
5460: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5461: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5462: if (($domain eq $cdom) && ($name eq $cnum)) {
5463: my $courseprivid=$env{'request.course.id'};
5464: $courseprivid=~s/\_/\//;
5465: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5466: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5467: return $1;
1.762 raeburn 5468: } else {
5469: if ($env{'request.course.sec'}) {
5470: $courseprivid.='/'.$env{'request.course.sec'};
5471: }
5472: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5473: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5474: return $2;
5475: }
1.714 raeburn 5476: }
5477: }
5478: }
5479: }
5480:
1.159 www 5481: # Free bre to public access
5482:
5483: if ($priv eq 'bre') {
1.238 www 5484: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5485: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5486: return 'F';
5487: }
1.238 www 5488: if ($copyright eq 'priv') {
5489: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5490: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5491: return '';
5492: }
5493: }
5494: if ($copyright eq 'domain') {
5495: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5496: unless (($env{'user.domain'} eq $1) ||
5497: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5498: return '';
5499: }
1.262 matthew 5500: }
1.620 albertel 5501: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5502: # Library role, so allow browsing of resources in this domain.
5503: return 'F';
1.238 www 5504: }
1.341 www 5505: if ($copyright eq 'custom') {
5506: unless (&customaccess($priv,$uri)) { return ''; }
5507: }
1.14 www 5508: }
1.264 matthew 5509: # Domain coordinator is trying to create a course
1.620 albertel 5510: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5511: # uri is the requested domain in this case.
5512: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5513: # a role of dc for the domain in question.
1.620 albertel 5514: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5515: }
1.29 www 5516:
1.52 www 5517: my $thisallowed='';
5518: my $statecond=0;
5519: my $courseprivid='';
5520:
1.1039 raeburn 5521: my $ownaccess;
1.1043 raeburn 5522: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5523: if (($priv eq 'bro') && ($env{'user.author'})) {
5524: if ($uri eq '') {
5525: $ownaccess = 1;
5526: } else {
5527: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5528: my $udom = $env{'user.domain'};
5529: my $uname = $env{'user.name'};
5530: if ($uri =~ m{^\Q$udom\E/?$}) {
5531: $ownaccess = 1;
1.1040 raeburn 5532: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5533: unless ($uri =~ m{\.\./}) {
5534: $ownaccess = 1;
5535: }
5536: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5537: my $now = time;
5538: if ($uri =~ m{^([^/]+)/?$}) {
5539: my $adom = $1;
5540: foreach my $key (keys(%env)) {
1.1042 raeburn 5541: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5542: my ($start,$end) = split('.',$env{$key});
5543: if (($now >= $start) && (!$end || $end < $now)) {
5544: $ownaccess = 1;
5545: last;
5546: }
5547: }
5548: }
5549: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5550: my $adom = $1;
5551: my $aname = $2;
1.1042 raeburn 5552: foreach my $role ('ca','aa') {
5553: if ($env{"user.role.$role./$adom/$aname"}) {
5554: my ($start,$end) =
5555: split('.',$env{"user.role.$role./$adom/$aname"});
5556: if (($now >= $start) && (!$end || $end < $now)) {
5557: $ownaccess = 1;
5558: last;
5559: }
1.1039 raeburn 5560: }
5561: }
5562: }
5563: }
5564: }
5565: }
5566: }
5567:
1.52 www 5568: # Course
5569:
1.620 albertel 5570: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5571: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5572: $thisallowed.=$1;
5573: }
1.52 www 5574: }
1.29 www 5575:
1.52 www 5576: # Domain
5577:
1.620 albertel 5578: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5579: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5580: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5581: $thisallowed.=$1;
5582: }
1.12 www 5583: }
1.52 www 5584:
5585: # Course: uri itself is a course
1.66 www 5586: my $courseuri=$uri;
5587: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5588: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5589:
1.620 albertel 5590: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5591: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5592: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5593: $thisallowed.=$1;
5594: }
1.12 www 5595: }
1.29 www 5596:
1.665 albertel 5597: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5598: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5599: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5600: $thisallowed='';
1.671 raeburn 5601: my ($match)=&is_on_map($uri);
5602: if ($match) {
5603: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5604: =~/\Q$priv\E\&([^\:]*)/) {
5605: $thisallowed.=$1;
5606: }
5607: } else {
1.705 albertel 5608: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5609: if ($refuri) {
5610: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5611: $thisallowed='F';
1.671 raeburn 5612: } else {
5613: $refuri=&declutter($refuri);
5614: my ($match) = &is_on_map($refuri);
5615: if ($match) {
5616: $thisallowed='F';
5617: }
1.669 raeburn 5618: }
1.671 raeburn 5619: }
5620: }
1.314 www 5621: }
1.492 albertel 5622:
1.766 albertel 5623: if ($priv eq 'bre'
5624: && $thisallowed ne 'F'
5625: && $thisallowed ne '2'
5626: && &is_portfolio_url($uri)) {
5627: $thisallowed = &portfolio_access($uri);
5628: }
5629:
1.52 www 5630: # Full access at system, domain or course-wide level? Exit.
1.29 www 5631: if ($thisallowed=~/F/) {
5632: return 'F';
5633: }
5634:
1.52 www 5635: # If this is generating or modifying users, exit with special codes
1.29 www 5636:
1.643 www 5637: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5638: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5639: my ($audom,$auname)=split('/',$uri);
1.643 www 5640: # no author name given, so this just checks on the general right to make a co-author in this domain
5641: unless ($auname) { return $thisallowed; }
5642: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5643: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5644: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5645: ($audom ne $env{'request.role.domain'}))) { return ''; }
5646: }
1.52 www 5647: return $thisallowed;
5648: }
5649: #
1.103 harris41 5650: # Gathered so far: system, domain and course wide privileges
1.52 www 5651: #
5652: # Course: See if uri or referer is an individual resource that is part of
5653: # the course
5654:
1.620 albertel 5655: if ($env{'request.course.id'}) {
1.232 www 5656:
1.620 albertel 5657: $courseprivid=$env{'request.course.id'};
5658: if ($env{'request.course.sec'}) {
5659: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5660: }
5661: $courseprivid=~s/\_/\//;
5662: my $checkreferer=1;
1.232 www 5663: my ($match,$cond)=&is_on_map($uri);
5664: if ($match) {
5665: $statecond=$cond;
1.620 albertel 5666: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5667: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5668: $thisallowed.=$1;
5669: $checkreferer=0;
5670: }
1.29 www 5671: }
1.83 www 5672:
1.148 www 5673: if ($checkreferer) {
1.620 albertel 5674: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5675: unless ($refuri) {
1.800 albertel 5676: foreach my $key (keys(%env)) {
5677: if ($key=~/^httpref\..*\*/) {
5678: my $pattern=$key;
1.156 www 5679: $pattern=~s/^httpref\.\/res\///;
1.148 www 5680: $pattern=~s/\*/\[\^\/\]\+/g;
5681: $pattern=~s/\//\\\//g;
1.152 www 5682: if ($orguri=~/$pattern/) {
1.800 albertel 5683: $refuri=$env{$key};
1.148 www 5684: }
5685: }
1.191 harris41 5686: }
1.148 www 5687: }
1.232 www 5688:
1.148 www 5689: if ($refuri) {
1.152 www 5690: $refuri=&declutter($refuri);
1.232 www 5691: my ($match,$cond)=&is_on_map($refuri);
5692: if ($match) {
5693: my $refstatecond=$cond;
1.620 albertel 5694: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5695: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5696: $thisallowed.=$1;
1.53 www 5697: $uri=$refuri;
5698: $statecond=$refstatecond;
1.52 www 5699: }
5700: }
1.148 www 5701: }
1.29 www 5702: }
1.52 www 5703: }
1.29 www 5704:
1.52 www 5705: #
1.103 harris41 5706: # Gathered now: all privileges that could apply, and condition number
1.52 www 5707: #
5708: #
5709: # Full or no access?
5710: #
1.29 www 5711:
1.52 www 5712: if ($thisallowed=~/F/) {
5713: return 'F';
5714: }
1.29 www 5715:
1.52 www 5716: unless ($thisallowed) {
5717: return '';
5718: }
1.29 www 5719:
1.52 www 5720: # Restrictions exist, deal with them
5721: #
5722: # C:according to course preferences
5723: # R:according to resource settings
5724: # L:unless locked
5725: # X:according to user session state
5726: #
5727:
5728: # Possibly locked functionality, check all courses
1.54 www 5729: # Locks might take effect only after 10 minutes cache expiration for other
5730: # courses, and 2 minutes for current course
1.52 www 5731:
5732: my $envkey;
5733: if ($thisallowed=~/L/) {
1.1000 raeburn 5734: foreach $envkey (keys(%env)) {
1.54 www 5735: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5736: my $courseid=$2;
5737: my $roleid=$1.'.'.$2;
1.92 www 5738: $courseid=~s/^\///;
1.54 www 5739: my $expiretime=600;
1.620 albertel 5740: if ($env{'request.role'} eq $roleid) {
1.54 www 5741: $expiretime=120;
5742: }
5743: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5744: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5745: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5746: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5747: }
1.620 albertel 5748: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5749: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5750: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5751: &log($env{'user.domain'},$env{'user.name'},
5752: $env{'user.home'},
1.57 www 5753: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5754: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5755: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5756: return '';
5757: }
5758: }
1.620 albertel 5759: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5760: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5761: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5762: &log($env{'user.domain'},$env{'user.name'},
5763: $env{'user.home'},
1.57 www 5764: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5765: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5766: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5767: return '';
5768: }
5769: }
5770: }
1.29 www 5771: }
1.52 www 5772: }
5773:
5774: #
5775: # Rest of the restrictions depend on selected course
5776: #
5777:
1.620 albertel 5778: unless ($env{'request.course.id'}) {
1.766 albertel 5779: if ($thisallowed eq 'A') {
5780: return 'A';
1.814 raeburn 5781: } elsif ($thisallowed eq 'B') {
5782: return 'B';
1.766 albertel 5783: } else {
5784: return '1';
5785: }
1.52 www 5786: }
1.29 www 5787:
1.52 www 5788: #
5789: # Now user is definitely in a course
5790: #
1.53 www 5791:
5792:
5793: # Course preferences
5794:
5795: if ($thisallowed=~/C/) {
1.620 albertel 5796: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5797: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5798: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5799: =~/\Q$rolecode\E/) {
1.1056.4.22 raeburn 5800: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5801: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5802: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5803: $env{'request.course.id'});
5804: }
1.237 www 5805: return '';
5806: }
5807:
1.620 albertel 5808: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5809: =~/\Q$unamedom\E/) {
1.1056.4.22 raeburn 5810: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5811: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5812: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5813: $env{'request.course.id'});
5814: }
1.54 www 5815: return '';
5816: }
1.53 www 5817: }
5818:
5819: # Resource preferences
5820:
5821: if ($thisallowed=~/R/) {
1.620 albertel 5822: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5823: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1056.4.22 raeburn 5824: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5825: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5826: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5827: }
5828: return '';
1.54 www 5829: }
1.53 www 5830: }
1.30 www 5831:
1.246 www 5832: # Restricted by state or randomout?
1.30 www 5833:
1.52 www 5834: if ($thisallowed=~/X/) {
1.620 albertel 5835: if ($env{'acc.randomout'}) {
1.579 albertel 5836: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5837: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5838: return '';
5839: }
1.247 www 5840: }
5841: if (&condval($statecond)) {
1.52 www 5842: return '2';
5843: } else {
5844: return '';
5845: }
5846: }
1.30 www 5847:
1.766 albertel 5848: if ($thisallowed eq 'A') {
5849: return 'A';
1.814 raeburn 5850: } elsif ($thisallowed eq 'B') {
5851: return 'B';
1.766 albertel 5852: }
1.52 www 5853: return 'F';
1.232 www 5854: }
5855:
1.710 albertel 5856: sub split_uri_for_cond {
5857: my $uri=&deversion(&declutter(shift));
5858: my @uriparts=split(/\//,$uri);
5859: my $filename=pop(@uriparts);
5860: my $pathname=join('/',@uriparts);
5861: return ($pathname,$filename);
5862: }
1.232 www 5863: # --------------------------------------------------- Is a resource on the map?
5864:
5865: sub is_on_map {
1.710 albertel 5866: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5867: #Trying to find the conditional for the file
1.620 albertel 5868: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5869: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5870: if ($match) {
1.289 bowersj2 5871: return (1,$1);
5872: } else {
1.434 www 5873: return (0,0);
1.289 bowersj2 5874: }
1.12 www 5875: }
5876:
1.427 www 5877: # --------------------------------------------------------- Get symb from alias
5878:
5879: sub get_symb_from_alias {
5880: my $symb=shift;
5881: my ($map,$resid,$url)=&decode_symb($symb);
5882: # Already is a symb
5883: if ($url) { return $symb; }
5884: # Must be an alias
5885: my $aliassymb='';
5886: my %bighash;
1.620 albertel 5887: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5888: &GDBM_READER(),0640)) {
5889: my $rid=$bighash{'mapalias_'.$symb};
5890: if ($rid) {
5891: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5892: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5893: $resid,$bighash{'src_'.$rid});
1.427 www 5894: }
5895: untie %bighash;
5896: }
5897: return $aliassymb;
5898: }
5899:
1.12 www 5900: # ----------------------------------------------------------------- Define Role
5901:
5902: sub definerole {
5903: if (allowed('mcr','/')) {
5904: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5905: foreach my $role (split(':',$sysrole)) {
5906: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5907: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5908: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5909: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5910: return "refused:s:$crole&$cqual";
5911: }
5912: }
1.191 harris41 5913: }
1.800 albertel 5914: foreach my $role (split(':',$domrole)) {
5915: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5916: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5917: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5918: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5919: return "refused:d:$crole&$cqual";
5920: }
5921: }
1.191 harris41 5922: }
1.800 albertel 5923: foreach my $role (split(':',$courole)) {
5924: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5925: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5926: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5927: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5928: return "refused:c:$crole&$cqual";
5929: }
5930: }
1.191 harris41 5931: }
1.620 albertel 5932: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5933: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5934: "rolesdef_$rolename=".
5935: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5936: return reply($command,$env{'user.home'});
1.12 www 5937: } else {
5938: return 'refused';
5939: }
1.105 harris41 5940: }
5941:
5942: # ---------------- Make a metadata query against the network of library servers
5943:
5944: sub metadata_query {
1.244 matthew 5945: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5946: my %rhash;
1.845 albertel 5947: my %libserv = &all_library();
1.244 matthew 5948: my @server_list = (defined($server_array) ? @$server_array
5949: : keys(%libserv) );
5950: for my $server (@server_list) {
1.118 harris41 5951: unless ($custom or $customshow) {
5952: my $reply=&reply("querysend:".&escape($query),$server);
5953: $rhash{$server}=$reply;
5954: }
5955: else {
5956: my $reply=&reply("querysend:".&escape($query).':'.
5957: &escape($custom).':'.&escape($customshow),
5958: $server);
5959: $rhash{$server}=$reply;
5960: }
1.112 harris41 5961: }
1.118 harris41 5962: return \%rhash;
1.240 www 5963: }
5964:
5965: # ----------------------------------------- Send log queries and wait for reply
5966:
5967: sub log_query {
5968: my ($uname,$udom,$query,%filters)=@_;
5969: my $uhome=&homeserver($uname,$udom);
5970: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5971: my $uhost=&hostname($uhome);
1.800 albertel 5972: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5973: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5974: $uhome);
1.479 albertel 5975: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5976: return get_query_reply($queryid);
5977: }
5978:
1.818 raeburn 5979: # -------------------------- Update MySQL table for portfolio file
5980:
5981: sub update_portfolio_table {
1.821 raeburn 5982: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5983: if ($group ne '') {
5984: $file_name =~s /^\Q$group\E//;
5985: }
1.818 raeburn 5986: my $homeserver = &homeserver($uname,$udom);
5987: my $queryid=
1.821 raeburn 5988: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5989: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5990: my $reply = &get_query_reply($queryid);
5991: return $reply;
5992: }
5993:
1.899 raeburn 5994: # -------------------------- Update MySQL allusers table
5995:
5996: sub update_allusers_table {
5997: my ($uname,$udom,$names) = @_;
5998: my $homeserver = &homeserver($uname,$udom);
5999: my $queryid=
6000: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6001: 'lastname='.&escape($names->{'lastname'}).'%%'.
6002: 'firstname='.&escape($names->{'firstname'}).'%%'.
6003: 'middlename='.&escape($names->{'middlename'}).'%%'.
6004: 'generation='.&escape($names->{'generation'}).'%%'.
6005: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6006: 'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4 raeburn 6007: return;
1.899 raeburn 6008: }
6009:
1.508 raeburn 6010: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6011:
6012: sub fetch_enrollment_query {
1.511 raeburn 6013: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6014: my $homeserver;
1.547 raeburn 6015: my $maxtries = 1;
1.508 raeburn 6016: if ($context eq 'automated') {
6017: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6018: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6019: } else {
6020: $homeserver = &homeserver($cnum,$dom);
6021: }
1.838 albertel 6022: my $host=&hostname($homeserver);
1.506 raeburn 6023: my $cmd = '';
1.1000 raeburn 6024: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6025: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6026: }
6027: $cmd =~ s/%%$//;
6028: $cmd = &escape($cmd);
6029: my $query = 'fetchenrollment';
1.620 albertel 6030: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6031: unless ($queryid=~/^\Q$host\E\_/) {
6032: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6033: return 'error: '.$queryid;
6034: }
1.506 raeburn 6035: my $reply = &get_query_reply($queryid);
1.547 raeburn 6036: my $tries = 1;
6037: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6038: $reply = &get_query_reply($queryid);
6039: $tries ++;
6040: }
1.526 raeburn 6041: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6042: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6043: } else {
1.901 albertel 6044: my @responses = split(/:/,$reply);
1.515 raeburn 6045: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6046: foreach my $line (@responses) {
6047: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6048: $$replyref{$key} = $value;
6049: }
6050: } else {
1.506 raeburn 6051: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 6052: foreach my $line (@responses) {
6053: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6054: $$replyref{$key} = $value;
6055: if ($value > 0) {
1.800 albertel 6056: foreach my $item (@{$$affiliatesref{$key}}) {
6057: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6058: my $destname = $pathname.'/'.$filename;
6059: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6060: if ($xml_classlist =~ /^error/) {
6061: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6062: } else {
1.506 raeburn 6063: if ( open(FILE,">$destname") ) {
6064: print FILE &unescape($xml_classlist);
6065: close(FILE);
1.526 raeburn 6066: } else {
6067: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6068: }
6069: }
6070: }
6071: }
6072: }
6073: }
6074: return 'ok';
6075: }
6076: return 'error';
6077: }
6078:
1.242 www 6079: sub get_query_reply {
6080: my $queryid=shift;
1.240 www 6081: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
6082: my $reply='';
6083: for (1..100) {
6084: sleep 2;
6085: if (-e $replyfile.'.end') {
1.448 albertel 6086: if (open(my $fh,$replyfile)) {
1.904 albertel 6087: $reply = join('',<$fh>);
6088: close($fh);
1.240 www 6089: } else { return 'error: reply_file_error'; }
1.242 www 6090: return &unescape($reply);
6091: }
1.240 www 6092: }
1.242 www 6093: return 'timeout:'.$queryid;
1.240 www 6094: }
6095:
6096: sub courselog_query {
1.241 www 6097: #
6098: # possible filters:
6099: # url: url or symb
6100: # username
6101: # domain
6102: # action: view, submit, grade
6103: # start: timestamp
6104: # end: timestamp
6105: #
1.240 www 6106: my (%filters)=@_;
1.620 albertel 6107: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6108: if ($filters{'url'}) {
6109: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6110: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6111: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6112: }
1.620 albertel 6113: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6114: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6115: return &log_query($cname,$cdom,'courselog',%filters);
6116: }
6117:
6118: sub userlog_query {
1.858 raeburn 6119: #
6120: # possible filters:
6121: # action: log check role
6122: # start: timestamp
6123: # end: timestamp
6124: #
1.240 www 6125: my ($uname,$udom,%filters)=@_;
6126: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6127: }
6128:
1.506 raeburn 6129: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6130:
6131: sub auto_run {
1.508 raeburn 6132: my ($cnum,$cdom) = @_;
1.876 raeburn 6133: my $response = 0;
6134: my $settings;
6135: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6136: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6137: $settings = $domconfig{'autoenroll'};
6138: if ($settings->{'run'} eq '1') {
6139: $response = 1;
6140: }
6141: } else {
1.934 raeburn 6142: my $homeserver;
6143: if (&is_course($cdom,$cnum)) {
6144: $homeserver = &homeserver($cnum,$cdom);
6145: } else {
6146: $homeserver = &domain($cdom,'primary');
6147: }
6148: if ($homeserver ne 'no_host') {
6149: $response = &reply('autorun:'.$cdom,$homeserver);
6150: }
1.876 raeburn 6151: }
1.506 raeburn 6152: return $response;
6153: }
1.776 albertel 6154:
1.506 raeburn 6155: sub auto_get_sections {
1.508 raeburn 6156: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6157: my $homeserver;
6158: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6159: $homeserver = &homeserver($cnum,$cdom);
6160: }
6161: if (!defined($homeserver)) {
6162: if ($cdom =~ /^$match_domain$/) {
6163: $homeserver = &domain($cdom,'primary');
6164: }
6165: }
6166: my @secs;
6167: if (defined($homeserver)) {
6168: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6169: unless ($response eq 'refused') {
6170: @secs = split(/:/,$response);
6171: }
1.506 raeburn 6172: }
6173: return @secs;
6174: }
1.776 albertel 6175:
1.506 raeburn 6176: sub auto_new_course {
1.1056.4.19 raeburn 6177: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6178: my $homeserver = &homeserver($cnum,$cdom);
1.1056.4.19 raeburn 6179: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6180: return $response;
6181: }
1.776 albertel 6182:
1.506 raeburn 6183: sub auto_validate_courseID {
1.508 raeburn 6184: my ($cnum,$cdom,$inst_course_id) = @_;
6185: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6186: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6187: return $response;
6188: }
1.776 albertel 6189:
1.1007 raeburn 6190: sub auto_validate_instcode {
1.1020 raeburn 6191: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6192: my ($homeserver,$response);
6193: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6194: $homeserver = &homeserver($cnum,$cdom);
6195: }
6196: if (!defined($homeserver)) {
6197: if ($cdom =~ /^$match_domain$/) {
6198: $homeserver = &domain($cdom,'primary');
6199: }
6200: }
1.1056.4.2 raeburn 6201: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6202: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6203: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6204: return ($outcome,$description);
1.1007 raeburn 6205: }
6206:
1.506 raeburn 6207: sub auto_create_password {
1.873 raeburn 6208: my ($cnum,$cdom,$authparam,$udom) = @_;
6209: my ($homeserver,$response);
1.506 raeburn 6210: my $create_passwd = 0;
6211: my $authchk = '';
1.873 raeburn 6212: if ($udom =~ /^$match_domain$/) {
6213: $homeserver = &domain($udom,'primary');
6214: }
6215: if ($homeserver eq '') {
6216: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6217: $homeserver = &homeserver($cnum,$cdom);
6218: }
6219: }
6220: if ($homeserver eq '') {
6221: $authchk = 'nodomain';
1.506 raeburn 6222: } else {
1.873 raeburn 6223: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6224: if ($response eq 'refused') {
6225: $authchk = 'refused';
6226: } else {
1.901 albertel 6227: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6228: }
1.506 raeburn 6229: }
6230: return ($authparam,$create_passwd,$authchk);
6231: }
6232:
1.706 raeburn 6233: sub auto_photo_permission {
6234: my ($cnum,$cdom,$students) = @_;
6235: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6236: my ($outcome,$perm_reqd,$conditions) =
6237: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6238: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6239: return (undef,undef);
6240: }
1.706 raeburn 6241: return ($outcome,$perm_reqd,$conditions);
6242: }
6243:
6244: sub auto_checkphotos {
6245: my ($uname,$udom,$pid) = @_;
6246: my $homeserver = &homeserver($uname,$udom);
6247: my ($result,$resulttype);
6248: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6249: &escape($uname).':'.&escape($pid),
6250: $homeserver));
1.709 albertel 6251: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6252: return (undef,undef);
6253: }
1.706 raeburn 6254: if ($outcome) {
6255: ($result,$resulttype) = split(/:/,$outcome);
6256: }
6257: return ($result,$resulttype);
6258: }
6259:
6260: sub auto_photochoice {
6261: my ($cnum,$cdom) = @_;
6262: my $homeserver = &homeserver($cnum,$cdom);
6263: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6264: &escape($cdom),
6265: $homeserver)));
1.709 albertel 6266: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6267: return (undef,undef);
6268: }
1.706 raeburn 6269: return ($update,$comment);
6270: }
6271:
6272: sub auto_photoupdate {
6273: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6274: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6275: my $host=&hostname($homeserver);
1.706 raeburn 6276: my $cmd = '';
6277: my $maxtries = 1;
1.800 albertel 6278: foreach my $affiliate (keys(%{$affiliatesref})) {
6279: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6280: }
6281: $cmd =~ s/%%$//;
6282: $cmd = &escape($cmd);
6283: my $query = 'institutionalphotos';
6284: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6285: unless ($queryid=~/^\Q$host\E\_/) {
6286: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6287: return 'error: '.$queryid;
6288: }
6289: my $reply = &get_query_reply($queryid);
6290: my $tries = 1;
6291: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6292: $reply = &get_query_reply($queryid);
6293: $tries ++;
6294: }
6295: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6296: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6297: } else {
6298: my @responses = split(/:/,$reply);
6299: my $outcome = shift(@responses);
6300: foreach my $item (@responses) {
6301: my ($key,$value) = split(/=/,$item);
6302: $$photo{$key} = $value;
6303: }
6304: return $outcome;
6305: }
6306: return 'error';
6307: }
6308:
1.521 raeburn 6309: sub auto_instcode_format {
1.793 albertel 6310: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6311: $cat_order) = @_;
1.521 raeburn 6312: my $courses = '';
1.772 raeburn 6313: my @homeservers;
1.521 raeburn 6314: if ($caller eq 'global') {
1.841 albertel 6315: my %servers = &get_servers($codedom,'library');
6316: foreach my $tryserver (keys(%servers)) {
6317: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6318: push(@homeservers,$tryserver);
6319: }
1.584 raeburn 6320: }
1.1022 raeburn 6321: } elsif ($caller eq 'requests') {
6322: if ($codedom =~ /^$match_domain$/) {
6323: my $chome = &domain($codedom,'primary');
6324: unless ($chome eq 'no_host') {
6325: push(@homeservers,$chome);
6326: }
6327: }
1.521 raeburn 6328: } else {
1.772 raeburn 6329: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6330: }
1.793 albertel 6331: foreach my $code (keys(%{$instcodes})) {
6332: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6333: }
6334: chop($courses);
1.772 raeburn 6335: my $ok_response = 0;
6336: my $response;
6337: while (@homeservers > 0 && $ok_response == 0) {
6338: my $server = shift(@homeservers);
6339: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6340: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6341: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6342: split(/:/,$response);
1.772 raeburn 6343: %{$codes} = (%{$codes},&str2hash($codes_str));
6344: push(@{$codetitles},&str2array($codetitles_str));
6345: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6346: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6347: $ok_response = 1;
6348: }
6349: }
6350: if ($ok_response) {
1.521 raeburn 6351: return 'ok';
1.772 raeburn 6352: } else {
6353: return $response;
1.521 raeburn 6354: }
6355: }
6356:
1.792 raeburn 6357: sub auto_instcode_defaults {
6358: my ($domain,$returnhash,$code_order) = @_;
6359: my @homeservers;
1.841 albertel 6360:
6361: my %servers = &get_servers($domain,'library');
6362: foreach my $tryserver (keys(%servers)) {
6363: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6364: push(@homeservers,$tryserver);
6365: }
1.792 raeburn 6366: }
1.841 albertel 6367:
1.792 raeburn 6368: my $response;
1.841 albertel 6369: foreach my $server (@homeservers) {
1.792 raeburn 6370: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6371: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6372:
6373: foreach my $pair (split(/\&/,$response)) {
6374: my ($name,$value)=split(/\=/,$pair);
6375: if ($name eq 'code_order') {
6376: @{$code_order} = split(/\&/,&unescape($value));
6377: } else {
6378: $returnhash->{&unescape($name)}=&unescape($value);
6379: }
6380: }
6381: return 'ok';
1.792 raeburn 6382: }
1.841 albertel 6383:
6384: return $response;
1.1003 raeburn 6385: }
6386:
6387: sub auto_possible_instcodes {
1.1007 raeburn 6388: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6389: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6390: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6391: return;
6392: }
1.1003 raeburn 6393: my (@homeservers,$uhome);
6394: if (defined(&domain($domain,'primary'))) {
6395: $uhome=&domain($domain,'primary');
6396: push(@homeservers,&domain($domain,'primary'));
6397: } else {
6398: my %servers = &get_servers($domain,'library');
6399: foreach my $tryserver (keys(%servers)) {
6400: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6401: push(@homeservers,$tryserver);
6402: }
6403: }
6404: }
6405: my $response;
6406: foreach my $server (@homeservers) {
6407: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6408: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6409: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6410: split(':',$response);
6411: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6412: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6413: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6414: my ($name,$value)=split('=',$item);
6415: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6416: }
6417: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6418: my ($name,$value)=split('=',$item);
6419: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6420: }
6421: return 'ok';
6422: }
6423: return $response;
6424: }
1.792 raeburn 6425:
1.1010 raeburn 6426: sub auto_courserequest_checks {
6427: my ($dom) = @_;
1.1020 raeburn 6428: my ($homeserver,%validations);
6429: if ($dom =~ /^$match_domain$/) {
6430: $homeserver = &domain($dom,'primary');
6431: }
6432: unless ($homeserver eq 'no_host') {
6433: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6434: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6435: my @items = split(/&/,$response);
6436: foreach my $item (@items) {
6437: my ($key,$value) = split('=',$item);
6438: $validations{&unescape($key)} = &thaw_unescape($value);
6439: }
6440: }
6441: }
1.1010 raeburn 6442: return %validations;
6443: }
6444:
1.1020 raeburn 6445: sub auto_courserequest_validation {
6446: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6447: my ($homeserver,$response);
6448: if ($dom =~ /^$match_domain$/) {
6449: $homeserver = &domain($dom,'primary');
6450: }
6451: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6452:
1.1020 raeburn 6453: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6454: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6455: ':'.&escape($instcode).':'.&escape($instseclist),
6456: $homeserver));
6457: }
6458: return $response;
6459: }
6460:
1.777 albertel 6461: sub auto_validate_class_sec {
1.918 raeburn 6462: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6463: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6464: my $ownerlist;
6465: if (ref($owners) eq 'ARRAY') {
6466: $ownerlist = join(',',@{$owners});
6467: } else {
6468: $ownerlist = $owners;
6469: }
1.773 raeburn 6470: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6471: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6472: return $response;
6473: }
6474:
1.679 raeburn 6475: # ------------------------------------------------------- Course Group routines
6476:
6477: sub get_coursegroups {
1.809 raeburn 6478: my ($cdom,$cnum,$group,$namespace) = @_;
6479: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6480: }
6481:
1.679 raeburn 6482: sub modify_coursegroup {
6483: my ($cdom,$cnum,$groupsettings) = @_;
6484: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6485: }
6486:
1.809 raeburn 6487: sub toggle_coursegroup_status {
6488: my ($cdom,$cnum,$group,$action) = @_;
6489: my ($from_namespace,$to_namespace);
6490: if ($action eq 'delete') {
6491: $from_namespace = 'coursegroups';
6492: $to_namespace = 'deleted_groups';
6493: } else {
6494: $from_namespace = 'deleted_groups';
6495: $to_namespace = 'coursegroups';
6496: }
6497: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6498: if (my $tmp = &error(%curr_group)) {
6499: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6500: return ('read error',$tmp);
6501: } else {
6502: my %savedsettings = %curr_group;
1.809 raeburn 6503: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6504: my $deloutcome;
6505: if ($result eq 'ok') {
1.809 raeburn 6506: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6507: } else {
6508: return ('write error',$result);
6509: }
6510: if ($deloutcome eq 'ok') {
6511: return 'ok';
6512: } else {
6513: return ('delete error',$deloutcome);
6514: }
6515: }
6516: }
6517:
1.679 raeburn 6518: sub modify_group_roles {
1.957 raeburn 6519: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6520: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6521: my $role = 'gr/'.&escape($userprivs);
6522: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6523: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6524: if ($result eq 'ok') {
6525: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6526: }
1.679 raeburn 6527: return $result;
6528: }
6529:
6530: sub modify_coursegroup_membership {
6531: my ($cdom,$cnum,$membership) = @_;
6532: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6533: return $result;
6534: }
6535:
1.682 raeburn 6536: sub get_active_groups {
6537: my ($udom,$uname,$cdom,$cnum) = @_;
6538: my $now = time;
6539: my %groups = ();
6540: foreach my $key (keys(%env)) {
1.811 albertel 6541: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6542: my ($start,$end) = split(/\./,$env{$key});
6543: if (($end!=0) && ($end<$now)) { next; }
6544: if (($start!=0) && ($start>$now)) { next; }
6545: if ($1 eq $cdom && $2 eq $cnum) {
6546: $groups{$3} = $env{$key} ;
6547: }
6548: }
6549: }
6550: return %groups;
6551: }
6552:
1.683 raeburn 6553: sub get_group_membership {
6554: my ($cdom,$cnum,$group) = @_;
6555: return(&dump('groupmembership',$cdom,$cnum,$group));
6556: }
6557:
6558: sub get_users_groups {
6559: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6560: my @usersgroups;
1.683 raeburn 6561: my $cachetime=1800;
6562:
6563: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6564: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6565: if (defined($cached)) {
1.734 albertel 6566: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6567: } else {
6568: $grouplist = '';
1.816 raeburn 6569: my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 6570: my $extra = &freeze_escape({'skipcheck' => 1});
6571: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6572: my $access_end = $env{'course.'.$courseid.
6573: '.default_enrollment_end_date'};
6574: my $now = time;
6575: foreach my $key (keys(%roleshash)) {
6576: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6577: my $group = $1;
6578: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6579: my $start = $2;
6580: my $end = $1;
6581: if ($start == -1) { next; } # deleted from group
6582: if (($start!=0) && ($start>$now)) { next; }
6583: if (($end!=0) && ($end<$now)) {
6584: if ($access_end && $access_end < $now) {
6585: if ($access_end - $end < 86400) {
6586: push(@usersgroups,$group);
1.733 raeburn 6587: }
6588: }
1.817 raeburn 6589: next;
1.733 raeburn 6590: }
1.817 raeburn 6591: push(@usersgroups,$group);
1.683 raeburn 6592: }
6593: }
6594: }
1.817 raeburn 6595: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6596: $grouplist = join(':',@usersgroups);
6597: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6598: }
1.733 raeburn 6599: return @usersgroups;
1.683 raeburn 6600: }
6601:
6602: sub devalidate_getgroups_cache {
6603: my ($udom,$uname,$cdom,$cnum)=@_;
6604: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6605:
1.683 raeburn 6606: my $hashid="$udom:$uname:$courseid";
6607: &devalidate_cache_new('getgroups',$hashid);
6608: }
6609:
1.12 www 6610: # ------------------------------------------------------------------ Plain Text
6611:
6612: sub plaintext {
1.988 raeburn 6613: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6614: if ($short =~ m{^cr/}) {
1.758 albertel 6615: return (split('/',$short))[-1];
6616: }
1.742 raeburn 6617: if (!defined($cid)) {
6618: $cid = $env{'request.course.id'};
6619: }
6620: my %rolenames = (
1.1008 raeburn 6621: Course => 'std',
6622: Community => 'alt1',
1.742 raeburn 6623: );
1.1037 raeburn 6624: if ($cid ne '') {
6625: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6626: unless ($forcedefault) {
6627: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6628: &Apache::lonlocal::mt_escape(\$roletext);
6629: return &Apache::lonlocal::mt($roletext);
6630: }
6631: }
6632: }
6633: if ((defined($type)) && (defined($rolenames{$type})) &&
6634: (defined($rolenames{$type})) &&
6635: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6636: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6637: } elsif ($cid ne '') {
6638: my $crstype = $env{'course.'.$cid.'.type'};
6639: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6640: (defined($prp{$short}{$rolenames{$crstype}}))) {
6641: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6642: }
1.742 raeburn 6643: }
1.1037 raeburn 6644: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6645: }
6646:
6647: # ----------------------------------------------------------------- Assign Role
6648:
6649: sub assignrole {
1.957 raeburn 6650: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6651: $context)=@_;
1.21 www 6652: my $mrole;
6653: if ($role =~ /^cr\//) {
1.393 www 6654: my $cwosec=$url;
1.811 albertel 6655: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6656: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6657: my $refused = 1;
6658: if ($context eq 'requestcourses') {
6659: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6660: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6661: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6662: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6663: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6664: if ($crsenv{'internal.courseowner'} eq
6665: $env{'user.name'}.':'.$env{'user.domain'}) {
6666: $refused = '';
6667: }
6668: }
6669: }
6670: }
6671: }
6672: if ($refused) {
6673: &logthis('Refused custom assignrole: '.
6674: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6675: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6676: return 'refused';
6677: }
1.104 www 6678: }
1.21 www 6679: $mrole='cr';
1.678 raeburn 6680: } elsif ($role =~ /^gr\//) {
6681: my $cwogrp=$url;
1.811 albertel 6682: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6683: unless (&allowed('mdg',$cwogrp)) {
6684: &logthis('Refused group assignrole: '.
6685: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6686: $env{'user.name'}.' at '.$env{'user.domain'});
6687: return 'refused';
6688: }
6689: $mrole='gr';
1.21 www 6690: } else {
1.82 www 6691: my $cwosec=$url;
1.811 albertel 6692: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6693: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6694: my $refused;
6695: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6696: if (!(&allowed('c'.$role,$url))) {
6697: $refused = 1;
6698: }
6699: } else {
6700: $refused = 1;
6701: }
1.947 raeburn 6702: if ($refused) {
1.1045 raeburn 6703: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6704: if (!$selfenroll && $context eq 'course') {
6705: my %crsenv;
6706: if ($role eq 'cc' || $role eq 'co') {
6707: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6708: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6709: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6710: if ($crsenv{'internal.courseowner'} eq
6711: $env{'user.name'}.':'.$env{'user.domain'}) {
6712: $refused = '';
6713: }
6714: }
6715: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6716: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6717: if ($crsenv{'internal.courseowner'} eq
6718: $env{'user.name'}.':'.$env{'user.domain'}) {
6719: $refused = '';
6720: }
6721: }
6722: }
6723: }
6724: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6725: $refused = '';
1.1017 raeburn 6726: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6727: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6728: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6729: my $wrongcc;
6730: if ($cnum =~ /^$match_community$/) {
6731: $wrongcc = 1 if ($role eq 'cc');
6732: } else {
6733: $wrongcc = 1 if ($role eq 'co');
6734: }
6735: unless ($wrongcc) {
6736: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6737: if ($crsenv{'internal.courseowner'} eq
6738: $env{'user.name'}.':'.$env{'user.domain'}) {
6739: $refused = '';
6740: }
1.1017 raeburn 6741: }
6742: }
6743: }
6744: if ($refused) {
1.947 raeburn 6745: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6746: ' '.$role.' '.$end.' '.$start.' by '.
6747: $env{'user.name'}.' at '.$env{'user.domain'});
6748: return 'refused';
6749: }
1.932 raeburn 6750: }
1.1056.4.30 raeburn 6751: } elsif ($role eq 'au') {
6752: if ($url ne '/'.$udom.'/') {
6753: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
6754: ' to assign author role for '.$uname.':'.$udom.
6755: ' in domain: '.$url.' refused (wrong domain).');
6756: return 'refused';
6757: }
1.104 www 6758: }
1.21 www 6759: $mrole=$role;
6760: }
1.620 albertel 6761: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6762: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6763: if ($end) { $command.='_'.$end; }
1.21 www 6764: if ($start) {
6765: if ($end) {
1.81 www 6766: $command.='_'.$start;
1.21 www 6767: } else {
1.81 www 6768: $command.='_0_'.$start;
1.21 www 6769: }
6770: }
1.739 raeburn 6771: my $origstart = $start;
6772: my $origend = $end;
1.957 raeburn 6773: my $delflag;
1.357 www 6774: # actually delete
6775: if ($deleteflag) {
1.373 www 6776: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6777: # modify command to delete the role
1.620 albertel 6778: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6779: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6780: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6781: # set start and finish to negative values for userrolelog
6782: $start=-1;
6783: $end=-1;
1.957 raeburn 6784: $delflag = 1;
1.357 www 6785: }
6786: }
6787: # send command
1.349 www 6788: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6789: # log new user role if status is ok
1.349 www 6790: if ($answer eq 'ok') {
1.663 raeburn 6791: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6792: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6793: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6794: unless ($role =~ /^gr/) {
6795: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6796: $origstart,$selfenroll,$context);
1.739 raeburn 6797: }
1.1053 raeburn 6798: if ($role eq 'cc') {
6799: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6800: }
1.349 www 6801: }
6802: return $answer;
1.169 harris41 6803: }
6804:
1.1053 raeburn 6805: sub autoupdate_coowners {
6806: my ($url,$end,$start,$uname,$udom) = @_;
6807: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6808: if (($cdom ne '') && ($cnum ne '')) {
6809: my $now = time;
6810: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6811: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6812: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6813: my $instcode = $coursehash{'internal.coursecode'};
6814: if ($instcode ne '') {
1.1056 raeburn 6815: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6816: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6817: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6818: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6819: if ($result eq 'valid') {
6820: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6821: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6822: push(@newcoowners,$coowner);
6823: }
6824: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6825: push(@newcoowners,$uname.':'.$udom);
6826: }
6827: @newcoowners = sort(@newcoowners);
6828: } else {
6829: push(@newcoowners,$uname.':'.$udom);
6830: }
6831: } else {
6832: if ($coursehash{'internal.co-owners'}) {
6833: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6834: unless ($coowner eq $uname.':'.$udom) {
6835: push(@newcoowners,$coowner);
6836: }
6837: }
6838: unless (@newcoowners > 0) {
6839: $delcoowners = 1;
6840: $coowners = '';
6841: }
6842: }
6843: }
6844: if (@newcoowners || $delcoowners) {
6845: &store_coowners($cdom,$cnum,$coursehash{'home'},
6846: $delcoowners,@newcoowners);
6847: }
6848: }
6849: }
6850: }
6851: }
6852: }
6853: }
6854:
6855: sub store_coowners {
6856: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6857: my $cid = $cdom.'_'.$cnum;
6858: my ($coowners,$delresult,$putresult);
6859: if (@newcoowners) {
6860: $coowners = join(',',@newcoowners);
6861: my %coownershash = (
6862: 'internal.co-owners' => $coowners,
6863: );
6864: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6865: if ($putresult eq 'ok') {
6866: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6867: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6868: }
6869: }
6870: }
6871: if ($delcoowners) {
6872: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6873: if ($delresult eq 'ok') {
6874: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6875: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6876: }
6877: }
6878: }
6879: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6880: my %crsinfo =
6881: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6882: if (ref($crsinfo{$cid}) eq 'HASH') {
6883: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6884: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6885: }
6886: }
6887: }
6888:
1.169 harris41 6889: # -------------------------------------------------- Modify user authentication
1.197 www 6890: # Overrides without validation
6891:
1.169 harris41 6892: sub modifyuserauth {
6893: my ($udom,$uname,$umode,$upass)=@_;
6894: my $uhome=&homeserver($uname,$udom);
1.197 www 6895: unless (&allowed('mau',$udom)) { return 'refused'; }
6896: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6897: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6898: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6899: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6900: &escape($upass),$uhome);
1.620 albertel 6901: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6902: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6903: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6904: &log($udom,,$uname,$uhome,
1.620 albertel 6905: 'Authentication changed by '.$env{'user.domain'}.', '.
6906: $env{'user.name'}.', '.$umode.
1.197 www 6907: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6908: unless ($reply eq 'ok') {
1.197 www 6909: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6910: return 'error: '.$reply;
6911: }
1.170 harris41 6912: return 'ok';
1.80 www 6913: }
6914:
1.81 www 6915: # --------------------------------------------------------------- Modify a user
1.80 www 6916:
1.81 www 6917: sub modifyuser {
1.206 matthew 6918: my ($udom, $uname, $uid,
6919: $umode, $upass, $first,
6920: $middle, $last, $gene,
1.1056.4.1 raeburn 6921: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6922: $udom= &LONCAPA::clean_domain($udom);
6923: $uname=&LONCAPA::clean_username($uname);
1.1056.4.1 raeburn 6924: my $showcandelete = 'none';
6925: if (ref($candelete) eq 'ARRAY') {
6926: if (@{$candelete} > 0) {
6927: $showcandelete = join(', ',@{$candelete});
6928: }
6929: }
1.81 www 6930: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6931: $umode.', '.$first.', '.$middle.', '.
1.1056.4.1 raeburn 6932: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6933: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6934: ' desiredhome not specified').
1.620 albertel 6935: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6936: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6937: my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4 raeburn 6938: my $newuser;
6939: if ($uhome eq 'no_host') {
6940: $newuser = 1;
6941: }
1.80 www 6942: # ----------------------------------------------------------------- Create User
1.406 albertel 6943: if (($uhome eq 'no_host') &&
6944: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6945: my $unhome='';
1.844 albertel 6946: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6947: $unhome = $desiredhome;
1.620 albertel 6948: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6949: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6950: } else { # load balancing routine for determining $unhome
1.81 www 6951: my $loadm=10000000;
1.841 albertel 6952: my %servers = &get_servers($udom,'library');
6953: foreach my $tryserver (keys(%servers)) {
6954: my $answer=reply('load',$tryserver);
6955: if (($answer=~/\d+/) && ($answer<$loadm)) {
6956: $loadm=$answer;
6957: $unhome=$tryserver;
6958: }
1.80 www 6959: }
6960: }
6961: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6962: return 'error: unable to find a home server for '.$uname.
6963: ' in domain '.$udom;
1.80 www 6964: }
6965: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6966: &escape($upass),$unhome);
6967: unless ($reply eq 'ok') {
6968: return 'error: '.$reply;
6969: }
1.230 stredwic 6970: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6971: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6972: return 'error: unable verify users home machine.';
1.80 www 6973: }
1.209 matthew 6974: } # End of creation of new user
1.80 www 6975: # ---------------------------------------------------------------------- Add ID
6976: if ($uid) {
6977: $uid=~tr/A-Z/a-z/;
6978: my %uidhash=&idrget($udom,$uname);
1.196 www 6979: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6980: && (!$forceid)) {
1.80 www 6981: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6982: return 'error: user id "'.$uid.'" does not match '.
6983: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6984: }
6985: } else {
6986: &idput($udom,($uname => $uid));
6987: }
6988: }
6989: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6990: my @tmp=&get('environment',
1.899 raeburn 6991: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6992: 'permanentemail','inststatus'],
1.134 albertel 6993: $udom,$uname);
1.1056.4.4 raeburn 6994: my (%names,%oldnames);
1.313 matthew 6995: if ($tmp[0] =~ m/^error:.*/) {
6996: %names=();
6997: } else {
6998: %names = @tmp;
1.1056.4.4 raeburn 6999: %oldnames = %names;
1.313 matthew 7000: }
1.1056.4.6 raeburn 7001: #
1.1056.4.1 raeburn 7002: # If name, email and/or uid are blank (e.g., because an uploaded file
7003: # of users did not contain them), do not overwrite existing values
7004: # unless field is in $candelete array ref.
7005: #
7006:
7007: my @fields = ('firstname','middlename','lastname','generation',
7008: 'permanentemail','id');
7009: my %newvalues;
7010: if (ref($candelete) eq 'ARRAY') {
7011: foreach my $field (@fields) {
7012: if (grep(/^\Q$field\E$/,@{$candelete})) {
7013: if ($field eq 'firstname') {
7014: $names{$field} = $first;
7015: } elsif ($field eq 'middlename') {
7016: $names{$field} = $middle;
7017: } elsif ($field eq 'lastname') {
7018: $names{$field} = $last;
7019: } elsif ($field eq 'generation') {
7020: $names{$field} = $gene;
7021: } elsif ($field eq 'permanentemail') {
7022: $names{$field} = $email;
7023: } elsif ($field eq 'id') {
7024: $names{$field} = $uid;
7025: }
7026: }
7027: }
7028: }
1.388 www 7029: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7030: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7031: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7032: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7033: if ($email) {
7034: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7035: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7036: }
1.899 raeburn 7037: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7038: if (defined($inststatus)) {
7039: $names{'inststatus'} = '';
7040: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7041: if (ref($usertypes) eq 'HASH') {
7042: my @okstatuses;
7043: foreach my $item (split(/:/,$inststatus)) {
7044: if (defined($usertypes->{$item})) {
7045: push(@okstatuses,$item);
7046: }
7047: }
7048: if (@okstatuses) {
7049: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7050: }
7051: }
7052: }
1.1056.4.4 raeburn 7053: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7054: $umode.', '.$first.', '.$middle.', '.
1.1056.4.4 raeburn 7055: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7056: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7057: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7058: } else {
7059: $logmsg .= ' during self creation';
7060: }
1.1056.4.4 raeburn 7061: my $changed;
7062: if ($newuser) {
7063: $changed = 1;
7064: } else {
7065: foreach my $field (@fields) {
7066: if ($names{$field} ne $oldnames{$field}) {
7067: $changed = 1;
7068: last;
7069: }
7070: }
7071: }
7072: unless ($changed) {
7073: $logmsg = 'No changes in user information needed for: '.$logmsg;
7074: &logthis($logmsg);
7075: return 'ok';
7076: }
7077: my $reply = &put('environment', \%names, $udom,$uname);
7078: if ($reply ne 'ok') {
7079: return 'error: '.$reply;
7080: }
1.1056.4.11 raeburn 7081: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7082: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7083: }
1.1056.4.4 raeburn 7084: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7085: &devalidate_cache_new('namescache',$uname.':'.$udom);
7086: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7087: &logthis($logmsg);
1.134 albertel 7088: return 'ok';
1.80 www 7089: }
7090:
1.81 www 7091: # -------------------------------------------------------------- Modify student
1.80 www 7092:
1.81 www 7093: sub modifystudent {
7094: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7095: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7096: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7097: if (!$cid) {
1.620 albertel 7098: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7099: return 'not_in_class';
7100: }
1.80 www 7101: }
7102: # --------------------------------------------------------------- Make the user
1.81 www 7103: my $reply=&modifyuser
1.209 matthew 7104: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7105: $desiredhome,$email,$inststatus);
1.80 www 7106: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7107: # This will cause &modify_student_enrollment to get the uid from the
7108: # students environment
7109: $uid = undef if (!$forceid);
1.455 albertel 7110: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7111: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7112: return $reply;
7113: }
7114:
7115: sub modify_student_enrollment {
1.957 raeburn 7116: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7117: my ($cdom,$cnum,$chome);
7118: if (!$cid) {
1.620 albertel 7119: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7120: return 'not_in_class';
7121: }
1.620 albertel 7122: $cdom=$env{'course.'.$cid.'.domain'};
7123: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7124: } else {
7125: ($cdom,$cnum)=split(/_/,$cid);
7126: }
1.620 albertel 7127: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7128: if (!$chome) {
1.457 raeburn 7129: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7130: }
1.455 albertel 7131: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7132: # Make sure the user exists
1.81 www 7133: my $uhome=&homeserver($uname,$udom);
7134: if (($uhome eq '') || ($uhome eq 'no_host')) {
7135: return 'error: no such user';
7136: }
1.297 matthew 7137: # Get student data if we were not given enough information
7138: if (!defined($first) || $first eq '' ||
7139: !defined($last) || $last eq '' ||
7140: !defined($uid) || $uid eq '' ||
7141: !defined($middle) || $middle eq '' ||
7142: !defined($gene) || $gene eq '') {
1.294 matthew 7143: # They did not supply us with enough data to enroll the student, so
7144: # we need to pick up more information.
1.297 matthew 7145: my %tmp = &get('environment',
1.294 matthew 7146: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7147: ,$udom,$uname);
7148:
1.800 albertel 7149: #foreach my $key (keys(%tmp)) {
7150: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7151: #}
1.294 matthew 7152: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7153: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7154: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7155: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7156: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7157: }
1.556 albertel 7158: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7159: my $reply=cput('classlist',
7160: {"$uname:$udom" =>
1.515 raeburn 7161: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7162: $cdom,$cnum);
1.81 www 7163: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7164: return 'error: '.$reply;
1.652 albertel 7165: } else {
7166: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7167: }
1.297 matthew 7168: # Add student role to user
1.83 www 7169: my $uurl='/'.$cid;
1.81 www 7170: $uurl=~s/\_/\//g;
7171: if ($usec) {
7172: $uurl.='/'.$usec;
7173: }
1.957 raeburn 7174: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7175: }
7176:
1.556 albertel 7177: sub format_name {
7178: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7179: my $name;
7180: if ($first ne 'lastname') {
7181: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7182: } else {
7183: if ($lastname=~/\S/) {
7184: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7185: $name=~s/\s+,/,/;
7186: } else {
7187: $name.= $firstname.' '.$middlename.' '.$generation;
7188: }
7189: }
7190: $name=~s/^\s+//;
7191: $name=~s/\s+$//;
7192: $name=~s/\s+/ /g;
7193: return $name;
7194: }
7195:
1.84 www 7196: # ------------------------------------------------- Write to course preferences
7197:
7198: sub writecoursepref {
7199: my ($courseid,%prefs)=@_;
7200: $courseid=~s/^\///;
7201: $courseid=~s/\_/\//g;
7202: my ($cdomain,$cnum)=split(/\//,$courseid);
7203: my $chome=homeserver($cnum,$cdomain);
7204: if (($chome eq '') || ($chome eq 'no_host')) {
7205: return 'error: no such course';
7206: }
7207: my $cstring='';
1.800 albertel 7208: foreach my $pref (keys(%prefs)) {
7209: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7210: }
1.84 www 7211: $cstring=~s/\&$//;
7212: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7213: }
7214:
7215: # ---------------------------------------------------------- Make/modify course
7216:
7217: sub createcourse {
1.741 raeburn 7218: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7219: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7220: $url=&declutter($url);
7221: my $cid='';
1.1028 raeburn 7222: if ($context eq 'requestcourses') {
7223: my $can_create = 0;
7224: my ($ownername,$ownerdom) = split(':',$course_owner);
7225: if ($udom eq $ownerdom) {
7226: if (&usertools_access($ownername,$ownerdom,$category,undef,
7227: $context)) {
7228: $can_create = 1;
7229: }
7230: } else {
7231: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7232: $category);
7233: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7234: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7235: if (@curr > 0) {
7236: my @options = qw(approval validate autolimit);
7237: my $optregex = join('|',@options);
7238: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7239: $can_create = 1;
7240: }
7241: }
7242: }
7243: }
7244: if ($can_create) {
7245: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7246: unless (&allowed('ccc',$udom)) {
7247: return 'refused';
7248: }
1.1017 raeburn 7249: }
7250: } else {
7251: return 'refused';
7252: }
1.1028 raeburn 7253: } elsif (!&allowed('ccc',$udom)) {
7254: return 'refused';
1.84 www 7255: }
1.1011 raeburn 7256: # --------------------------------------------------------------- Get Unique ID
7257: my $uname;
7258: if ($cnum =~ /^$match_courseid$/) {
7259: my $chome=&homeserver($cnum,$udom,'true');
7260: if (($chome eq '') || ($chome eq 'no_host')) {
7261: $uname = $cnum;
7262: } else {
1.1038 raeburn 7263: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7264: }
7265: } else {
1.1038 raeburn 7266: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7267: }
7268: return $uname if ($uname =~ /^error/);
7269: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7270: if (!defined($course_server)) {
7271: if (defined(&domain($udom,'primary'))) {
7272: $course_server = &domain($udom,'primary');
7273: } else {
7274: $course_server = $env{'user.home'};
7275: }
7276: }
7277: my %host_servers =
7278: &Apache::lonnet::get_servers($udom,'library');
7279: unless ($host_servers{$course_server}) {
7280: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7281: }
1.84 www 7282: # ------------------------------------------------------------- Make the course
7283: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7284: $course_server);
1.84 www 7285: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7286: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7287: if (($uhome eq '') || ($uhome eq 'no_host')) {
7288: return 'error: no such course';
7289: }
1.271 www 7290: # ----------------------------------------------------------------- Course made
1.516 raeburn 7291: # log existence
1.1029 raeburn 7292: my $now = time;
1.918 raeburn 7293: my $newcourse = {
7294: $udom.'_'.$uname => {
1.921 raeburn 7295: description => $description,
7296: inst_code => $inst_code,
7297: owner => $course_owner,
7298: type => $crstype,
1.1029 raeburn 7299: creator => $env{'user.name'}.':'.
7300: $env{'user.domain'},
7301: created => $now,
7302: context => $context,
1.918 raeburn 7303: },
7304: };
1.921 raeburn 7305: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7306: # set toplevel url
1.271 www 7307: my $topurl=$url;
7308: unless ($nonstandard) {
7309: # ------------------------------------------ For standard courses, make top url
7310: my $mapurl=&clutter($url);
1.278 www 7311: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7312: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7313: <map>
7314: <resource id="1" type="start"></resource>
7315: <resource id="2" src="$mapurl"></resource>
7316: <resource id="3" type="finish"></resource>
7317: <link index="1" from="1" to="2"></link>
7318: <link index="2" from="2" to="3"></link>
7319: </map>
7320: ENDINITMAP
7321: $topurl=&declutter(
1.638 albertel 7322: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7323: );
7324: }
7325: # ----------------------------------------------------------- Write preferences
1.84 www 7326: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7327: ('description' => $description,
7328: 'url' => $topurl,
7329: 'internal.creator' => $env{'user.name'}.':'.
7330: $env{'user.domain'},
7331: 'internal.created' => $now,
7332: 'internal.creationcontext' => $context)
7333: );
1.84 www 7334: return '/'.$udom.'/'.$uname;
7335: }
7336:
1.1011 raeburn 7337: # ------------------------------------------------------------------- Create ID
7338: sub generate_coursenum {
1.1038 raeburn 7339: my ($udom,$crstype) = @_;
1.1011 raeburn 7340: my $domdesc = &domain($udom);
7341: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7342: my $first;
7343: if ($crstype eq 'Community') {
7344: $first = '0';
7345: } else {
7346: $first = int(1+rand(9));
7347: }
7348: my $uname=$first.
1.1011 raeburn 7349: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7350: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7351: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7352: # ----------------------------------------------- Make sure that does not exist
7353: my $uhome=&homeserver($uname,$udom,'true');
7354: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7355: if ($crstype eq 'Community') {
7356: $first = '0';
7357: } else {
7358: $first = int(1+rand(9));
7359: }
7360: $uname=$first.
1.1011 raeburn 7361: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7362: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7363: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7364: $uhome=&homeserver($uname,$udom,'true');
7365: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7366: return 'error: unable to generate unique course-ID';
7367: }
7368: }
7369: return $uname;
7370: }
7371:
1.813 albertel 7372: sub is_course {
7373: my ($cdom,$cnum) = @_;
7374: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7375: undef,'.');
1.813 albertel 7376: if (exists($courses{$cdom.'_'.$cnum})) {
7377: return 1;
7378: }
7379: return 0;
7380: }
7381:
1.1015 raeburn 7382: sub store_userdata {
7383: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7384: my $result;
1.1016 raeburn 7385: if ($datakey ne '') {
1.1013 raeburn 7386: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7387: if ($udom eq '' || $uname eq '') {
7388: $udom = $env{'user.domain'};
7389: $uname = $env{'user.name'};
7390: }
7391: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7392: if (($uhome eq '') || ($uhome eq 'no_host')) {
7393: $result = 'error: no_host';
7394: } else {
7395: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7396: $storehash->{'host'} = $perlvar{'lonHostID'};
7397:
7398: my $namevalue='';
7399: foreach my $key (keys(%{$storehash})) {
7400: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7401: }
7402: $namevalue=~s/\&$//;
1.1056.4.24 raeburn 7403: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7404: $namevalue,$uhome);
1.1013 raeburn 7405: }
7406: } else {
7407: $result = 'error: data to store was not a hash reference';
7408: }
7409: } else {
7410: $result= 'error: invalid requestkey';
7411: }
7412: return $result;
7413: }
7414:
1.21 www 7415: # ---------------------------------------------------------- Assign Custom Role
7416:
7417: sub assigncustomrole {
1.957 raeburn 7418: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7419: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7420: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7421: }
7422:
7423: # ----------------------------------------------------------------- Revoke Role
7424:
7425: sub revokerole {
1.957 raeburn 7426: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7427: my $now=time;
1.965 raeburn 7428: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7429: }
7430:
7431: # ---------------------------------------------------------- Revoke Custom Role
7432:
7433: sub revokecustomrole {
1.957 raeburn 7434: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7435: my $now=time;
1.357 www 7436: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7437: $deleteflag,$selfenroll,$context);
1.17 www 7438: }
7439:
1.533 banghart 7440: # ------------------------------------------------------------ Disk usage
1.535 albertel 7441: sub diskusage {
1.955 raeburn 7442: my ($udom,$uname,$directorypath,$getpropath)=@_;
7443: $directorypath =~ s/\/$//;
7444: my $listing=&reply('du2:'.&escape($directorypath).':'
7445: .&escape($getpropath).':'.&escape($uname).':'
7446: .&escape($udom),homeserver($uname,$udom));
7447: if ($listing eq 'unknown_cmd') {
7448: if ($getpropath) {
7449: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7450: }
7451: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7452: }
1.514 albertel 7453: return $listing;
1.512 banghart 7454: }
7455:
1.566 banghart 7456: sub is_locked {
1.1056.4.17 raeburn 7457: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7458: my @check;
7459: my $is_locked;
1.1056.4.14 raeburn 7460: push(@check,$file_name);
1.613 albertel 7461: my %locked = &get('file_permissions',\@check,
1.620 albertel 7462: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7463: my ($tmp)=keys(%locked);
7464: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7465:
1.566 banghart 7466: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7467: $is_locked = 'false';
7468: foreach my $entry (@{$locked{$file_name}}) {
1.1056.4.17 raeburn 7469: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7470: $is_locked = 'true';
1.1056.4.17 raeburn 7471: if (ref($which) eq 'ARRAY') {
7472: push(@{$which},$entry);
7473: } else {
7474: last;
7475: }
1.745 raeburn 7476: }
7477: }
1.566 banghart 7478: } else {
7479: $is_locked = 'false';
7480: }
1.1056.4.14 raeburn 7481: return $is_locked;
1.566 banghart 7482: }
7483:
1.759 albertel 7484: sub declutter_portfile {
7485: my ($file) = @_;
1.833 albertel 7486: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7487: return $file;
7488: }
7489:
1.559 banghart 7490: # ------------------------------------------------------------- Mark as Read Only
7491:
7492: sub mark_as_readonly {
7493: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7494: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7495: my ($tmp)=keys(%current_permissions);
7496: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7497: foreach my $file (@{$files}) {
1.759 albertel 7498: $file = &declutter_portfile($file);
1.561 banghart 7499: push(@{$current_permissions{$file}},$what);
1.559 banghart 7500: }
1.613 albertel 7501: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7502: return;
7503: }
7504:
1.572 banghart 7505: # ------------------------------------------------------------Save Selected Files
7506:
7507: sub save_selected_files {
7508: my ($user, $path, @files) = @_;
7509: my $filename = $user."savedfiles";
1.573 banghart 7510: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7511: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7512: foreach my $file (@files) {
1.620 albertel 7513: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7514: }
7515: foreach my $file (@other_files) {
1.574 banghart 7516: print (OUT $file."\n");
1.572 banghart 7517: }
1.574 banghart 7518: close (OUT);
1.572 banghart 7519: return 'ok';
7520: }
7521:
1.574 banghart 7522: sub clear_selected_files {
7523: my ($user) = @_;
7524: my $filename = $user."savedfiles";
7525: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7526: print (OUT undef);
7527: close (OUT);
7528: return ("ok");
7529: }
7530:
1.572 banghart 7531: sub files_in_path {
7532: my ($user, $path) = @_;
7533: my $filename = $user."savedfiles";
7534: my %return_files;
1.574 banghart 7535: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7536: while (my $line_in = <IN>) {
1.574 banghart 7537: chomp ($line_in);
7538: my @paths_and_file = split (m!/!, $line_in);
7539: my $file_part = pop (@paths_and_file);
7540: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7541: $path_part.='/';
7542: my $path_and_file = $path_part.$file_part;
7543: if ($path_part eq $path) {
7544: $return_files{$file_part}= 'selected';
7545: }
7546: }
1.574 banghart 7547: close (IN);
7548: return (\%return_files);
1.572 banghart 7549: }
7550:
7551: # called in portfolio select mode, to show files selected NOT in current directory
7552: sub files_not_in_path {
7553: my ($user, $path) = @_;
7554: my $filename = $user."savedfiles";
7555: my @return_files;
7556: my $path_part;
1.800 albertel 7557: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7558: while (my $line = <IN>) {
1.572 banghart 7559: #ok, I know it's clunky, but I want it to work
1.800 albertel 7560: my @paths_and_file = split(m|/|, $line);
7561: my $file_part = pop(@paths_and_file);
7562: chomp($file_part);
7563: my $path_part = join('/', @paths_and_file);
1.572 banghart 7564: $path_part .= '/';
7565: my $path_and_file = $path_part.$file_part;
7566: if ($path_part ne $path) {
1.800 albertel 7567: push(@return_files, ($path_and_file));
1.572 banghart 7568: }
7569: }
1.800 albertel 7570: close(OUT);
1.574 banghart 7571: return (@return_files);
1.572 banghart 7572: }
7573:
1.745 raeburn 7574: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7575:
1.745 raeburn 7576: sub get_portfile_permissions {
7577: my ($domain,$user) = @_;
1.613 albertel 7578: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7579: my ($tmp)=keys(%current_permissions);
7580: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7581: return \%current_permissions;
7582: }
7583:
7584: #---------------------------------------------Get portfolio file access controls
7585:
1.749 raeburn 7586: sub get_access_controls {
1.745 raeburn 7587: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7588: my %access;
7589: my $real_file = $file;
7590: $file =~ s/\.meta$//;
1.745 raeburn 7591: if (defined($file)) {
1.749 raeburn 7592: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7593: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7594: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7595: }
7596: }
1.745 raeburn 7597: } else {
1.749 raeburn 7598: foreach my $key (keys(%{$current_permissions})) {
7599: if ($key =~ /\0accesscontrol$/) {
7600: if (defined($group)) {
7601: if ($key !~ m-^\Q$group\E/-) {
7602: next;
7603: }
7604: }
7605: my ($fullpath) = split(/\0/,$key);
7606: if (ref($$current_permissions{$key}) eq 'HASH') {
7607: foreach my $control (keys(%{$$current_permissions{$key}})) {
7608: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7609: }
7610: }
7611: }
7612: }
7613: }
7614: return %access;
7615: }
7616:
7617: sub modify_access_controls {
7618: my ($file_name,$changes,$domain,$user)=@_;
7619: my ($outcome,$deloutcome);
7620: my %store_permissions;
7621: my %new_values;
7622: my %new_control;
7623: my %translation;
7624: my @deletions = ();
7625: my $now = time;
7626: if (exists($$changes{'activate'})) {
7627: if (ref($$changes{'activate'}) eq 'HASH') {
7628: my @newitems = sort(keys(%{$$changes{'activate'}}));
7629: my $numnew = scalar(@newitems);
7630: for (my $i=0; $i<$numnew; $i++) {
7631: my $newkey = $newitems[$i];
7632: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7633: if ($newkey =~ /^\d+:/) {
7634: $newkey =~ s/^(\d+)/$newid/;
7635: $translation{$1} = $newid;
7636: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7637: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7638: $translation{$1} = $newid;
7639: }
1.749 raeburn 7640: $new_values{$file_name."\0".$newkey} =
7641: $$changes{'activate'}{$newitems[$i]};
7642: $new_control{$newkey} = $now;
7643: }
7644: }
7645: }
7646: my %todelete;
7647: my %changed_items;
7648: foreach my $action ('delete','update') {
7649: if (exists($$changes{$action})) {
7650: if (ref($$changes{$action}) eq 'HASH') {
7651: foreach my $key (keys(%{$$changes{$action}})) {
7652: my ($itemnum) = ($key =~ /^([^:]+):/);
7653: if ($action eq 'delete') {
7654: $todelete{$itemnum} = 1;
7655: } else {
7656: $changed_items{$itemnum} = $key;
7657: }
7658: }
1.745 raeburn 7659: }
7660: }
1.749 raeburn 7661: }
7662: # get lock on access controls for file.
7663: my $lockhash = {
7664: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7665: ':'.$env{'user.domain'},
7666: };
7667: my $tries = 0;
7668: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7669:
7670: while (($gotlock ne 'ok') && $tries <3) {
7671: $tries ++;
7672: sleep 1;
7673: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7674: }
7675: if ($gotlock eq 'ok') {
7676: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7677: my ($tmp)=keys(%curr_permissions);
7678: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7679: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7680: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7681: if (ref($curr_controls) eq 'HASH') {
7682: foreach my $control_item (keys(%{$curr_controls})) {
7683: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7684: if (defined($todelete{$itemnum})) {
7685: push(@deletions,$file_name."\0".$control_item);
7686: } else {
7687: if (defined($changed_items{$itemnum})) {
7688: $new_control{$changed_items{$itemnum}} = $now;
7689: push(@deletions,$file_name."\0".$control_item);
7690: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7691: } else {
7692: $new_control{$control_item} = $$curr_controls{$control_item};
7693: }
7694: }
1.745 raeburn 7695: }
7696: }
7697: }
1.970 raeburn 7698: my ($group);
7699: if (&is_course($domain,$user)) {
7700: ($group,my $file) = split(/\//,$file_name,2);
7701: }
1.749 raeburn 7702: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7703: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7704: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7705: # remove lock
7706: my @del_lock = ($file_name."\0".'locked_access_records');
7707: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7708: my $sqlresult =
1.970 raeburn 7709: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7710: $group);
1.749 raeburn 7711: } else {
7712: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7713: }
1.749 raeburn 7714: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7715: }
7716:
1.827 raeburn 7717: sub make_public_indefinitely {
7718: my ($requrl) = @_;
7719: my $now = time;
7720: my $action = 'activate';
7721: my $aclnum = 0;
7722: if (&is_portfolio_url($requrl)) {
7723: my (undef,$udom,$unum,$file_name,$group) =
7724: &parse_portfolio_url($requrl);
7725: my $current_perms = &get_portfile_permissions($udom,$unum);
7726: my %access_controls = &get_access_controls($current_perms,
7727: $group,$file_name);
7728: foreach my $key (keys(%{$access_controls{$file_name}})) {
7729: my ($num,$scope,$end,$start) =
7730: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7731: if ($scope eq 'public') {
7732: if ($start <= $now && $end == 0) {
7733: $action = 'none';
7734: } else {
7735: $action = 'update';
7736: $aclnum = $num;
7737: }
7738: last;
7739: }
7740: }
7741: if ($action eq 'none') {
7742: return 'ok';
7743: } else {
7744: my %changes;
7745: my $newend = 0;
7746: my $newstart = $now;
7747: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7748: $changes{$action}{$newkey} = {
7749: type => 'public',
7750: time => {
7751: start => $newstart,
7752: end => $newend,
7753: },
7754: };
7755: my ($outcome,$deloutcome,$new_values,$translation) =
7756: &modify_access_controls($file_name,\%changes,$udom,$unum);
7757: return $outcome;
7758: }
7759: } else {
7760: return 'invalid';
7761: }
7762: }
7763:
1.745 raeburn 7764: #------------------------------------------------------Get Marked as Read Only
7765:
7766: sub get_marked_as_readonly {
7767: my ($domain,$user,$what,$group) = @_;
7768: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7769: my @readonly_files;
1.629 banghart 7770: my $cmp1=$what;
7771: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7772: while (my ($file_name,$value) = each(%{$current_permissions})) {
7773: if (defined($group)) {
7774: if ($file_name !~ m-^\Q$group\E/-) {
7775: next;
7776: }
7777: }
1.561 banghart 7778: if (ref($value) eq "ARRAY"){
7779: foreach my $stored_what (@{$value}) {
1.629 banghart 7780: my $cmp2=$stored_what;
1.759 albertel 7781: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7782: $cmp2=join('',@{$stored_what});
1.745 raeburn 7783: }
1.629 banghart 7784: if ($cmp1 eq $cmp2) {
1.561 banghart 7785: push(@readonly_files, $file_name);
1.745 raeburn 7786: last;
1.563 banghart 7787: } elsif (!defined($what)) {
7788: push(@readonly_files, $file_name);
1.745 raeburn 7789: last;
1.561 banghart 7790: }
7791: }
1.745 raeburn 7792: }
1.561 banghart 7793: }
7794: return @readonly_files;
7795: }
1.577 banghart 7796: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7797:
1.577 banghart 7798: sub get_marked_as_readonly_hash {
1.745 raeburn 7799: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7800: my %readonly_files;
1.745 raeburn 7801: while (my ($file_name,$value) = each(%{$current_permissions})) {
7802: if (defined($group)) {
7803: if ($file_name !~ m-^\Q$group\E/-) {
7804: next;
7805: }
7806: }
1.577 banghart 7807: if (ref($value) eq "ARRAY"){
7808: foreach my $stored_what (@{$value}) {
1.745 raeburn 7809: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7810: foreach my $lock_descriptor(@{$stored_what}) {
7811: if ($lock_descriptor eq 'graded') {
7812: $readonly_files{$file_name} = 'graded';
7813: } elsif ($lock_descriptor eq 'handback') {
7814: $readonly_files{$file_name} = 'handback';
7815: } else {
7816: if (!exists($readonly_files{$file_name})) {
7817: $readonly_files{$file_name} = 'locked';
7818: }
7819: }
1.745 raeburn 7820: }
1.750 banghart 7821: }
1.577 banghart 7822: }
7823: }
7824: }
7825: return %readonly_files;
7826: }
1.559 banghart 7827: # ------------------------------------------------------------ Unmark as Read Only
7828:
7829: sub unmark_as_readonly {
1.629 banghart 7830: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7831: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7832: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7833: $file_name = &declutter_portfile($file_name);
1.634 albertel 7834: my $symb_crs = $what;
7835: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7836: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7837: my ($tmp)=keys(%current_permissions);
7838: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7839: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7840: foreach my $file (@readonly_files) {
1.759 albertel 7841: my $clean_file = &declutter_portfile($file);
7842: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7843: my $current_locks = $current_permissions{$file};
1.563 banghart 7844: my @new_locks;
7845: my @del_keys;
7846: if (ref($current_locks) eq "ARRAY"){
7847: foreach my $locker (@{$current_locks}) {
1.632 albertel 7848: my $compare=$locker;
1.749 raeburn 7849: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7850: $compare=join('',@{$locker});
1.746 raeburn 7851: if ($compare ne $symb_crs) {
7852: push(@new_locks, $locker);
7853: }
1.563 banghart 7854: }
7855: }
1.650 albertel 7856: if (scalar(@new_locks) > 0) {
1.563 banghart 7857: $current_permissions{$file} = \@new_locks;
7858: } else {
7859: push(@del_keys, $file);
1.613 albertel 7860: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7861: delete($current_permissions{$file});
1.563 banghart 7862: }
7863: }
1.561 banghart 7864: }
1.613 albertel 7865: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7866: return;
7867: }
1.512 banghart 7868:
1.17 www 7869: # ------------------------------------------------------------ Directory lister
7870:
7871: sub dirlist {
1.955 raeburn 7872: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7873: $uri=~s/^\///;
7874: $uri=~s/\/$//;
1.253 stredwic 7875: my ($udom, $uname);
1.955 raeburn 7876: if ($getuserdir) {
1.253 stredwic 7877: $udom = $userdomain;
7878: $uname = $username;
1.955 raeburn 7879: } else {
7880: (undef,$udom,$uname)=split(/\//,$uri);
7881: if(defined($userdomain)) {
7882: $udom = $userdomain;
7883: }
7884: if(defined($username)) {
7885: $uname = $username;
7886: }
1.253 stredwic 7887: }
1.955 raeburn 7888: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7889:
1.955 raeburn 7890: $dirRoot = $perlvar{'lonDocRoot'};
7891: if (defined($getpropath)) {
7892: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7893: $dirRoot =~ s/\/$//;
1.955 raeburn 7894: } elsif (defined($getuserdir)) {
7895: my $subdir=$uname.'__';
7896: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7897: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7898: ."/$udom/$subdir/$uname";
7899: } elsif (defined($alternateRoot)) {
7900: $dirRoot = $alternateRoot;
1.751 banghart 7901: }
1.253 stredwic 7902:
7903: if($udom) {
7904: if($uname) {
1.955 raeburn 7905: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7906: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7907: .':'.&escape($uname).':'.&escape($udom),
7908: &homeserver($uname,$udom));
7909: if ($listing eq 'unknown_cmd') {
7910: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7911: &homeserver($uname,$udom));
7912: } else {
7913: @listing_results = map { &unescape($_); } split(/:/,$listing);
7914: }
1.605 matthew 7915: if ($listing eq 'unknown_cmd') {
1.800 albertel 7916: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7917: &homeserver($uname,$udom));
1.605 matthew 7918: @listing_results = split(/:/,$listing);
7919: } else {
7920: @listing_results = map { &unescape($_); } split(/:/,$listing);
7921: }
7922: return @listing_results;
1.955 raeburn 7923: } elsif(!$alternateRoot) {
1.800 albertel 7924: my %allusers;
1.841 albertel 7925: my %servers = &get_servers($udom,'library');
1.955 raeburn 7926: foreach my $tryserver (keys(%servers)) {
7927: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7928: &escape($udom),$tryserver);
7929: if ($listing eq 'unknown_cmd') {
7930: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7931: $udom, $tryserver);
7932: } else {
7933: @listing_results = map { &unescape($_); } split(/:/,$listing);
7934: }
1.841 albertel 7935: if ($listing eq 'unknown_cmd') {
7936: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7937: $udom, $tryserver);
7938: @listing_results = split(/:/,$listing);
7939: } else {
7940: @listing_results =
7941: map { &unescape($_); } split(/:/,$listing);
7942: }
7943: if ($listing_results[0] ne 'no_such_dir' &&
7944: $listing_results[0] ne 'empty' &&
7945: $listing_results[0] ne 'con_lost') {
7946: foreach my $line (@listing_results) {
7947: my ($entry) = split(/&/,$line,2);
7948: $allusers{$entry} = 1;
7949: }
7950: }
1.253 stredwic 7951: }
7952: my $alluserstr='';
1.800 albertel 7953: foreach my $user (sort(keys(%allusers))) {
7954: $alluserstr.=$user.'&user:';
1.253 stredwic 7955: }
7956: $alluserstr=~s/:$//;
7957: return split(/:/,$alluserstr);
7958: } else {
1.800 albertel 7959: return ('missing user name');
1.253 stredwic 7960: }
1.955 raeburn 7961: } elsif(!defined($getpropath)) {
1.841 albertel 7962: my @all_domains = sort(&all_domains());
1.955 raeburn 7963: foreach my $domain (@all_domains) {
7964: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7965: }
7966: return @all_domains;
7967: } else {
1.800 albertel 7968: return ('missing domain');
1.275 stredwic 7969: }
7970: }
7971:
7972: # --------------------------------------------- GetFileTimestamp
7973: # This function utilizes dirlist and returns the date stamp for
7974: # when it was last modified. It will also return an error of -1
7975: # if an error occurs
7976:
7977: sub GetFileTimestamp {
1.955 raeburn 7978: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7979: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7980: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7981: my ($fileStat) =
7982: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7983: undef,$getuserdir);
1.275 stredwic 7984: my @stats = split('&', $fileStat);
7985: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7986: # @stats contains first the filename, then the stat output
7987: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7988: } else {
7989: return -1;
1.253 stredwic 7990: }
1.26 www 7991: }
7992:
1.712 albertel 7993: sub stat_file {
7994: my ($uri) = @_;
1.787 albertel 7995: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7996:
1.955 raeburn 7997: my ($udom,$uname,$file);
1.712 albertel 7998: if ($uri =~ m-^/(uploaded|editupload)/-) {
7999: ($udom,$uname,$file) =
1.811 albertel 8000: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8001: $file = 'userfiles/'.$file;
8002: }
8003: if ($uri =~ m-^/res/-) {
8004: ($udom,$uname) =
1.807 albertel 8005: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8006: $file = $uri;
8007: }
8008:
8009: if (!$udom || !$uname || !$file) {
8010: # unable to handle the uri
8011: return ();
8012: }
1.956 raeburn 8013: my $getpropath;
8014: if ($file =~ /^userfiles\//) {
8015: $getpropath = 1;
8016: }
1.955 raeburn 8017: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 8018: my @stats = split('&', $result);
1.721 banghart 8019:
1.712 albertel 8020: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
8021: shift(@stats); #filename is first
8022: return @stats;
8023: }
8024: return ();
8025: }
8026:
1.26 www 8027: # -------------------------------------------------------- Value of a Condition
8028:
1.713 albertel 8029: # gets the value of a specific preevaluated condition
8030: # stored in the string $env{user.state.<cid>}
8031: # or looks up a condition reference in the bighash and if if hasn't
8032: # already been evaluated recurses into docondval to get the value of
8033: # the condition, then memoizing it to
8034: # $env{user.state.<cid>.<condition>}
1.40 www 8035: sub directcondval {
8036: my $number=shift;
1.620 albertel 8037: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8038: &Apache::lonuserstate::evalstate();
8039: }
1.713 albertel 8040: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8041: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8042: } elsif ($number =~ /^_/) {
8043: my $sub_condition;
8044: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8045: &GDBM_READER(),0640)) {
8046: $sub_condition=$bighash{'conditions'.$number};
8047: untie(%bighash);
8048: }
8049: my $value = &docondval($sub_condition);
1.949 raeburn 8050: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8051: return $value;
8052: }
1.620 albertel 8053: if ($env{'user.state.'.$env{'request.course.id'}}) {
8054: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8055: } else {
8056: return 2;
8057: }
8058: }
8059:
1.713 albertel 8060: # get the collection of conditions for this resource
1.26 www 8061: sub condval {
8062: my $condidx=shift;
1.54 www 8063: my $allpathcond='';
1.713 albertel 8064: foreach my $cond (split(/\|/,$condidx)) {
8065: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8066: $allpathcond.=
8067: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8068: }
1.191 harris41 8069: }
1.54 www 8070: $allpathcond=~s/\|$//;
1.713 albertel 8071: return &docondval($allpathcond);
8072: }
8073:
8074: #evaluates an expression of conditions
8075: sub docondval {
8076: my ($allpathcond) = @_;
8077: my $result=0;
8078: if ($env{'request.course.id'}
8079: && defined($allpathcond)) {
8080: my $operand='|';
8081: my @stack;
8082: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8083: if ($chunk eq '(') {
8084: push @stack,($operand,$result);
8085: } elsif ($chunk eq ')') {
8086: my $before=pop @stack;
8087: if (pop @stack eq '&') {
8088: $result=$result>$before?$before:$result;
8089: } else {
8090: $result=$result>$before?$result:$before;
8091: }
8092: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8093: $operand=$chunk;
8094: } else {
8095: my $new=directcondval($chunk);
8096: if ($operand eq '&') {
8097: $result=$result>$new?$new:$result;
8098: } else {
8099: $result=$result>$new?$result:$new;
8100: }
8101: }
8102: }
1.26 www 8103: }
8104: return $result;
1.421 albertel 8105: }
8106:
8107: # ---------------------------------------------------- Devalidate courseresdata
8108:
8109: sub devalidatecourseresdata {
8110: my ($coursenum,$coursedomain)=@_;
8111: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8112: &devalidate_cache_new('courseres',$hashid);
1.28 www 8113: }
8114:
1.763 www 8115:
1.200 www 8116: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8117: #
8118: # Parameters:
8119: # $coursenum - Number of the course.
8120: # $coursedomain - Domain at which the course was created.
8121: # Returns:
8122: # A hash of the course parameters along (I think) with timestamps
8123: # and version info.
1.877 foxr 8124:
1.624 albertel 8125: sub get_courseresdata {
8126: my ($coursenum,$coursedomain)=@_;
1.200 www 8127: my $coursehom=&homeserver($coursenum,$coursedomain);
8128: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8129: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8130: my %dumpreply;
1.417 albertel 8131: unless (defined($cached)) {
1.624 albertel 8132: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8133: $result=\%dumpreply;
1.251 albertel 8134: my ($tmp) = keys(%dumpreply);
8135: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8136: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8137: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8138: return $tmp;
1.416 albertel 8139: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8140: $result=undef;
1.599 albertel 8141: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8142: }
8143: }
1.624 albertel 8144: return $result;
8145: }
8146:
1.633 albertel 8147: sub devalidateuserresdata {
8148: my ($uname,$udom)=@_;
8149: my $hashid="$udom:$uname";
8150: &devalidate_cache_new('userres',$hashid);
8151: }
8152:
1.624 albertel 8153: sub get_userresdata {
8154: my ($uname,$udom)=@_;
8155: #most student don\'t have any data set, check if there is some data
8156: if (&EXT_cache_status($udom,$uname)) { return undef; }
8157:
8158: my $hashid="$udom:$uname";
8159: my ($result,$cached)=&is_cached_new('userres',$hashid);
8160: if (!defined($cached)) {
8161: my %resourcedata=&dump('resourcedata',$udom,$uname);
8162: $result=\%resourcedata;
8163: &do_cache_new('userres',$hashid,$result,600);
8164: }
8165: my ($tmp)=keys(%$result);
8166: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8167: return $result;
8168: }
8169: #error 2 occurs when the .db doesn't exist
8170: if ($tmp!~/error: 2 /) {
1.672 albertel 8171: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8172: " Trying to get resource data for ".
8173: $uname." at ".$udom.": ".
8174: $tmp."</font>");
8175: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8176: #&EXT_cache_set($udom,$uname);
8177: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8178: undef($tmp); # not really an error so don't send it back
1.624 albertel 8179: }
8180: return $tmp;
8181: }
1.879 foxr 8182: #----------------------------------------------- resdata - return resource data
8183: # Purpose:
8184: # Return resource data for either users or for a course.
8185: # Parameters:
8186: # $name - Course/user name.
8187: # $domain - Name of the domain the user/course is registered on.
8188: # $type - Type of thing $name is (must be 'course' or 'user'
8189: # @which - Array of names of resources desired.
8190: # Returns:
8191: # The value of the first reasource in @which that is found in the
8192: # resource hash.
8193: # Exceptional Conditions:
8194: # If the $type passed in is not valid (not the string 'course' or
8195: # 'user', an undefined reference is returned.
8196: # If none of the resources are found, an undef is returned
1.624 albertel 8197: sub resdata {
8198: my ($name,$domain,$type,@which)=@_;
8199: my $result;
8200: if ($type eq 'course') {
8201: $result=&get_courseresdata($name,$domain);
8202: } elsif ($type eq 'user') {
8203: $result=&get_userresdata($name,$domain);
8204: }
8205: if (!ref($result)) { return $result; }
1.251 albertel 8206: foreach my $item (@which) {
1.927 albertel 8207: if (defined($result->{$item->[0]})) {
8208: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8209: }
1.250 albertel 8210: }
1.291 albertel 8211: return undef;
1.200 www 8212: }
8213:
1.379 matthew 8214: #
8215: # EXT resource caching routines
8216: #
8217:
8218: sub clear_EXT_cache_status {
1.383 albertel 8219: &delenv('cache.EXT.');
1.379 matthew 8220: }
8221:
8222: sub EXT_cache_status {
8223: my ($target_domain,$target_user) = @_;
1.383 albertel 8224: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8225: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8226: # We know already the user has no data
8227: return 1;
8228: } else {
8229: return 0;
8230: }
8231: }
8232:
8233: sub EXT_cache_set {
8234: my ($target_domain,$target_user) = @_;
1.383 albertel 8235: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8236: #&appenv({$cachename => time});
1.379 matthew 8237: }
8238:
1.28 www 8239: # --------------------------------------------------------- Value of a Variable
1.58 www 8240: sub EXT {
1.715 albertel 8241:
1.395 albertel 8242: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8243: unless ($varname) { return ''; }
1.218 albertel 8244: #get real user name/domain, courseid and symb
8245: my $courseid;
1.359 albertel 8246: my $publicuser;
1.427 www 8247: if ($symbparm) {
8248: $symbparm=&get_symb_from_alias($symbparm);
8249: }
1.218 albertel 8250: if (!($uname && $udom)) {
1.790 albertel 8251: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8252: if (!$symbparm) { $symbparm=$cursymb; }
8253: } else {
1.620 albertel 8254: $courseid=$env{'request.course.id'};
1.218 albertel 8255: }
1.48 www 8256: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8257: my $rest;
1.320 albertel 8258: if (defined($therest[0])) {
1.48 www 8259: $rest=join('.',@therest);
8260: } else {
8261: $rest='';
8262: }
1.320 albertel 8263:
1.57 www 8264: my $qualifierrest=$qualifier;
8265: if ($rest) { $qualifierrest.='.'.$rest; }
8266: my $spacequalifierrest=$space;
8267: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8268: if ($realm eq 'user') {
1.48 www 8269: # --------------------------------------------------------------- user.resource
8270: if ($space eq 'resource') {
1.651 albertel 8271: if ( (defined($Apache::lonhomework::parsing_a_problem)
8272: || defined($Apache::lonhomework::parsing_a_task))
8273: &&
1.744 albertel 8274: ($symbparm eq &symbread()) ) {
8275: # if we are in the middle of processing the resource the
8276: # get the value we are planning on committing
8277: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8278: return $Apache::lonhomework::results{$qualifierrest};
8279: } else {
8280: return $Apache::lonhomework::history{$qualifierrest};
8281: }
1.335 albertel 8282: } else {
1.359 albertel 8283: my %restored;
1.620 albertel 8284: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8285: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8286: } else {
8287: %restored=&restore($symbparm,$courseid,$udom,$uname);
8288: }
1.335 albertel 8289: return $restored{$qualifierrest};
8290: }
1.48 www 8291: # ----------------------------------------------------------------- user.access
8292: } elsif ($space eq 'access') {
1.218 albertel 8293: # FIXME - not supporting calls for a specific user
1.48 www 8294: return &allowed($qualifier,$rest);
8295: # ------------------------------------------ user.preferences, user.environment
8296: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8297: if (($uname eq $env{'user.name'}) &&
8298: ($udom eq $env{'user.domain'})) {
8299: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8300: } else {
1.359 albertel 8301: my %returnhash;
8302: if (!$publicuser) {
8303: %returnhash=&userenvironment($udom,$uname,
8304: $qualifierrest);
8305: }
1.218 albertel 8306: return $returnhash{$qualifierrest};
8307: }
1.48 www 8308: # ----------------------------------------------------------------- user.course
8309: } elsif ($space eq 'course') {
1.218 albertel 8310: # FIXME - not supporting calls for a specific user
1.620 albertel 8311: return $env{join('.',('request.course',$qualifier))};
1.48 www 8312: # ------------------------------------------------------------------- user.role
8313: } elsif ($space eq 'role') {
1.218 albertel 8314: # FIXME - not supporting calls for a specific user
1.620 albertel 8315: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8316: if ($qualifier eq 'value') {
8317: return $role;
8318: } elsif ($qualifier eq 'extent') {
8319: return $where;
8320: }
8321: # ----------------------------------------------------------------- user.domain
8322: } elsif ($space eq 'domain') {
1.218 albertel 8323: return $udom;
1.48 www 8324: # ------------------------------------------------------------------- user.name
8325: } elsif ($space eq 'name') {
1.218 albertel 8326: return $uname;
1.48 www 8327: # ---------------------------------------------------- Any other user namespace
1.29 www 8328: } else {
1.359 albertel 8329: my %reply;
8330: if (!$publicuser) {
8331: %reply=&get($space,[$qualifierrest],$udom,$uname);
8332: }
8333: return $reply{$qualifierrest};
1.48 www 8334: }
1.236 www 8335: } elsif ($realm eq 'query') {
8336: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8337: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8338: [$spacequalifierrest]);
1.620 albertel 8339: return $env{'form.'.$spacequalifierrest};
1.236 www 8340: } elsif ($realm eq 'request') {
1.48 www 8341: # ------------------------------------------------------------- request.browser
8342: if ($space eq 'browser') {
1.430 www 8343: if ($qualifier eq 'textremote') {
1.676 albertel 8344: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8345: return 1;
8346: } else {
8347: return 0;
8348: }
8349: } else {
1.620 albertel 8350: return $env{'browser.'.$qualifier};
1.430 www 8351: }
1.57 www 8352: # ------------------------------------------------------------ request.filename
8353: } else {
1.620 albertel 8354: return $env{'request.'.$spacequalifierrest};
1.29 www 8355: }
1.28 www 8356: } elsif ($realm eq 'course') {
1.48 www 8357: # ---------------------------------------------------------- course.description
1.620 albertel 8358: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8359: } elsif ($realm eq 'resource') {
1.165 www 8360:
1.620 albertel 8361: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8362: if (!$symbparm) { $symbparm=&symbread(); }
8363: }
1.693 albertel 8364:
8365: if ($space eq 'title') {
8366: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8367: return &gettitle($symbparm);
8368: }
8369:
8370: if ($space eq 'map') {
8371: my ($map) = &decode_symb($symbparm);
8372: return &symbread($map);
8373: }
1.905 albertel 8374: if ($space eq 'filename') {
8375: if ($symbparm) {
8376: return &clutter((&decode_symb($symbparm))[2]);
8377: }
8378: return &hreflocation('',$env{'request.filename'});
8379: }
1.693 albertel 8380:
8381: my ($section, $group, @groups);
1.593 albertel 8382: my ($courselevelm,$courselevel);
1.539 albertel 8383: if ($symbparm && defined($courseid) &&
1.620 albertel 8384: $courseid eq $env{'request.course.id'}) {
1.165 www 8385:
1.218 albertel 8386: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8387:
1.60 www 8388: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8389: my $symbp=$symbparm;
1.735 albertel 8390: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8391:
8392: my $symbparm=$symbp.'.'.$spacequalifierrest;
8393: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8394:
1.620 albertel 8395: if (($env{'user.name'} eq $uname) &&
8396: ($env{'user.domain'} eq $udom)) {
8397: $section=$env{'request.course.sec'};
1.733 raeburn 8398: @groups = split(/:/,$env{'request.course.groups'});
8399: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8400: } else {
1.539 albertel 8401: if (! defined($usection)) {
1.551 albertel 8402: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8403: } else {
8404: $section = $usection;
8405: }
1.733 raeburn 8406: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8407: }
8408:
8409: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8410: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8411: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8412:
1.593 albertel 8413: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8414: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8415: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8416:
1.60 www 8417: # ----------------------------------------------------------- first, check user
1.624 albertel 8418:
8419: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8420: ([$courselevelr,'resource'],
8421: [$courselevelm,'map' ],
8422: [$courselevel, 'course' ]));
1.931 albertel 8423: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8424:
1.594 albertel 8425: # ------------------------------------------------ second, check some of course
1.684 raeburn 8426: my $coursereply;
1.691 raeburn 8427: if (@groups > 0) {
8428: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8429: $mapparm,$spacequalifierrest);
1.927 albertel 8430: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8431: }
1.96 www 8432:
1.684 raeburn 8433: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8434: $env{'course.'.$courseid.'.domain'},
8435: 'course',
8436: ([$seclevelr, 'resource'],
8437: [$seclevelm, 'map' ],
8438: [$seclevel, 'course' ],
8439: [$courselevelr,'resource']));
8440: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8441:
1.60 www 8442: # ------------------------------------------------------ third, check map parms
1.218 albertel 8443: my %parmhash=();
8444: my $thisparm='';
8445: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8446: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8447: &GDBM_READER(),0640)) {
1.218 albertel 8448: $thisparm=$parmhash{$symbparm};
8449: untie(%parmhash);
8450: }
1.927 albertel 8451: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8452: }
1.594 albertel 8453: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8454:
1.218 albertel 8455: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8456: my $filename;
8457: if (!$symbparm) { $symbparm=&symbread(); }
8458: if ($symbparm) {
1.409 www 8459: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8460: } else {
1.620 albertel 8461: $filename=$env{'request.filename'};
1.282 albertel 8462: }
8463: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8464: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8465: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8466: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8467:
1.927 albertel 8468: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8469: if ($symbparm && defined($courseid) &&
1.620 albertel 8470: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8471: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8472: $env{'course.'.$courseid.'.domain'},
8473: 'course',
1.927 albertel 8474: ([$courselevelm,'map' ],
8475: [$courselevel, 'course']));
8476: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8477: }
1.145 www 8478: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8479: unless ($space eq '0') {
1.336 albertel 8480: my @parts=split(/_/,$space);
8481: my $id=pop(@parts);
8482: my $part=join('_',@parts);
8483: if ($part eq '') { $part='0'; }
1.927 albertel 8484: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8485: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8486: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8487: }
1.395 albertel 8488: if ($recurse) { return undef; }
8489: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8490: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8491: # ---------------------------------------------------- Any other user namespace
8492: } elsif ($realm eq 'environment') {
8493: # ----------------------------------------------------------------- environment
1.620 albertel 8494: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8495: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8496: } else {
1.770 albertel 8497: if ($uname eq 'anonymous' && $udom eq '') {
8498: return '';
8499: }
1.219 albertel 8500: my %returnhash=&userenvironment($udom,$uname,
8501: $spacequalifierrest);
8502: return $returnhash{$spacequalifierrest};
8503: }
1.28 www 8504: } elsif ($realm eq 'system') {
1.48 www 8505: # ----------------------------------------------------------------- system.time
8506: if ($space eq 'time') {
8507: return time;
8508: }
1.696 albertel 8509: } elsif ($realm eq 'server') {
8510: # ----------------------------------------------------------------- system.time
8511: if ($space eq 'name') {
8512: return $ENV{'SERVER_NAME'};
8513: }
1.28 www 8514: }
1.48 www 8515: return '';
1.61 www 8516: }
8517:
1.927 albertel 8518: sub get_reply {
8519: my ($reply_value) = @_;
1.940 raeburn 8520: if (ref($reply_value) eq 'ARRAY') {
8521: if (wantarray) {
8522: return @$reply_value;
8523: }
8524: return $reply_value->[0];
8525: } else {
8526: return $reply_value;
1.927 albertel 8527: }
8528: }
8529:
1.691 raeburn 8530: sub check_group_parms {
8531: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8532: my @groupitems = ();
8533: my $resultitem;
1.927 albertel 8534: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8535: foreach my $group (@{$groups}) {
8536: foreach my $level (@levels) {
1.927 albertel 8537: my $item = $courseid.'.['.$group.'].'.$level->[0];
8538: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8539: }
8540: }
8541: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8542: $env{'course.'.$courseid.'.domain'},
8543: 'course',@groupitems);
8544: return $coursereply;
8545: }
8546:
8547: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8548: my ($courseid,@groups) = @_;
8549: @groups = sort(@groups);
1.691 raeburn 8550: return @groups;
8551: }
8552:
1.395 albertel 8553: sub packages_tab_default {
8554: my ($uri,$varname)=@_;
8555: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8556:
8557: my (@extension,@specifics,$do_default);
8558: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8559: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8560: if ($pack_type eq 'default') {
8561: $do_default=1;
8562: } elsif ($pack_type eq 'extension') {
8563: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8564: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8565: # only look at packages defaults for packages that this id is
1.738 albertel 8566: push(@specifics,[$package,$pack_type,$pack_part]);
8567: }
8568: }
8569: # first look for a package that matches the requested part id
8570: foreach my $package (@specifics) {
8571: my (undef,$pack_type,$pack_part)=@{$package};
8572: next if ($pack_part ne $part);
8573: if (defined($packagetab{"$pack_type&$name&default"})) {
8574: return $packagetab{"$pack_type&$name&default"};
8575: }
8576: }
8577: # look for any possible matching non extension_ package
8578: foreach my $package (@specifics) {
8579: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8580: if (defined($packagetab{"$pack_type&$name&default"})) {
8581: return $packagetab{"$pack_type&$name&default"};
8582: }
1.585 albertel 8583: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8584: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8585: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8586: }
8587: }
1.738 albertel 8588: # look for any posible extension_ match
8589: foreach my $package (@extension) {
8590: my ($package,$pack_type)=@{$package};
8591: if (defined($packagetab{"$pack_type&$name&default"})) {
8592: return $packagetab{"$pack_type&$name&default"};
8593: }
8594: if (defined($packagetab{$package."&$name&default"})) {
8595: return $packagetab{$package."&$name&default"};
8596: }
8597: }
8598: # look for a global default setting
8599: if ($do_default && defined($packagetab{"default&$name&default"})) {
8600: return $packagetab{"default&$name&default"};
8601: }
1.395 albertel 8602: return undef;
8603: }
8604:
1.334 albertel 8605: sub add_prefix_and_part {
8606: my ($prefix,$part)=@_;
8607: my $keyroot;
8608: if (defined($prefix) && $prefix !~ /^__/) {
8609: # prefix that has a part already
8610: $keyroot=$prefix;
8611: } elsif (defined($prefix)) {
8612: # prefix that is missing a part
8613: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8614: } else {
8615: # no prefix at all
8616: if (defined($part)) { $keyroot='_'.$part; }
8617: }
8618: return $keyroot;
8619: }
8620:
1.71 www 8621: # ---------------------------------------------------------------- Get metadata
8622:
1.599 albertel 8623: my %metaentry;
1.71 www 8624: sub metadata {
1.176 www 8625: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8626: $uri=&declutter($uri);
1.288 albertel 8627: # if it is a non metadata possible uri return quickly
1.529 albertel 8628: if (($uri eq '') ||
8629: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8630: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.26 raeburn 8631: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 8632: return undef;
8633: }
8634: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8635: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8636: return undef;
1.288 albertel 8637: }
1.73 www 8638: my $filename=$uri;
8639: $uri=~s/\.meta$//;
1.172 www 8640: #
8641: # Is the metadata already cached?
1.177 www 8642: # Look at timestamp of caching
1.172 www 8643: # Everything is cached by the main uri, libraries are never directly cached
8644: #
1.428 albertel 8645: if (!defined($liburi)) {
1.599 albertel 8646: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8647: if (defined($cached)) { return $result->{':'.$what}; }
8648: }
8649: {
1.172 www 8650: #
8651: # Is this a recursive call for a library?
8652: #
1.599 albertel 8653: # if (! exists($metacache{$uri})) {
8654: # $metacache{$uri}={};
8655: # }
1.924 albertel 8656: my $cachetime = 60*60;
1.171 www 8657: if ($liburi) {
8658: $liburi=&declutter($liburi);
8659: $filename=$liburi;
1.401 bowersj2 8660: } else {
1.599 albertel 8661: &devalidate_cache_new('meta',$uri);
8662: undef(%metaentry);
1.401 bowersj2 8663: }
1.140 www 8664: my %metathesekeys=();
1.73 www 8665: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8666: my $metastring;
1.924 albertel 8667: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8668: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8669: $metastring =
1.929 albertel 8670: &Apache::lonnet::ssi_body($which,
1.924 albertel 8671: ('grade_target' => 'meta'));
8672: $cachetime = 1; # only want this cached in the child not long term
1.1056.4.26 raeburn 8673: } elsif (($uri !~ m -^(editupload)/-) &&
8674: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 8675: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8676: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8677: $metastring=&getfile($file);
1.489 albertel 8678: }
1.208 albertel 8679: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8680: my $token;
1.140 www 8681: undef %metathesekeys;
1.71 www 8682: while ($token=$parser->get_token) {
1.339 albertel 8683: if ($token->[0] eq 'S') {
8684: if (defined($token->[2]->{'package'})) {
1.172 www 8685: #
8686: # This is a package - get package info
8687: #
1.339 albertel 8688: my $package=$token->[2]->{'package'};
8689: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8690: if (defined($token->[2]->{'id'})) {
8691: $keyroot.='_'.$token->[2]->{'id'};
8692: }
1.599 albertel 8693: if ($metaentry{':packages'}) {
8694: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8695: } else {
1.599 albertel 8696: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8697: }
1.736 albertel 8698: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8699: my $part=$keyroot;
8700: $part=~s/^\_//;
1.736 albertel 8701: if ($pack_entry=~/^\Q$package\E\&/ ||
8702: $pack_entry=~/^\Q$package\E_0\&/) {
8703: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8704: # ignore package.tab specified default values
8705: # here &package_tab_default() will fetch those
8706: if ($subp eq 'default') { next; }
1.736 albertel 8707: my $value=$packagetab{$pack_entry};
1.432 albertel 8708: my $unikey;
8709: if ($pack =~ /_0$/) {
8710: $unikey='parameter_0_'.$name;
8711: $part=0;
8712: } else {
8713: $unikey='parameter'.$keyroot.'_'.$name;
8714: }
1.339 albertel 8715: if ($subp eq 'display') {
8716: $value.=' [Part: '.$part.']';
8717: }
1.599 albertel 8718: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8719: $metathesekeys{$unikey}=1;
1.599 albertel 8720: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8721: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8722: }
1.599 albertel 8723: if (defined($metaentry{':'.$unikey.'.default'})) {
8724: $metaentry{':'.$unikey}=
8725: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8726: }
1.339 albertel 8727: }
8728: }
8729: } else {
1.172 www 8730: #
8731: # This is not a package - some other kind of start tag
1.339 albertel 8732: #
8733: my $entry=$token->[1];
8734: my $unikey;
8735: if ($entry eq 'import') {
8736: $unikey='';
8737: } else {
8738: $unikey=$entry;
8739: }
8740: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8741:
8742: if (defined($token->[2]->{'id'})) {
8743: $unikey.='_'.$token->[2]->{'id'};
8744: }
1.175 www 8745:
1.339 albertel 8746: if ($entry eq 'import') {
1.175 www 8747: #
8748: # Importing a library here
1.339 albertel 8749: #
8750: if ($depthcount<20) {
8751: my $location=$parser->get_text('/import');
8752: my $dir=$filename;
8753: $dir=~s|[^/]*$||;
8754: $location=&filelocation($dir,$location);
1.736 albertel 8755: my $metadata =
8756: &metadata($uri,'keys', $location,$unikey,
8757: $depthcount+1);
8758: foreach my $meta (split(',',$metadata)) {
8759: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8760: $metathesekeys{$meta}=1;
1.339 albertel 8761: }
8762: }
8763: } else {
8764: if (defined($token->[2]->{'name'})) {
8765: $unikey.='_'.$token->[2]->{'name'};
8766: }
8767: $metathesekeys{$unikey}=1;
1.736 albertel 8768: foreach my $param (@{$token->[3]}) {
8769: $metaentry{':'.$unikey.'.'.$param} =
8770: $token->[2]->{$param};
1.339 albertel 8771: }
8772: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8773: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8774: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8775: # only ws inside the tag, and not in default, so use default
8776: # as value
1.599 albertel 8777: $metaentry{':'.$unikey}=$default;
1.908 albertel 8778: } elsif ( $internaltext =~ /\S/ ) {
8779: # something interesting inside the tag
8780: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8781: } else {
1.908 albertel 8782: # no interesting values, don't set a default
1.339 albertel 8783: }
1.172 www 8784: # end of not-a-package not-a-library import
1.339 albertel 8785: }
1.172 www 8786: # end of not-a-package start tag
1.339 albertel 8787: }
1.172 www 8788: # the next is the end of "start tag"
1.339 albertel 8789: }
8790: }
1.483 albertel 8791: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8792: $extension = lc($extension);
8793: if ($extension eq 'htm') { $extension='html'; }
8794:
1.737 albertel 8795: foreach my $key (keys(%packagetab)) {
1.483 albertel 8796: #no specific packages #how's our extension
8797: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8798: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8799: \%metathesekeys);
8800: }
1.883 albertel 8801:
8802: if (!exists($metaentry{':packages'})
8803: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8804: foreach my $key (keys(%packagetab)) {
1.483 albertel 8805: #no specific packages well let's get default then
8806: if ($key!~/^default&/) { next; }
1.488 albertel 8807: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8808: \%metathesekeys);
8809: }
8810: }
1.338 www 8811: # are there custom rights to evaluate
1.599 albertel 8812: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8813:
1.338 www 8814: #
8815: # Importing a rights file here
1.339 albertel 8816: #
8817: unless ($depthcount) {
1.599 albertel 8818: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8819: my $dir=$filename;
8820: $dir=~s|[^/]*$||;
8821: $location=&filelocation($dir,$location);
1.736 albertel 8822: my $rights_metadata =
8823: &metadata($uri,'keys',$location,'_rights',
8824: $depthcount+1);
8825: foreach my $rights (split(',',$rights_metadata)) {
8826: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8827: $metathesekeys{$rights}=1;
1.339 albertel 8828: }
8829: }
8830: }
1.737 albertel 8831: # uniqifiy package listing
8832: my %seen;
8833: my @uniq_packages =
8834: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8835: $metaentry{':packages'} = join(',',@uniq_packages);
8836:
8837: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8838: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8839: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8840: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8841: # this is the end of "was not already recently cached
1.71 www 8842: }
1.599 albertel 8843: return $metaentry{':'.$what};
1.261 albertel 8844: }
8845:
1.488 albertel 8846: sub metadata_create_package_def {
1.483 albertel 8847: my ($uri,$key,$package,$metathesekeys)=@_;
8848: my ($pack,$name,$subp)=split(/\&/,$key);
8849: if ($subp eq 'default') { next; }
8850:
1.599 albertel 8851: if (defined($metaentry{':packages'})) {
8852: $metaentry{':packages'}.=','.$package;
1.483 albertel 8853: } else {
1.599 albertel 8854: $metaentry{':packages'}=$package;
1.483 albertel 8855: }
8856: my $value=$packagetab{$key};
8857: my $unikey;
8858: $unikey='parameter_0_'.$name;
1.599 albertel 8859: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8860: $$metathesekeys{$unikey}=1;
1.599 albertel 8861: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8862: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8863: }
1.599 albertel 8864: if (defined($metaentry{':'.$unikey.'.default'})) {
8865: $metaentry{':'.$unikey}=
8866: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8867: }
8868: }
8869:
1.261 albertel 8870: sub metadata_generate_part0 {
8871: my ($metadata,$metacache,$uri) = @_;
8872: my %allnames;
1.737 albertel 8873: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8874: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8875: my $part=$$metacache{':'.$metakey.'.part'};
8876: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8877: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8878: $allnames{$name}=$part;
8879: }
8880: }
8881: }
8882: foreach my $name (keys(%allnames)) {
8883: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8884: my $key=":parameter_0_$name";
1.261 albertel 8885: $$metacache{"$key.part"}='0';
8886: $$metacache{"$key.name"}=$name;
1.428 albertel 8887: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8888: $allnames{$name}.'_'.$name.
8889: '.type'};
1.428 albertel 8890: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8891: '.display'};
1.644 www 8892: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8893: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8894: $$metacache{"$key.display"}=$olddis;
8895: }
1.71 www 8896: }
8897:
1.764 albertel 8898: # ------------------------------------------------------ Devalidate title cache
8899:
8900: sub devalidate_title_cache {
8901: my ($url)=@_;
8902: if (!$env{'request.course.id'}) { return; }
8903: my $symb=&symbread($url);
8904: if (!$symb) { return; }
8905: my $key=$env{'request.course.id'}."\0".$symb;
8906: &devalidate_cache_new('title',$key);
8907: }
8908:
1.1014 droeschl 8909: # ------------------------------------------------- Get the title of a course
8910:
8911: sub current_course_title {
8912: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8913: }
1.301 www 8914: # ------------------------------------------------- Get the title of a resource
8915:
8916: sub gettitle {
8917: my $urlsymb=shift;
8918: my $symb=&symbread($urlsymb);
1.534 albertel 8919: if ($symb) {
1.620 albertel 8920: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8921: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8922: if (defined($cached)) {
8923: return $result;
8924: }
1.534 albertel 8925: my ($map,$resid,$url)=&decode_symb($symb);
8926: my $title='';
1.907 albertel 8927: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8928: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8929: } else {
8930: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8931: &GDBM_READER(),0640)) {
8932: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8933: $title=$bighash{'title_'.$mapid.'.'.$resid};
8934: untie(%bighash);
8935: }
1.534 albertel 8936: }
8937: $title=~s/\&colon\;/\:/gs;
8938: if ($title) {
1.599 albertel 8939: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8940: }
8941: $urlsymb=$url;
8942: }
8943: my $title=&metadata($urlsymb,'title');
8944: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8945: return $title;
1.301 www 8946: }
1.613 albertel 8947:
1.614 albertel 8948: sub get_slot {
8949: my ($which,$cnum,$cdom)=@_;
8950: if (!$cnum || !$cdom) {
1.790 albertel 8951: (undef,my $courseid)=&whichuser();
1.620 albertel 8952: $cdom=$env{'course.'.$courseid.'.domain'};
8953: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8954: }
1.703 albertel 8955: my $key=join("\0",'slots',$cdom,$cnum,$which);
8956: my %slotinfo;
8957: if (exists($remembered{$key})) {
8958: $slotinfo{$which} = $remembered{$key};
8959: } else {
8960: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8961: &Apache::lonhomework::showhash(%slotinfo);
8962: my ($tmp)=keys(%slotinfo);
8963: if ($tmp=~/^error:/) { return (); }
8964: $remembered{$key} = $slotinfo{$which};
8965: }
1.616 albertel 8966: if (ref($slotinfo{$which}) eq 'HASH') {
8967: return %{$slotinfo{$which}};
8968: }
8969: return $slotinfo{$which};
1.614 albertel 8970: }
1.31 www 8971: # ------------------------------------------------- Update symbolic store links
8972:
8973: sub symblist {
8974: my ($mapname,%newhash)=@_;
1.438 www 8975: $mapname=&deversion(&declutter($mapname));
1.31 www 8976: my %hash;
1.620 albertel 8977: if (($env{'request.course.fn'}) && (%newhash)) {
8978: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8979: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8980: foreach my $url (keys(%newhash)) {
1.711 albertel 8981: next if ($url eq 'last_known'
8982: && $env{'form.no_update_last_known'});
8983: $hash{declutter($url)}=&encode_symb($mapname,
8984: $newhash{$url}->[1],
8985: $newhash{$url}->[0]);
1.191 harris41 8986: }
1.31 www 8987: if (untie(%hash)) {
8988: return 'ok';
8989: }
8990: }
8991: }
8992: return 'error';
1.212 www 8993: }
8994:
8995: # --------------------------------------------------------------- Verify a symb
8996:
8997: sub symbverify {
1.510 www 8998: my ($symb,$thisurl)=@_;
8999: my $thisfn=$thisurl;
1.439 www 9000: $thisfn=&declutter($thisfn);
1.215 www 9001: # direct jump to resource in page or to a sequence - will construct own symbs
9002: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9003: # check URL part
1.409 www 9004: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9005:
1.431 www 9006: unless ($url eq $thisfn) { return 0; }
1.213 www 9007:
1.216 www 9008: $symb=&symbclean($symb);
1.510 www 9009: $thisurl=&deversion($thisurl);
1.439 www 9010: $thisfn=&deversion($thisfn);
1.213 www 9011:
9012: my %bighash;
9013: my $okay=0;
1.431 www 9014:
1.620 albertel 9015: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9016: &GDBM_READER(),0640)) {
1.1032 raeburn 9017: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9018: $thisurl =~ s/\?.+$//;
9019: }
1.510 www 9020: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 9021: unless ($ids) {
1.1056.4.21 raeburn 9022: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9023: $ids=$bighash{$idkey};
1.216 www 9024: }
9025: if ($ids) {
9026: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9027: foreach my $id (split(/\,/,$ids)) {
9028: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9029: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9030: $symb =~ s/\?.+$//;
9031: }
1.216 www 9032: if (
9033: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9034: eq $symb) {
1.620 albertel 9035: if (($env{'request.role.adv'}) ||
1.1056.4.20 raeburn 9036: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9037: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9038: $okay=1;
9039: }
9040: }
1.216 www 9041: }
9042: }
1.213 www 9043: untie(%bighash);
9044: }
9045: return $okay;
1.31 www 9046: }
9047:
1.210 www 9048: # --------------------------------------------------------------- Clean-up symb
9049:
9050: sub symbclean {
9051: my $symb=shift;
1.568 albertel 9052: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9053: # remove version from map
9054: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9055:
1.210 www 9056: # remove version from URL
9057: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9058:
1.507 www 9059: # remove wrapper
9060:
1.510 www 9061: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9062: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9063: return $symb;
1.409 www 9064: }
9065:
9066: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9067:
9068: sub encode_symb {
9069: my ($map,$resid,$url)=@_;
9070: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9071: }
1.409 www 9072:
9073: sub decode_symb {
1.568 albertel 9074: my $symb=shift;
9075: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9076: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9077: return (&fixversion($map),$resid,&fixversion($url));
9078: }
9079:
9080: sub fixversion {
9081: my $fn=shift;
1.609 banghart 9082: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9083: my %bighash;
9084: my $uri=&clutter($fn);
1.620 albertel 9085: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9086: # is this cached?
1.599 albertel 9087: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9088: if (defined($cached)) { return $result; }
9089: # unfortunately not cached, or expired
1.620 albertel 9090: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9091: &GDBM_READER(),0640)) {
9092: if ($bighash{'version_'.$uri}) {
9093: my $version=$bighash{'version_'.$uri};
1.444 www 9094: unless (($version eq 'mostrecent') ||
9095: ($version==&getversion($uri))) {
1.440 www 9096: $uri=~s/\.(\w+)$/\.$version\.$1/;
9097: }
9098: }
9099: untie %bighash;
1.413 www 9100: }
1.599 albertel 9101: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9102: }
9103:
9104: sub deversion {
9105: my $url=shift;
9106: $url=~s/\.\d+\.(\w+)$/\.$1/;
9107: return $url;
1.210 www 9108: }
9109:
1.31 www 9110: # ------------------------------------------------------ Return symb list entry
9111:
9112: sub symbread {
1.249 www 9113: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9114: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9115: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9116: # no filename provided? try from environment
1.44 www 9117: unless ($thisfn) {
1.620 albertel 9118: if ($env{'request.symb'}) {
9119: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9120: }
1.620 albertel 9121: $thisfn=$env{'request.filename'};
1.44 www 9122: }
1.569 albertel 9123: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9124: # is that filename actually a symb? Verify, clean, and return
9125: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9126: if (&symbverify($thisfn,$1)) {
1.620 albertel 9127: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9128: }
1.242 www 9129: }
1.44 www 9130: $thisfn=declutter($thisfn);
1.31 www 9131: my %hash;
1.37 www 9132: my %bighash;
9133: my $syval='';
1.620 albertel 9134: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9135: my $targetfn = $thisfn;
1.609 banghart 9136: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9137: $targetfn = 'adm/wrapper/'.$thisfn;
9138: }
1.687 albertel 9139: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9140: $targetfn=$1;
9141: }
1.620 albertel 9142: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9143: &GDBM_READER(),0640)) {
1.481 raeburn 9144: $syval=$hash{$targetfn};
1.37 www 9145: untie(%hash);
9146: }
9147: # ---------------------------------------------------------- There was an entry
9148: if ($syval) {
1.601 albertel 9149: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9150: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9151: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9152: #return $env{$cache_str}='';
1.601 albertel 9153: #}
9154: #$syval.=$1;
9155: #}
1.37 www 9156: } else {
9157: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9158: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9159: &GDBM_READER(),0640)) {
1.37 www 9160: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9161: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9162: unless ($ids) {
9163: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9164: }
9165: unless ($ids) {
9166: # alias?
9167: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9168: }
1.37 www 9169: if ($ids) {
9170: # ------------------------------------------------------------------- Has ID(s)
9171: my @possibilities=split(/\,/,$ids);
1.39 www 9172: if ($#possibilities==0) {
9173: # ----------------------------------------------- There is only one possibility
1.37 www 9174: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9175: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9176: $resid,$thisfn);
1.249 www 9177: } elsif (!$donotrecurse) {
1.39 www 9178: # ------------------------------------------ There is more than one possibility
9179: my $realpossible=0;
1.800 albertel 9180: foreach my $id (@possibilities) {
9181: my $file=$bighash{'src_'.$id};
1.39 www 9182: if (&allowed('bre',$file)) {
1.800 albertel 9183: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9184: if ($bighash{'map_type_'.$mapid} ne 'page') {
9185: $realpossible++;
1.626 albertel 9186: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9187: $resid,$thisfn);
1.39 www 9188: }
9189: }
1.191 harris41 9190: }
1.39 www 9191: if ($realpossible!=1) { $syval=''; }
1.249 www 9192: } else {
9193: $syval='';
1.37 www 9194: }
9195: }
9196: untie(%bighash)
1.481 raeburn 9197: }
1.31 www 9198: }
1.62 www 9199: if ($syval) {
1.620 albertel 9200: return $env{$cache_str}=$syval;
1.62 www 9201: }
1.31 www 9202: }
1.949 raeburn 9203: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9204: return $env{$cache_str}='';
1.31 www 9205: }
9206:
9207: # ---------------------------------------------------------- Return random seed
9208:
1.32 www 9209: sub numval {
9210: my $txt=shift;
9211: $txt=~tr/A-J/0-9/;
9212: $txt=~tr/a-j/0-9/;
9213: $txt=~tr/K-T/0-9/;
9214: $txt=~tr/k-t/0-9/;
9215: $txt=~tr/U-Z/0-5/;
9216: $txt=~tr/u-z/0-5/;
9217: $txt=~s/\D//g;
1.564 albertel 9218: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9219: return int($txt);
1.368 albertel 9220: }
9221:
1.484 albertel 9222: sub numval2 {
9223: my $txt=shift;
9224: $txt=~tr/A-J/0-9/;
9225: $txt=~tr/a-j/0-9/;
9226: $txt=~tr/K-T/0-9/;
9227: $txt=~tr/k-t/0-9/;
9228: $txt=~tr/U-Z/0-5/;
9229: $txt=~tr/u-z/0-5/;
9230: $txt=~s/\D//g;
9231: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9232: my $total;
9233: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9234: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9235: return int($total);
9236: }
9237:
1.575 albertel 9238: sub numval3 {
9239: use integer;
9240: my $txt=shift;
9241: $txt=~tr/A-J/0-9/;
9242: $txt=~tr/a-j/0-9/;
9243: $txt=~tr/K-T/0-9/;
9244: $txt=~tr/k-t/0-9/;
9245: $txt=~tr/U-Z/0-5/;
9246: $txt=~tr/u-z/0-5/;
9247: $txt=~s/\D//g;
9248: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9249: my $total;
9250: foreach my $val (@txts) { $total+=$val; }
9251: if ($_64bit) { $total=(($total<<32)>>32); }
9252: return $total;
9253: }
9254:
1.675 albertel 9255: sub digest {
9256: my ($data)=@_;
9257: my $digest=&Digest::MD5::md5($data);
9258: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9259: my ($e,$f);
9260: {
9261: use integer;
9262: $e=($a+$b);
9263: $f=($c+$d);
9264: if ($_64bit) {
9265: $e=(($e<<32)>>32);
9266: $f=(($f<<32)>>32);
9267: }
9268: }
9269: if (wantarray) {
9270: return ($e,$f);
9271: } else {
9272: my $g;
9273: {
9274: use integer;
9275: $g=($e+$f);
9276: if ($_64bit) {
9277: $g=(($g<<32)>>32);
9278: }
9279: }
9280: return $g;
9281: }
9282: }
9283:
1.368 albertel 9284: sub latest_rnd_algorithm_id {
1.675 albertel 9285: return '64bit5';
1.366 albertel 9286: }
1.32 www 9287:
1.503 albertel 9288: sub get_rand_alg {
9289: my ($courseid)=@_;
1.790 albertel 9290: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9291: if ($courseid) {
1.620 albertel 9292: return $env{"course.$courseid.rndseed"};
1.503 albertel 9293: }
9294: return &latest_rnd_algorithm_id();
9295: }
9296:
1.562 albertel 9297: sub validCODE {
9298: my ($CODE)=@_;
9299: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9300: return 0;
9301: }
9302:
1.491 albertel 9303: sub getCODE {
1.620 albertel 9304: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9305: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9306: defined($Apache::lonhomework::parsing_a_task) ) &&
9307: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9308: return $Apache::lonhomework::history{'resource.CODE'};
9309: }
9310: return undef;
9311: }
9312:
1.31 www 9313: sub rndseed {
1.155 albertel 9314: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9315: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9316: if (!defined($symb)) {
1.366 albertel 9317: unless ($symb=$wsymb) { return time; }
9318: }
9319: if (!$courseid) { $courseid=$wcourseid; }
9320: if (!$domain) { $domain=$wdomain; }
9321: if (!$username) { $username=$wusername }
1.503 albertel 9322: my $which=&get_rand_alg();
1.803 albertel 9323:
1.491 albertel 9324: if (defined(&getCODE())) {
1.675 albertel 9325: if ($which eq '64bit5') {
9326: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9327: } elsif ($which eq '64bit4') {
1.575 albertel 9328: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9329: } else {
9330: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9331: }
1.675 albertel 9332: } elsif ($which eq '64bit5') {
9333: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9334: } elsif ($which eq '64bit4') {
9335: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9336: } elsif ($which eq '64bit3') {
9337: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9338: } elsif ($which eq '64bit2') {
9339: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9340: } elsif ($which eq '64bit') {
9341: return &rndseed_64bit($symb,$courseid,$domain,$username);
9342: }
9343: return &rndseed_32bit($symb,$courseid,$domain,$username);
9344: }
9345:
9346: sub rndseed_32bit {
9347: my ($symb,$courseid,$domain,$username)=@_;
9348: {
9349: use integer;
9350: my $symbchck=unpack("%32C*",$symb) << 27;
9351: my $symbseed=numval($symb) << 22;
9352: my $namechck=unpack("%32C*",$username) << 17;
9353: my $nameseed=numval($username) << 12;
9354: my $domainseed=unpack("%32C*",$domain) << 7;
9355: my $courseseed=unpack("%32C*",$courseid);
9356: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9357: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9358: #&logthis("rndseed :$num:$symb");
1.564 albertel 9359: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9360: return $num;
9361: }
9362: }
9363:
9364: sub rndseed_64bit {
9365: my ($symb,$courseid,$domain,$username)=@_;
9366: {
9367: use integer;
9368: my $symbchck=unpack("%32S*",$symb) << 21;
9369: my $symbseed=numval($symb) << 10;
9370: my $namechck=unpack("%32S*",$username);
9371:
9372: my $nameseed=numval($username) << 21;
9373: my $domainseed=unpack("%32S*",$domain) << 10;
9374: my $courseseed=unpack("%32S*",$courseid);
9375:
9376: my $num1=$symbchck+$symbseed+$namechck;
9377: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9378: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9379: #&logthis("rndseed :$num:$symb");
1.564 albertel 9380: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9381: return "$num1,$num2";
1.155 albertel 9382: }
1.366 albertel 9383: }
9384:
1.443 albertel 9385: sub rndseed_64bit2 {
9386: my ($symb,$courseid,$domain,$username)=@_;
9387: {
9388: use integer;
9389: # strings need to be an even # of cahracters long, it it is odd the
9390: # last characters gets thrown away
9391: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9392: my $symbseed=numval($symb) << 10;
9393: my $namechck=unpack("%32S*",$username.' ');
9394:
9395: my $nameseed=numval($username) << 21;
1.501 albertel 9396: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9397: my $courseseed=unpack("%32S*",$courseid.' ');
9398:
9399: my $num1=$symbchck+$symbseed+$namechck;
9400: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9401: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9402: #&logthis("rndseed :$num:$symb");
1.803 albertel 9403: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9404: return "$num1,$num2";
9405: }
9406: }
9407:
9408: sub rndseed_64bit3 {
9409: my ($symb,$courseid,$domain,$username)=@_;
9410: {
9411: use integer;
9412: # strings need to be an even # of cahracters long, it it is odd the
9413: # last characters gets thrown away
9414: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9415: my $symbseed=numval2($symb) << 10;
9416: my $namechck=unpack("%32S*",$username.' ');
9417:
9418: my $nameseed=numval2($username) << 21;
1.443 albertel 9419: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9420: my $courseseed=unpack("%32S*",$courseid.' ');
9421:
9422: my $num1=$symbchck+$symbseed+$namechck;
9423: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9424: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9425: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9426: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9427:
1.503 albertel 9428: return "$num1:$num2";
1.443 albertel 9429: }
9430: }
9431:
1.575 albertel 9432: sub rndseed_64bit4 {
9433: my ($symb,$courseid,$domain,$username)=@_;
9434: {
9435: use integer;
9436: # strings need to be an even # of cahracters long, it it is odd the
9437: # last characters gets thrown away
9438: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9439: my $symbseed=numval3($symb) << 10;
9440: my $namechck=unpack("%32S*",$username.' ');
9441:
9442: my $nameseed=numval3($username) << 21;
9443: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9444: my $courseseed=unpack("%32S*",$courseid.' ');
9445:
9446: my $num1=$symbchck+$symbseed+$namechck;
9447: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9448: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9449: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9450: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9451:
9452: return "$num1:$num2";
9453: }
9454: }
9455:
1.675 albertel 9456: sub rndseed_64bit5 {
9457: my ($symb,$courseid,$domain,$username)=@_;
9458: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9459: return "$num1:$num2";
9460: }
9461:
1.366 albertel 9462: sub rndseed_CODE_64bit {
9463: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9464: {
1.366 albertel 9465: use integer;
1.443 albertel 9466: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9467: my $symbseed=numval2($symb);
1.491 albertel 9468: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9469: my $CODEseed=numval(&getCODE());
1.443 albertel 9470: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9471: my $num1=$symbseed+$CODEchck;
9472: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9473: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9474: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9475: if ($_64bit) { $num1=(($num1<<32)>>32); }
9476: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9477: return "$num1:$num2";
1.366 albertel 9478: }
9479: }
9480:
1.575 albertel 9481: sub rndseed_CODE_64bit4 {
9482: my ($symb,$courseid,$domain,$username)=@_;
9483: {
9484: use integer;
9485: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9486: my $symbseed=numval3($symb);
9487: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9488: my $CODEseed=numval3(&getCODE());
9489: my $courseseed=unpack("%32S*",$courseid.' ');
9490: my $num1=$symbseed+$CODEchck;
9491: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9492: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9493: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9494: if ($_64bit) { $num1=(($num1<<32)>>32); }
9495: if ($_64bit) { $num2=(($num2<<32)>>32); }
9496: return "$num1:$num2";
9497: }
9498: }
9499:
1.675 albertel 9500: sub rndseed_CODE_64bit5 {
9501: my ($symb,$courseid,$domain,$username)=@_;
9502: my $code = &getCODE();
9503: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9504: return "$num1:$num2";
9505: }
9506:
1.366 albertel 9507: sub setup_random_from_rndseed {
9508: my ($rndseed)=@_;
1.503 albertel 9509: if ($rndseed =~/([,:])/) {
9510: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9511: &Math::Random::random_set_seed(abs($num1),abs($num2));
9512: } else {
9513: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9514: }
1.36 albertel 9515: }
9516:
1.474 albertel 9517: sub latest_receipt_algorithm_id {
1.835 albertel 9518: return 'receipt3';
1.474 albertel 9519: }
9520:
1.480 www 9521: sub recunique {
9522: my $fucourseid=shift;
9523: my $unique;
1.835 albertel 9524: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9525: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9526: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9527: } else {
9528: $unique=$perlvar{'lonReceipt'};
9529: }
9530: return unpack("%32C*",$unique);
9531: }
9532:
9533: sub recprefix {
9534: my $fucourseid=shift;
9535: my $prefix;
1.835 albertel 9536: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9537: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9538: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9539: } else {
9540: $prefix=$perlvar{'lonHostID'};
9541: }
9542: return unpack("%32C*",$prefix);
9543: }
9544:
1.76 www 9545: sub ireceipt {
1.474 albertel 9546: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9547:
9548: my $return =&recprefix($fucourseid).'-';
9549:
9550: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9551: $env{'request.state'} eq 'construct') {
9552: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9553: return $return;
9554: }
9555:
1.76 www 9556: my $cuname=unpack("%32C*",$funame);
9557: my $cudom=unpack("%32C*",$fudom);
9558: my $cucourseid=unpack("%32C*",$fucourseid);
9559: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9560: my $cunique=&recunique($fucourseid);
1.474 albertel 9561: my $cpart=unpack("%32S*",$part);
1.835 albertel 9562: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9563:
1.790 albertel 9564: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9565:
9566: $return.= ($cunique%$cuname+
9567: $cunique%$cudom+
9568: $cusymb%$cuname+
9569: $cusymb%$cudom+
9570: $cucourseid%$cuname+
9571: $cucourseid%$cudom+
9572: $cpart%$cuname+
9573: $cpart%$cudom);
9574: } else {
9575: $return.= ($cunique%$cuname+
9576: $cunique%$cudom+
9577: $cusymb%$cuname+
9578: $cusymb%$cudom+
9579: $cucourseid%$cuname+
9580: $cucourseid%$cudom);
9581: }
9582: return $return;
1.76 www 9583: }
9584:
9585: sub receipt {
1.474 albertel 9586: my ($part)=@_;
1.790 albertel 9587: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9588: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9589: }
1.260 ng 9590:
1.790 albertel 9591: sub whichuser {
9592: my ($passedsymb)=@_;
9593: my ($symb,$courseid,$domain,$name,$publicuser);
9594: if (defined($env{'form.grade_symb'})) {
9595: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9596: my $allowed=&allowed('vgr',$tmp_courseid);
9597: if (!$allowed &&
9598: exists($env{'request.course.sec'}) &&
9599: $env{'request.course.sec'} !~ /^\s*$/) {
9600: $allowed=&allowed('vgr',$tmp_courseid.
9601: '/'.$env{'request.course.sec'});
9602: }
9603: if ($allowed) {
9604: ($symb)=&get_env_multiple('form.grade_symb');
9605: $courseid=$tmp_courseid;
9606: ($domain)=&get_env_multiple('form.grade_domain');
9607: ($name)=&get_env_multiple('form.grade_username');
9608: return ($symb,$courseid,$domain,$name,$publicuser);
9609: }
9610: }
9611: if (!$passedsymb) {
9612: $symb=&symbread();
9613: } else {
9614: $symb=$passedsymb;
9615: }
9616: $courseid=$env{'request.course.id'};
9617: $domain=$env{'user.domain'};
9618: $name=$env{'user.name'};
9619: if ($name eq 'public' && $domain eq 'public') {
9620: if (!defined($env{'form.username'})) {
9621: $env{'form.username'}.=time.rand(10000000);
9622: }
9623: $name.=$env{'form.username'};
9624: }
9625: return ($symb,$courseid,$domain,$name,$publicuser);
9626:
9627: }
9628:
1.36 albertel 9629: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9630: # returns either the contents of the file or
9631: # -1 if the file doesn't exist
1.481 raeburn 9632: #
9633: # if the target is a file that was uploaded via DOCS,
9634: # a check will be made to see if a current copy exists on the local server,
9635: # if it does this will be served, otherwise a copy will be retrieved from
9636: # the home server for the course and stored in /home/httpd/html/userfiles on
9637: # the local server.
1.472 albertel 9638:
1.36 albertel 9639: sub getfile {
1.538 albertel 9640: my ($file) = @_;
1.609 banghart 9641: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9642: &repcopy($file);
9643: return &readfile($file);
9644: }
9645:
9646: sub repcopy_userfile {
9647: my ($file)=@_;
1.609 banghart 9648: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9649: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9650: my ($cdom,$cnum,$filename) =
1.811 albertel 9651: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9652: my $uri="/uploaded/$cdom/$cnum/$filename";
9653: if (-e "$file") {
1.828 www 9654: # we already have a local copy, check it out
1.538 albertel 9655: my @fileinfo = stat($file);
1.828 www 9656: my $rtncode;
9657: my $info;
1.538 albertel 9658: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9659: if ($lwpresp ne 'ok') {
1.828 www 9660: # there is no such file anymore, even though we had a local copy
1.482 albertel 9661: if ($rtncode eq '404') {
1.538 albertel 9662: unlink($file);
1.482 albertel 9663: }
9664: return -1;
9665: }
9666: if ($info < $fileinfo[9]) {
1.828 www 9667: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9668: return 'ok';
1.828 www 9669: } else {
9670: # the file is outdated, get rid of it
9671: unlink($file);
1.482 albertel 9672: }
1.828 www 9673: }
9674: # one way or the other, at this point, we don't have the file
9675: # construct the correct path for the file
9676: my @parts = ($cdom,$cnum);
9677: if ($filename =~ m|^(.+)/[^/]+$|) {
9678: push @parts, split(/\//,$1);
9679: }
9680: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9681: foreach my $part (@parts) {
9682: $path .= '/'.$part;
9683: if (!-e $path) {
9684: mkdir($path,0770);
1.482 albertel 9685: }
9686: }
1.828 www 9687: # now the path exists for sure
9688: # get a user agent
9689: my $ua=new LWP::UserAgent;
9690: my $transferfile=$file.'.in.transfer';
9691: # FIXME: this should flock
9692: if (-e $transferfile) { return 'ok'; }
9693: my $request;
9694: $uri=~s/^\///;
1.980 raeburn 9695: my $homeserver = &homeserver($cnum,$cdom);
9696: my $protocol = $protocol{$homeserver};
9697: $protocol = 'http' if ($protocol ne 'https');
9698: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9699: my $response=$ua->request($request,$transferfile);
9700: # did it work?
9701: if ($response->is_error()) {
9702: unlink($transferfile);
9703: &logthis("Userfile repcopy failed for $uri");
9704: return -1;
9705: }
9706: # worked, rename the transfer file
9707: rename($transferfile,$file);
1.607 raeburn 9708: return 'ok';
1.481 raeburn 9709: }
9710:
1.517 albertel 9711: sub tokenwrapper {
9712: my $uri=shift;
1.980 raeburn 9713: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9714: $uri=~s|^/||;
1.620 albertel 9715: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9716: my $token=$1;
1.552 albertel 9717: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9718: if ($udom && $uname && $file) {
9719: $file=~s|(\?\.*)*$||;
1.949 raeburn 9720: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9721: my $homeserver = &homeserver($uname,$udom);
9722: my $protocol = $protocol{$homeserver};
9723: $protocol = 'http' if ($protocol ne 'https');
9724: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9725: (($uri=~/\?/)?'&':'?').'token='.$token.
9726: '&tokenissued='.$perlvar{'lonHostID'};
9727: } else {
9728: return '/adm/notfound.html';
9729: }
9730: }
9731:
1.828 www 9732: # call with reqtype HEAD: get last modification time
9733: # call with reqtype GET: get the file contents
9734: # Do not call this with reqtype GET for large files! It loads everything into memory
9735: #
1.481 raeburn 9736: sub getuploaded {
9737: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9738: $uri=~s/^\///;
1.980 raeburn 9739: my $homeserver = &homeserver($cnum,$cdom);
9740: my $protocol = $protocol{$homeserver};
9741: $protocol = 'http' if ($protocol ne 'https');
9742: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9743: my $ua=new LWP::UserAgent;
9744: my $request=new HTTP::Request($reqtype,$uri);
9745: my $response=$ua->request($request);
9746: $$rtncode = $response->code;
1.482 albertel 9747: if (! $response->is_success()) {
9748: return 'failed';
9749: }
9750: if ($reqtype eq 'HEAD') {
1.486 www 9751: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9752: } elsif ($reqtype eq 'GET') {
9753: $$info = $response->content;
1.472 albertel 9754: }
1.482 albertel 9755: return 'ok';
1.36 albertel 9756: }
9757:
1.481 raeburn 9758: sub readfile {
9759: my $file = shift;
9760: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9761: my $fh;
9762: open($fh,"<$file");
9763: my $a='';
1.800 albertel 9764: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9765: return $a;
9766: }
9767:
1.36 albertel 9768: sub filelocation {
1.590 banghart 9769: my ($dir,$file) = @_;
9770: my $location;
9771: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9772:
9773: if ($file =~ m-^/adm/-) {
9774: $file=~s-^/adm/wrapper/-/-;
9775: $file=~s-^/adm/coursedocs/showdoc/-/-;
9776: }
1.882 albertel 9777:
1.590 banghart 9778: if ($file=~m:^/~:) { # is a contruction space reference
9779: $location = $file;
9780: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9781: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9782: # is a correct contruction space reference
9783: $location = $file;
1.956 raeburn 9784: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9785: $location = $file;
1.609 banghart 9786: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9787: my ($udom,$uname,$filename)=
1.811 albertel 9788: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9789: my $home=&homeserver($uname,$udom);
9790: my $is_me=0;
9791: my @ids=¤t_machine_ids();
9792: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9793: if ($is_me) {
1.955 raeburn 9794: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9795: } else {
9796: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9797: $udom.'/'.$uname.'/'.$filename;
9798: }
1.882 albertel 9799: } elsif ($file =~ m-^/adm/-) {
9800: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9801: } else {
9802: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9803: $file=~s:^/res/:/:;
9804: if ( !( $file =~ m:^/:) ) {
9805: $location = $dir. '/'.$file;
9806: } else {
9807: $location = '/home/httpd/html/res'.$file;
9808: }
1.59 albertel 9809: }
1.590 banghart 9810: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9811: while ($location=~m{/\.\./}) {
9812: if ($location =~ m{/[^/]+/\.\./}) {
9813: $location=~ s{/[^/]+/\.\./}{/}g;
9814: } else {
9815: $location=~ s{/\.\./}{/}g;
9816: }
9817: } #remove dir/..
1.590 banghart 9818: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9819: return $location;
1.46 www 9820: }
1.36 albertel 9821:
1.46 www 9822: sub hreflocation {
9823: my ($dir,$file)=@_;
1.980 raeburn 9824: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9825: $file=filelocation($dir,$file);
1.700 albertel 9826: } elsif ($file=~m-^/adm/-) {
9827: $file=~s-^/adm/wrapper/-/-;
9828: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9829: }
9830: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9831: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9832: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9833: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9834: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9835: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9836: -/uploaded/$1/$2/-x;
1.46 www 9837: }
1.913 albertel 9838: if ($file=~ m{^/userfiles/}) {
9839: $file =~ s{^/userfiles/}{/uploaded/};
9840: }
1.462 albertel 9841: return $file;
1.465 albertel 9842: }
9843:
9844: sub current_machine_domains {
1.853 albertel 9845: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9846: }
9847:
9848: sub machine_domains {
9849: my ($hostname) = @_;
1.465 albertel 9850: my @domains;
1.838 albertel 9851: my %hostname = &all_hostnames();
1.465 albertel 9852: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9853: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9854: if ($hostname eq $name) {
1.844 albertel 9855: push(@domains,&host_domain($id));
1.465 albertel 9856: }
9857: }
9858: return @domains;
9859: }
9860:
9861: sub current_machine_ids {
1.853 albertel 9862: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9863: }
9864:
9865: sub machine_ids {
9866: my ($hostname) = @_;
9867: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9868: my @ids;
1.888 albertel 9869: my %name_to_host = &all_names();
1.889 albertel 9870: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9871: return @{ $name_to_host{$hostname} };
9872: }
9873: return;
1.31 www 9874: }
9875:
1.824 raeburn 9876: sub additional_machine_domains {
9877: my @domains;
9878: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9879: while( my $line = <$fh>) {
9880: $line =~ s/\s//g;
9881: push(@domains,$line);
9882: }
9883: return @domains;
9884: }
9885:
9886: sub default_login_domain {
9887: my $domain = $perlvar{'lonDefDomain'};
9888: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9889: foreach my $posdom (¤t_machine_domains(),
9890: &additional_machine_domains()) {
9891: if (lc($posdom) eq lc($testdomain)) {
9892: $domain=$posdom;
9893: last;
9894: }
9895: }
9896: return $domain;
9897: }
9898:
1.31 www 9899: # ------------------------------------------------------------- Declutters URLs
9900:
9901: sub declutter {
9902: my $thisfn=shift;
1.569 albertel 9903: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9904: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9905: $thisfn=~s/^\///;
1.697 albertel 9906: $thisfn=~s|^adm/wrapper/||;
9907: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9908: $thisfn=~s/^res\///;
1.1032 raeburn 9909: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9910: $thisfn=~s/\?.+$//;
9911: }
1.268 www 9912: return $thisfn;
9913: }
9914:
9915: # ------------------------------------------------------------- Clutter up URLs
9916:
9917: sub clutter {
9918: my $thisfn='/'.&declutter(shift);
1.887 albertel 9919: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9920: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9921: $thisfn='/res'.$thisfn;
9922: }
1.1031 raeburn 9923: if ($thisfn !~m|^/adm|) {
9924: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9925: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9926: } else {
9927: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9928: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9929: if ($embstyle eq 'ssi'
9930: || ($embstyle eq 'hdn')
9931: || ($embstyle eq 'rat')
9932: || ($embstyle eq 'prv')
9933: || ($embstyle eq 'ign')) {
9934: #do nothing with these
9935: } elsif (($embstyle eq 'img')
1.695 albertel 9936: || ($embstyle eq 'emb')
9937: || ($embstyle eq 'wrp')) {
9938: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9939: } elsif ($embstyle eq 'unk'
9940: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9941: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9942: } else {
1.718 www 9943: # &logthis("Got a blank emb style");
1.695 albertel 9944: }
1.694 albertel 9945: }
9946: }
1.31 www 9947: return $thisfn;
1.12 www 9948: }
9949:
1.787 albertel 9950: sub clutter_with_no_wrapper {
9951: my $uri = &clutter(shift);
9952: if ($uri =~ m-^/adm/-) {
9953: $uri =~ s-^/adm/wrapper/-/-;
9954: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9955: }
9956: return $uri;
9957: }
9958:
1.557 albertel 9959: sub freeze_escape {
9960: my ($value)=@_;
9961: if (ref($value)) {
9962: $value=&nfreeze($value);
9963: return '__FROZEN__'.&escape($value);
9964: }
9965: return &escape($value);
9966: }
9967:
1.11 www 9968:
1.557 albertel 9969: sub thaw_unescape {
9970: my ($value)=@_;
9971: if ($value =~ /^__FROZEN__/) {
9972: substr($value,0,10,undef);
9973: $value=&unescape($value);
9974: return &thaw($value);
9975: }
9976: return &unescape($value);
9977: }
9978:
1.436 albertel 9979: sub correct_line_ends {
9980: my ($result)=@_;
9981: $$result =~s/\r\n/\n/mg;
9982: $$result =~s/\r/\n/mg;
1.415 albertel 9983: }
1.1 albertel 9984: # ================================================================ Main Program
9985:
1.184 www 9986: sub goodbye {
1.204 albertel 9987: &logthis("Starting Shut down");
1.443 albertel 9988: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9989: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9990: #converted
1.599 albertel 9991: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9992: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9993: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9994: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9995: #1.1 only
1.870 albertel 9996: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9997: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9998: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9999: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10000: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10001: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10002: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10003: &flushcourselogs();
10004: &logthis("Shutting down");
10005: }
10006:
1.852 albertel 10007: sub get_dns {
1.869 albertel 10008: my ($url,$func,$ignore_cache) = @_;
10009: if (!$ignore_cache) {
10010: my ($content,$cached)=
10011: &Apache::lonnet::is_cached_new('dns',$url);
10012: if ($cached) {
10013: &$func($content);
10014: return;
10015: }
10016: }
10017:
10018: my %alldns;
1.852 albertel 10019: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10020: foreach my $dns (<$config>) {
10021: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10022: my $line = $1;
10023: my ($host,$protocol) = split(/:/,$line);
10024: if ($protocol ne 'https') {
10025: $protocol = 'http';
10026: }
10027: $alldns{$host} = $protocol;
1.869 albertel 10028: }
10029: while (%alldns) {
10030: my ($dns) = keys(%alldns);
1.852 albertel 10031: my $ua=new LWP::UserAgent;
1.979 raeburn 10032: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10033: my $response=$ua->request($request);
1.979 raeburn 10034: delete($alldns{$dns});
1.852 albertel 10035: next if ($response->is_error());
10036: my @content = split("\n",$response->content);
1.869 albertel 10037: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10038: &$func(\@content);
1.869 albertel 10039: return;
1.852 albertel 10040: }
10041: close($config);
1.871 albertel 10042: my $which = (split('/',$url))[3];
10043: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10044: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10045: my @content = <$config>;
10046: &$func(\@content);
10047: return;
1.852 albertel 10048: }
1.327 albertel 10049: # ------------------------------------------------------------ Read domain file
10050: {
1.852 albertel 10051: my $loaded;
1.846 albertel 10052: my %domain;
10053:
1.852 albertel 10054: sub parse_domain_tab {
10055: my ($lines) = @_;
10056: foreach my $line (@$lines) {
10057: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10058:
1.846 albertel 10059: chomp($line);
1.852 albertel 10060: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10061: my %this_domain;
10062: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10063: 'lang_def', 'city', 'longi', 'lati',
10064: 'primary') {
10065: $this_domain{$field} = shift(@elements);
10066: }
10067: $domain{$name} = \%this_domain;
1.852 albertel 10068: }
10069: }
1.864 albertel 10070:
10071: sub reset_domain_info {
10072: undef($loaded);
10073: undef(%domain);
10074: }
10075:
1.852 albertel 10076: sub load_domain_tab {
1.869 albertel 10077: my ($ignore_cache) = @_;
10078: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10079: my $fh;
10080: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10081: my @lines = <$fh>;
10082: &parse_domain_tab(\@lines);
1.448 albertel 10083: }
1.852 albertel 10084: close($fh);
10085: $loaded = 1;
1.327 albertel 10086: }
1.846 albertel 10087:
10088: sub domain {
1.852 albertel 10089: &load_domain_tab() if (!$loaded);
10090:
1.846 albertel 10091: my ($name,$what) = @_;
10092: return if ( !exists($domain{$name}) );
10093:
10094: if (!$what) {
10095: return $domain{$name}{'description'};
10096: }
10097: return $domain{$name}{$what};
10098: }
1.974 raeburn 10099:
10100: sub domain_info {
10101: &load_domain_tab() if (!$loaded);
10102: return %domain;
10103: }
10104:
1.327 albertel 10105: }
10106:
10107:
1.1 albertel 10108: # ------------------------------------------------------------- Read hosts file
10109: {
1.838 albertel 10110: my %hostname;
1.844 albertel 10111: my %hostdom;
1.845 albertel 10112: my %libserv;
1.852 albertel 10113: my $loaded;
1.888 albertel 10114: my %name_to_host;
1.1056.4.6 raeburn 10115: my %internetdom;
1.1056.4.25 raeburn 10116: my %LC_dns_serv;
1.852 albertel 10117:
10118: sub parse_hosts_tab {
10119: my ($file) = @_;
10120: foreach my $configline (@$file) {
10121: next if ($configline =~ /^(\#|\s*$ )/x);
1.1056.4.25 raeburn 10122: chomp($configline);
10123: if ($configline =~ /^\^/) {
10124: if ($configline =~ /^\^([\w.\-]+)/) {
10125: $LC_dns_serv{$1} = 1;
10126: }
10127: next;
10128: }
1.1056.4.6 raeburn 10129: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10130: $name=~s/\s//g;
10131: if ($id && $domain && $role && $name) {
10132: $hostname{$id}=$name;
1.888 albertel 10133: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10134: $hostdom{$id}=$domain;
10135: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10136: if (defined($protocol)) {
10137: if ($protocol eq 'https') {
10138: $protocol{$id} = $protocol;
10139: } else {
10140: $protocol{$id} = 'http';
10141: }
1.968 raeburn 10142: } else {
1.969 raeburn 10143: $protocol{$id} = 'http';
1.968 raeburn 10144: }
1.1056.4.6 raeburn 10145: if (defined($intdom)) {
10146: $internetdom{$id} = $intdom;
10147: }
1.852 albertel 10148: }
10149: }
10150: }
1.864 albertel 10151:
10152: sub reset_hosts_info {
1.897 albertel 10153: &purge_remembered();
1.864 albertel 10154: &reset_domain_info();
10155: &reset_hosts_ip_info();
1.892 albertel 10156: undef(%name_to_host);
1.864 albertel 10157: undef(%hostname);
10158: undef(%hostdom);
10159: undef(%libserv);
10160: undef($loaded);
10161: }
1.1 albertel 10162:
1.852 albertel 10163: sub load_hosts_tab {
1.869 albertel 10164: my ($ignore_cache) = @_;
10165: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10166: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10167: my @config = <$config>;
10168: &parse_hosts_tab(\@config);
10169: close($config);
10170: $loaded=1;
1.1 albertel 10171: }
1.852 albertel 10172:
1.838 albertel 10173: sub hostname {
1.852 albertel 10174: &load_hosts_tab() if (!$loaded);
10175:
1.838 albertel 10176: my ($lonid) = @_;
10177: return $hostname{$lonid};
10178: }
1.845 albertel 10179:
1.838 albertel 10180: sub all_hostnames {
1.852 albertel 10181: &load_hosts_tab() if (!$loaded);
10182:
1.838 albertel 10183: return %hostname;
10184: }
1.845 albertel 10185:
1.888 albertel 10186: sub all_names {
10187: &load_hosts_tab() if (!$loaded);
10188:
10189: return %name_to_host;
10190: }
10191:
1.974 raeburn 10192: sub all_host_domain {
10193: &load_hosts_tab() if (!$loaded);
10194: return %hostdom;
10195: }
10196:
1.845 albertel 10197: sub is_library {
1.852 albertel 10198: &load_hosts_tab() if (!$loaded);
10199:
1.845 albertel 10200: return exists($libserv{$_[0]});
10201: }
10202:
10203: sub all_library {
1.852 albertel 10204: &load_hosts_tab() if (!$loaded);
10205:
1.845 albertel 10206: return %libserv;
10207: }
10208:
1.1056.4.2 raeburn 10209: sub unique_library {
10210: #2x reverse removes all hostnames that appear more than once
10211: my %unique = reverse &all_library();
10212: return reverse %unique;
10213: }
10214:
1.841 albertel 10215: sub get_servers {
1.852 albertel 10216: &load_hosts_tab() if (!$loaded);
10217:
1.841 albertel 10218: my ($domain,$type) = @_;
10219: my %possible_hosts = ($type eq 'library') ? %libserv
10220: : %hostname;
10221: my %result;
1.842 albertel 10222: if (ref($domain) eq 'ARRAY') {
10223: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10224: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10225: $result{$host} = $hostname;
10226: }
10227: }
10228: } else {
10229: while ( my ($host,$hostname) = each(%possible_hosts)) {
10230: if ($hostdom{$host} eq $domain) {
10231: $result{$host} = $hostname;
10232: }
1.841 albertel 10233: }
10234: }
10235: return %result;
10236: }
1.845 albertel 10237:
1.1056.4.2 raeburn 10238: sub get_unique_servers {
10239: my %unique = reverse &get_servers(@_);
10240: return reverse %unique;
10241: }
10242:
1.844 albertel 10243: sub host_domain {
1.852 albertel 10244: &load_hosts_tab() if (!$loaded);
10245:
1.844 albertel 10246: my ($lonid) = @_;
10247: return $hostdom{$lonid};
10248: }
10249:
1.841 albertel 10250: sub all_domains {
1.852 albertel 10251: &load_hosts_tab() if (!$loaded);
10252:
1.841 albertel 10253: my %seen;
10254: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10255: return @uniq;
10256: }
1.1056.4.3 raeburn 10257:
10258: sub internet_dom {
10259: &load_hosts_tab() if (!$loaded);
10260:
10261: my ($lonid) = @_;
10262: return $internetdom{$lonid};
10263: }
1.1056.4.27 raeburn 10264:
10265: sub is_LC_dns {
10266: &load_hosts_tab() if (!$loaded);
10267:
10268: my ($hostname) = @_;
10269: return exists($LC_dns_serv{$hostname});
10270: }
10271:
1.1 albertel 10272: }
10273:
1.847 albertel 10274: {
10275: my %iphost;
1.856 albertel 10276: my %name_to_ip;
10277: my %lonid_to_ip;
1.869 albertel 10278:
1.847 albertel 10279: sub get_hosts_from_ip {
10280: my ($ip) = @_;
10281: my %iphosts = &get_iphost();
10282: if (ref($iphosts{$ip})) {
10283: return @{$iphosts{$ip}};
10284: }
10285: return;
1.839 albertel 10286: }
1.864 albertel 10287:
10288: sub reset_hosts_ip_info {
10289: undef(%iphost);
10290: undef(%name_to_ip);
10291: undef(%lonid_to_ip);
10292: }
1.856 albertel 10293:
10294: sub get_host_ip {
10295: my ($lonid) = @_;
10296: if (exists($lonid_to_ip{$lonid})) {
10297: return $lonid_to_ip{$lonid};
10298: }
10299: my $name=&hostname($lonid);
10300: my $ip = gethostbyname($name);
10301: return if (!$ip || length($ip) ne 4);
10302: $ip=inet_ntoa($ip);
10303: $name_to_ip{$name} = $ip;
10304: $lonid_to_ip{$lonid} = $ip;
10305: return $ip;
10306: }
1.847 albertel 10307:
10308: sub get_iphost {
1.869 albertel 10309: my ($ignore_cache) = @_;
1.894 albertel 10310:
1.869 albertel 10311: if (!$ignore_cache) {
10312: if (%iphost) {
10313: return %iphost;
10314: }
10315: my ($ip_info,$cached)=
10316: &Apache::lonnet::is_cached_new('iphost','iphost');
10317: if ($cached) {
10318: %iphost = %{$ip_info->[0]};
10319: %name_to_ip = %{$ip_info->[1]};
10320: %lonid_to_ip = %{$ip_info->[2]};
10321: return %iphost;
10322: }
10323: }
1.894 albertel 10324:
10325: # get yesterday's info for fallback
10326: my %old_name_to_ip;
10327: my ($ip_info,$cached)=
10328: &Apache::lonnet::is_cached_new('iphost','iphost');
10329: if ($cached) {
10330: %old_name_to_ip = %{$ip_info->[1]};
10331: }
10332:
1.888 albertel 10333: my %name_to_host = &all_names();
10334: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10335: my $ip;
10336: if (!exists($name_to_ip{$name})) {
10337: $ip = gethostbyname($name);
10338: if (!$ip || length($ip) ne 4) {
1.894 albertel 10339: if (defined($old_name_to_ip{$name})) {
10340: $ip = $old_name_to_ip{$name};
10341: &logthis("Can't find $name defaulting to old $ip");
10342: } else {
10343: &logthis("Name $name no IP found");
10344: next;
10345: }
10346: } else {
10347: $ip=inet_ntoa($ip);
1.847 albertel 10348: }
10349: $name_to_ip{$name} = $ip;
10350: } else {
10351: $ip = $name_to_ip{$name};
1.653 albertel 10352: }
1.888 albertel 10353: foreach my $id (@{ $name_to_host{$name} }) {
10354: $lonid_to_ip{$id} = $ip;
10355: }
10356: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10357: }
1.869 albertel 10358: &Apache::lonnet::do_cache_new('iphost','iphost',
10359: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10360: 48*60*60);
1.869 albertel 10361:
1.847 albertel 10362: return %iphost;
1.598 albertel 10363: }
10364:
1.992 raeburn 10365: #
10366: # Given a DNS returns the loncapa host name for that DNS
10367: #
10368: sub host_from_dns {
10369: my ($dns) = @_;
10370: my @hosts;
10371: my $ip;
10372:
1.993 raeburn 10373: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10374: $ip = $name_to_ip{$dns};
10375: }
10376: if (!$ip) {
10377: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10378: if (length($ip) == 4) {
10379: $ip = &IO::Socket::inet_ntoa($ip);
10380: }
10381: }
10382: if ($ip) {
10383: @hosts = get_hosts_from_ip($ip);
10384: return $hosts[0];
10385: }
10386: return undef;
1.986 foxr 10387: }
1.992 raeburn 10388:
1.1056.4.3 raeburn 10389: sub get_internet_names {
10390: my ($lonid) = @_;
10391: return if ($lonid eq '');
10392: my ($idnref,$cached)=
10393: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10394: if ($cached) {
10395: return $idnref;
10396: }
10397: my $ip = &get_host_ip($lonid);
10398: my @hosts = &get_hosts_from_ip($ip);
10399: my %iphost = &get_iphost();
10400: my (@idns,%seen);
10401: foreach my $id (@hosts) {
10402: my $dom = &host_domain($id);
10403: my $prim_id = &domain($dom,'primary');
10404: my $prim_ip = &get_host_ip($prim_id);
10405: next if ($seen{$prim_ip});
10406: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10407: foreach my $id (@{$iphost{$prim_ip}}) {
10408: my $intdom = &internet_dom($id);
10409: unless (grep(/^\Q$intdom\E$/,@idns)) {
10410: push(@idns,$intdom);
10411: }
10412: }
10413: }
10414: $seen{$prim_ip} = 1;
10415: }
10416: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10417: }
10418:
10419: }
10420:
10421: sub all_loncaparevs {
10422: 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 10423: }
10424:
1.862 albertel 10425: BEGIN {
10426:
10427: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10428: unless ($readit) {
10429: {
10430: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10431: %perlvar = (%perlvar,%{$configvars});
10432: }
10433:
10434:
1.1 albertel 10435: # ------------------------------------------------------ Read spare server file
10436: {
1.448 albertel 10437: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10438:
10439: while (my $configline=<$config>) {
10440: chomp($configline);
1.284 matthew 10441: if ($configline) {
1.784 albertel 10442: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10443: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10444: push(@{ $spareid{$type} }, $host);
1.1 albertel 10445: }
10446: }
1.448 albertel 10447: close($config);
1.1 albertel 10448: }
1.11 www 10449: # ------------------------------------------------------------ Read permissions
10450: {
1.448 albertel 10451: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10452:
10453: while (my $configline=<$config>) {
1.448 albertel 10454: chomp($configline);
10455: if ($configline) {
10456: my ($role,$perm)=split(/ /,$configline);
10457: if ($perm ne '') { $pr{$role}=$perm; }
10458: }
1.11 www 10459: }
1.448 albertel 10460: close($config);
1.11 www 10461: }
10462:
10463: # -------------------------------------------- Read plain texts for permissions
10464: {
1.448 albertel 10465: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10466:
10467: while (my $configline=<$config>) {
1.448 albertel 10468: chomp($configline);
10469: if ($configline) {
1.742 raeburn 10470: my ($short,@plain)=split(/:/,$configline);
10471: %{$prp{$short}} = ();
10472: if (@plain > 0) {
10473: $prp{$short}{'std'} = $plain[0];
10474: for (my $i=1; $i<@plain; $i++) {
10475: $prp{$short}{'alt'.$i} = $plain[$i];
10476: }
10477: }
1.448 albertel 10478: }
1.135 www 10479: }
1.448 albertel 10480: close($config);
1.135 www 10481: }
10482:
10483: # ---------------------------------------------------------- Read package table
10484: {
1.448 albertel 10485: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10486:
10487: while (my $configline=<$config>) {
1.483 albertel 10488: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10489: chomp($configline);
10490: my ($short,$plain)=split(/:/,$configline);
10491: my ($pack,$name)=split(/\&/,$short);
10492: if ($plain ne '') {
10493: $packagetab{$pack.'&'.$name.'&name'}=$name;
10494: $packagetab{$short}=$plain;
10495: }
1.11 www 10496: }
1.448 albertel 10497: close($config);
1.329 matthew 10498: }
10499:
1.1056.4.3 raeburn 10500: # ---------------------------------------------------------- Read loncaparev table
10501: {
10502: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10503: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10504: while (my $configline=<$config>) {
10505: chomp($configline);
10506: my ($hostid,$loncaparev)=split(/:/,$configline);
10507: $loncaparevs{$hostid}=$loncaparev;
10508: }
10509: close($config);
10510: }
10511: }
10512: }
10513:
10514: # ---------------------------------------------------------- Read serverhostID table
10515: {
10516: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10517: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10518: while (my $configline=<$config>) {
10519: chomp($configline);
10520: my ($name,$id)=split(/:/,$configline);
10521: $serverhomeIDs{$name}=$id;
10522: }
10523: close($config);
10524: }
10525: }
10526: }
10527:
1.1056.4.5 raeburn 10528: {
10529: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10530: if (-e $file) {
10531: my $parser = HTML::LCParser->new($file);
10532: while (my $token = $parser->get_token()) {
10533: if ($token->[0] eq 'S') {
10534: my $item = $token->[1];
10535: my $name = $token->[2]{'name'};
10536: my $value = $token->[2]{'value'};
10537: if ($item ne '' && $name ne '' && $value ne '') {
10538: my $release = $parser->get_text();
10539: $release =~ s/(^\s*|\s*$ )//gx;
10540: $needsrelease{$item.':'.$name.':'.$value} = $release;
10541: }
10542: }
10543: }
10544: }
10545: }
10546:
1.329 matthew 10547: # ------------- set up temporary directory
10548: {
10549: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10550:
1.11 www 10551: }
10552:
1.794 albertel 10553: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10554: 'compress_threshold'=> 20_000,
10555: });
1.185 www 10556:
1.281 www 10557: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10558: $dumpcount=0;
1.958 www 10559: $locknum=0;
1.22 www 10560:
1.163 harris41 10561: &logtouch();
1.672 albertel 10562: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10563: $readit=1;
1.564 albertel 10564: {
10565: use integer;
10566: my $test=(2**32)+1;
1.568 albertel 10567: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10568: &logthis(" Detected 64bit platform ($_64bit)");
10569: }
1.195 www 10570: }
1.1 albertel 10571: }
1.179 www 10572:
1.1 albertel 10573: 1;
1.191 harris41 10574: __END__
10575:
1.243 albertel 10576: =pod
10577:
1.191 harris41 10578: =head1 NAME
10579:
1.243 albertel 10580: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10581:
10582: =head1 SYNOPSIS
10583:
1.243 albertel 10584: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10585:
10586: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10587:
1.243 albertel 10588: Common parameters:
10589:
10590: =over 4
10591:
10592: =item *
10593:
10594: $uname : an internal username (if $cname expecting a course Id specifically)
10595:
10596: =item *
10597:
10598: $udom : a domain (if $cdom expecting a course's domain specifically)
10599:
10600: =item *
10601:
10602: $symb : a resource instance identifier
10603:
10604: =item *
10605:
10606: $namespace : the name of a .db file that contains the data needed or
10607: being set.
10608:
10609: =back
10610:
1.394 bowersj2 10611: =head1 OVERVIEW
1.191 harris41 10612:
1.394 bowersj2 10613: lonnet provides subroutines which interact with the
10614: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10615: about classes, users, and resources.
1.243 albertel 10616:
10617: For many of these objects you can also use this to store data about
10618: them or modify them in various ways.
1.191 harris41 10619:
1.394 bowersj2 10620: =head2 Symbs
1.191 harris41 10621:
1.394 bowersj2 10622: To identify a specific instance of a resource, LON-CAPA uses symbols
10623: or "symbs"X<symb>. These identifiers are built from the URL of the
10624: map, the resource number of the resource in the map, and the URL of
10625: the resource itself. The latter is somewhat redundant, but might help
10626: if maps change.
10627:
10628: An example is
10629:
10630: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10631:
10632: The respective map entry is
10633:
10634: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10635: title="Problem 2">
10636: </resource>
10637:
10638: Symbs are used by the random number generator, as well as to store and
10639: restore data specific to a certain instance of for example a problem.
10640:
10641: =head2 Storing And Retrieving Data
10642:
10643: X<store()>X<cstore()>X<restore()>Three of the most important functions
10644: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10645: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10646: is is the non-critical message twin of cstore. These functions are for
10647: handlers to store a perl hash to a user's permanent data space in an
10648: easy manner, and to retrieve it again on another call. It is expected
10649: that a handler would use this once at the beginning to retrieve data,
10650: and then again once at the end to send only the new data back.
10651:
10652: The data is stored in the user's data directory on the user's
10653: homeserver under the ID of the course.
10654:
10655: The hash that is returned by restore will have all of the previous
10656: value for all of the elements of the hash.
10657:
10658: Example:
10659:
10660: #creating a hash
10661: my %hash;
10662: $hash{'foo'}='bar';
10663:
10664: #storing it
10665: &Apache::lonnet::cstore(\%hash);
10666:
10667: #changing a value
10668: $hash{'foo'}='notbar';
10669:
10670: #adding a new value
10671: $hash{'bar'}='foo';
10672: &Apache::lonnet::cstore(\%hash);
10673:
10674: #retrieving the hash
10675: my %history=&Apache::lonnet::restore();
10676:
10677: #print the hash
10678: foreach my $key (sort(keys(%history))) {
10679: print("\%history{$key} = $history{$key}");
10680: }
10681:
10682: Will print out:
1.191 harris41 10683:
1.394 bowersj2 10684: %history{1:foo} = bar
10685: %history{1:keys} = foo:timestamp
10686: %history{1:timestamp} = 990455579
10687: %history{2:bar} = foo
10688: %history{2:foo} = notbar
10689: %history{2:keys} = foo:bar:timestamp
10690: %history{2:timestamp} = 990455580
10691: %history{bar} = foo
10692: %history{foo} = notbar
10693: %history{timestamp} = 990455580
10694: %history{version} = 2
10695:
10696: Note that the special hash entries C<keys>, C<version> and
10697: C<timestamp> were added to the hash. C<version> will be equal to the
10698: total number of versions of the data that have been stored. The
10699: C<timestamp> attribute will be the UNIX time the hash was
10700: stored. C<keys> is available in every historical section to list which
10701: keys were added or changed at a specific historical revision of a
10702: hash.
10703:
10704: B<Warning>: do not store the hash that restore returns directly. This
10705: will cause a mess since it will restore the historical keys as if the
10706: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10707:
1.394 bowersj2 10708: Calling convention:
1.191 harris41 10709:
1.394 bowersj2 10710: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10711: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10712:
1.394 bowersj2 10713: For more detailed information, see lonnet specific documentation.
1.191 harris41 10714:
1.394 bowersj2 10715: =head1 RETURN MESSAGES
1.191 harris41 10716:
1.394 bowersj2 10717: =over 4
1.191 harris41 10718:
1.394 bowersj2 10719: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10720:
1.394 bowersj2 10721: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10722: when the connection is brought back up
1.191 harris41 10723:
1.394 bowersj2 10724: =item * B<con_failed>: unable to contact remote host and unable to save message
10725: for later delivery
1.191 harris41 10726:
1.967 bisitz 10727: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10728:
1.394 bowersj2 10729: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10730: that was requested
1.191 harris41 10731:
1.243 albertel 10732: =back
1.191 harris41 10733:
1.243 albertel 10734: =head1 PUBLIC SUBROUTINES
1.191 harris41 10735:
1.243 albertel 10736: =head2 Session Environment Functions
1.191 harris41 10737:
1.243 albertel 10738: =over 4
1.191 harris41 10739:
1.394 bowersj2 10740: =item *
10741: X<appenv()>
1.949 raeburn 10742: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10743: the user envirnoment file, and will be restored for each access this
1.620 albertel 10744: user makes during this session, also modifies the %env for the current
1.949 raeburn 10745: process. Optional rolesarrayref - if defined contains a reference to an array
10746: of roles which are exempt from the restriction on modifying user.role entries
10747: in the user's environment.db and in %env.
1.191 harris41 10748:
10749: =item *
1.394 bowersj2 10750: X<delenv()>
1.987 raeburn 10751: B<delenv($delthis,$regexp)>: removes all items from the session
10752: environment file that begin with $delthis. If the
10753: optional second arg - $regexp - is true, $delthis is treated as a
10754: regular expression, otherwise \Q$delthis\E is used.
10755: The values are also deleted from the current processes %env.
1.191 harris41 10756:
1.795 albertel 10757: =item * get_env_multiple($name)
10758:
10759: gets $name from the %env hash, it seemlessly handles the cases where multiple
10760: values may be defined and end up as an array ref.
10761:
10762: returns an array of values
10763:
1.243 albertel 10764: =back
10765:
10766: =head2 User Information
1.191 harris41 10767:
1.243 albertel 10768: =over 4
1.191 harris41 10769:
10770: =item *
1.394 bowersj2 10771: X<queryauthenticate()>
10772: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10773: authentication scheme
10774:
10775: =item *
1.394 bowersj2 10776: X<authenticate()>
1.1056.4.3 raeburn 10777: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10778: authenticate user from domain's lib servers (first use the current
10779: one). C<$upass> should be the users password.
1.1056.4.3 raeburn 10780: $checkdefauth is optional (value is 1 if a check should be made to
10781: authenticate user using default authentication method, and allow
10782: account creation if username does not have account in the domain).
10783: $clientcancheckhost is optional (value is 1 if checking whether the
10784: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10785:
10786: =item *
1.394 bowersj2 10787: X<homeserver()>
10788: B<homeserver($uname,$udom)>: find the server which has
10789: the user's directory and files (there must be only one), this caches
10790: the answer, and also caches if there is a borken connection.
1.191 harris41 10791:
10792: =item *
1.394 bowersj2 10793: X<idget()>
10794: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10795: (IDs are a unique resource in a domain, there must be only 1 ID per
10796: username, and only 1 username per ID in a specific domain) (returns
10797: hash: id=>name,id=>name)
1.191 harris41 10798:
10799: =item *
1.394 bowersj2 10800: X<idrget()>
10801: B<idrget($udom,@unames)>: find the IDs behind a list of
10802: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10803:
10804: =item *
1.394 bowersj2 10805: X<idput()>
10806: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10807:
10808: =item *
1.394 bowersj2 10809: X<rolesinit()>
10810: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10811:
10812: =item *
1.551 albertel 10813: X<getsection()>
10814: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10815: course $cname, return section name/number or '' for "not in course"
10816: and '-1' for "no section"
10817:
10818: =item *
1.394 bowersj2 10819: X<userenvironment()>
10820: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10821: passed in @what from the requested user's environment, returns a hash
10822:
1.858 raeburn 10823: =item *
10824: X<userlog_query()>
1.859 albertel 10825: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10826: activity.log file. %filters defines filters applied when parsing the
10827: log file. These can be start or end timestamps, or the type of action
10828: - log to look for Login or Logout events, check for Checkin or
10829: Checkout, role for role selection. The response is in the form
10830: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10831: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10832:
1.243 albertel 10833: =back
10834:
10835: =head2 User Roles
10836:
10837: =over 4
10838:
10839: =item *
10840:
1.810 raeburn 10841: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10842: F: full access
10843: U,I,K: authentication modes (cxx only)
10844: '': forbidden
10845: 1: user needs to choose course
10846: 2: browse allowed
1.766 albertel 10847: A: passphrase authentication needed
1.243 albertel 10848:
10849: =item *
10850:
10851: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10852: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10853: and course level
10854:
10855: =item *
10856:
1.988 raeburn 10857: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10858: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10859: $type is Course (default) or Community.
1.988 raeburn 10860: If $forcedefault evaluates to true, text returned will be default
10861: text for $type. Otherwise, if this is a course, the text returned
10862: will be a custom name for the role (if defined in the course's
10863: environment). If no custom name is defined the default is returned.
10864:
1.832 raeburn 10865: =item *
10866:
1.935 raeburn 10867: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10868: All arguments are optional. Returns a hash of a roles, either for
10869: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10870: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10871: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10872: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10873: For each key, value is set to colon-separated start and end times for
10874: the role. If no username and domain are specified, will default to
1.934 raeburn 10875: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10876: of role statuses (active, future or previous), roles
10877: (e.g., cc,in, st etc.) and domains of the roles which can be used
10878: to restrict the list of roles reported. If no array ref is
10879: provided for types, will default to return only active roles.
1.834 albertel 10880:
1.243 albertel 10881: =back
10882:
10883: =head2 User Modification
10884:
10885: =over 4
10886:
10887: =item *
10888:
1.957 raeburn 10889: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10890: user for the level given by URL. Optional start and end dates (leave empty
10891: string or zero for "no date")
1.191 harris41 10892:
10893: =item *
10894:
1.243 albertel 10895: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10896: change a users, password, possible return values are: ok,
10897: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10898: refused
1.191 harris41 10899:
10900: =item *
10901:
1.243 albertel 10902: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10903:
10904: =item *
10905:
1.1056.4.1 raeburn 10906: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10907: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10908:
10909: will update user information (firstname,middlename,lastname,generation,
10910: permanentemail), and if forceid is true, student/employee ID also.
10911: A user's institutional affiliation(s) can also be updated.
10912: User information fields will not be overwritten with empty entries
10913: unless the field is included in the $candelete array reference.
10914: This array is included when a single user is modified via "Manage Users",
10915: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10916:
10917: =item *
10918:
1.286 matthew 10919: modifystudent
10920:
1.957 raeburn 10921: modify a student's enrollment and identification information.
1.286 matthew 10922: The course id is resolved based on the current users environment.
10923: This means the envoking user must be a course coordinator or otherwise
10924: associated with a course.
10925:
1.297 matthew 10926: This call is essentially a wrapper for lonnet::modifyuser and
10927: lonnet::modify_student_enrollment
1.286 matthew 10928:
10929: Inputs:
10930:
10931: =over 4
10932:
1.957 raeburn 10933: =item B<$udom> Student's loncapa domain
1.286 matthew 10934:
1.957 raeburn 10935: =item B<$uname> Student's loncapa login name
1.286 matthew 10936:
1.964 bisitz 10937: =item B<$uid> Student/Employee ID
1.286 matthew 10938:
1.957 raeburn 10939: =item B<$umode> Student's authentication mode
1.286 matthew 10940:
1.957 raeburn 10941: =item B<$upass> Student's password
1.286 matthew 10942:
1.957 raeburn 10943: =item B<$first> Student's first name
1.286 matthew 10944:
1.957 raeburn 10945: =item B<$middle> Student's middle name
1.286 matthew 10946:
1.957 raeburn 10947: =item B<$last> Student's last name
1.286 matthew 10948:
1.957 raeburn 10949: =item B<$gene> Student's generation
1.286 matthew 10950:
1.957 raeburn 10951: =item B<$usec> Student's section in course
1.286 matthew 10952:
10953: =item B<$end> Unix time of the roles expiration
10954:
10955: =item B<$start> Unix time of the roles start date
10956:
10957: =item B<$forceid> If defined, allow $uid to be changed
10958:
10959: =item B<$desiredhome> server to use as home server for student
10960:
1.957 raeburn 10961: =item B<$email> Student's permanent e-mail address
10962:
10963: =item B<$type> Type of enrollment (auto or manual)
10964:
1.963 raeburn 10965: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10966:
10967: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10968:
1.963 raeburn 10969: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10970:
1.963 raeburn 10971: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10972:
1.963 raeburn 10973: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10974:
1.286 matthew 10975: =back
1.297 matthew 10976:
10977: =item *
10978:
10979: modify_student_enrollment
10980:
10981: Change a students enrollment status in a class. The environment variable
10982: 'role.request.course' must be defined for this function to proceed.
10983:
10984: Inputs:
10985:
10986: =over 4
10987:
10988: =item $udom, students domain
10989:
10990: =item $uname, students name
10991:
10992: =item $uid, students user id
10993:
10994: =item $first, students first name
10995:
10996: =item $middle
10997:
10998: =item $last
10999:
11000: =item $gene
11001:
11002: =item $usec
11003:
11004: =item $end
11005:
11006: =item $start
11007:
1.957 raeburn 11008: =item $type
11009:
11010: =item $locktype
11011:
11012: =item $cid
11013:
11014: =item $selfenroll
11015:
11016: =item $context
11017:
1.297 matthew 11018: =back
11019:
1.191 harris41 11020:
11021: =item *
11022:
1.243 albertel 11023: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11024: custom role; give a custom role to a user for the level given by URL. Specify
11025: name and domain of role author, and role name
1.191 harris41 11026:
11027: =item *
11028:
1.243 albertel 11029: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11030:
11031: =item *
11032:
1.243 albertel 11033: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11034:
11035: =back
11036:
11037: =head2 Course Infomation
11038:
11039: =over 4
1.191 harris41 11040:
11041: =item *
11042:
1.631 albertel 11043: coursedescription($courseid) : returns a hash of information about the
11044: specified course id, including all environment settings for the
11045: course, the description of the course will be in the hash under the
11046: key 'description'
1.191 harris41 11047:
11048: =item *
11049:
1.624 albertel 11050: resdata($name,$domain,$type,@which) : request for current parameter
11051: setting for a specific $type, where $type is either 'course' or 'user',
11052: @what should be a list of parameters to ask about. This routine caches
11053: answers for 5 minutes.
1.243 albertel 11054:
1.877 foxr 11055: =item *
11056:
11057: get_courseresdata($courseid, $domain) : dump the entire course resource
11058: data base, returning a hash that is keyed by the resource name and has
11059: values that are the resource value. I believe that the timestamps and
11060: versions are also returned.
11061:
11062:
1.243 albertel 11063: =back
11064:
11065: =head2 Course Modification
11066:
11067: =over 4
1.191 harris41 11068:
11069: =item *
11070:
1.243 albertel 11071: writecoursepref($courseid,%prefs) : write preferences (environment
11072: database) for a course
1.191 harris41 11073:
11074: =item *
11075:
1.1011 raeburn 11076: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11077:
11078: =item *
11079:
1.1038 raeburn 11080: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11081:
11082: =back
11083:
11084: =head2 Resource Subroutines
11085:
11086: =over 4
1.191 harris41 11087:
11088: =item *
11089:
1.243 albertel 11090: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11091:
11092: =item *
11093:
1.243 albertel 11094: repcopy($filename) : subscribes to the requested file, and attempts to
11095: replicate from the owning library server, Might return
1.607 raeburn 11096: 'unavailable', 'not_found', 'forbidden', 'ok', or
11097: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11098: resource. Expects the local filesystem pathname
11099: (/home/httpd/html/res/....)
11100:
11101: =back
11102:
11103: =head2 Resource Information
11104:
11105: =over 4
1.191 harris41 11106:
11107: =item *
11108:
1.243 albertel 11109: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11110: a vairety of different possible values, $varname should be a request
11111: string, and the other parameters can be used to specify who and what
11112: one is asking about.
11113:
11114: Possible values for $varname are environment.lastname (or other item
11115: from the envirnment hash), user.name (or someother aspect about the
11116: user), resource.0.maxtries (or some other part and parameter of a
11117: resource)
1.204 albertel 11118:
11119: =item *
11120:
1.243 albertel 11121: directcondval($number) : get current value of a condition; reads from a state
11122: string
1.204 albertel 11123:
11124: =item *
11125:
1.243 albertel 11126: condval($condidx) : value of condition index based on state
1.204 albertel 11127:
11128: =item *
11129:
1.243 albertel 11130: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11131: resource's metadata, $what should be either a specific key, or either
11132: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11133: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11134:
11135: this function automatically caches all requests
1.191 harris41 11136:
11137: =item *
11138:
1.243 albertel 11139: metadata_query($query,$custom,$customshow) : make a metadata query against the
11140: network of library servers; returns file handle of where SQL and regex results
11141: will be stored for query
1.191 harris41 11142:
11143: =item *
11144:
1.243 albertel 11145: symbread($filename) : return symbolic list entry (filename argument optional);
11146: returns the data handle
1.191 harris41 11147:
11148: =item *
11149:
1.243 albertel 11150: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11151: a possible symb for the URL in $thisfn, and if is an encryypted
11152: resource that the user accessed using /enc/ returns a 1 on success, 0
11153: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11154: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11155:
1.191 harris41 11156:
11157: =item *
11158:
1.243 albertel 11159: symbclean($symb) : removes versions numbers from a symb, returns the
11160: cleaned symb
1.191 harris41 11161:
11162: =item *
11163:
1.243 albertel 11164: is_on_map($uri) : checks if the $uri is somewhere on the current
11165: course map, user must be in a course for it to work.
1.191 harris41 11166:
11167: =item *
11168:
1.243 albertel 11169: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11170:
11171: =item *
11172:
1.243 albertel 11173: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11174: a random seed, all arguments are optional, if they aren't sent it uses the
11175: environment to derive them. Note: if symb isn't sent and it can't get one
11176: from &symbread it will use the current time as its return value
1.191 harris41 11177:
11178: =item *
11179:
1.243 albertel 11180: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11181: unfakeable, receipt
1.191 harris41 11182:
11183: =item *
11184:
1.620 albertel 11185: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11186:
11187: =item *
11188:
1.243 albertel 11189: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11190:
11191: =item *
11192:
1.243 albertel 11193: 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 11194:
11195: =item *
11196:
1.243 albertel 11197: 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 11198:
11199: =item *
11200:
1.243 albertel 11201: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11202:
11203: =item *
11204:
1.243 albertel 11205: devalidate($symb) : devalidate temporary spreadsheet calculations,
11206: forcing spreadsheet to reevaluate the resource scores next time.
11207:
11208: =back
11209:
11210: =head2 Storing/Retreiving Data
11211:
11212: =over 4
1.191 harris41 11213:
11214: =item *
11215:
1.243 albertel 11216: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11217: for this url; hashref needs to be given and should be a \%hashname; the
11218: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11219: be derived from the env
1.191 harris41 11220:
11221: =item *
11222:
1.243 albertel 11223: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11224: uses critical subroutine
1.191 harris41 11225:
11226: =item *
11227:
1.243 albertel 11228: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11229: all args are optional
1.191 harris41 11230:
11231: =item *
11232:
1.717 albertel 11233: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11234: dumps the complete (or key matching regexp) namespace into a hash
11235: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11236: normally &store()ed into
11237:
11238: $range should be either an integer '100' (give me the first 100
11239: matching records)
11240: or be two integers sperated by a - with no spaces
11241: '30-50' (give me the 30th through the 50th matching
11242: records)
11243:
11244:
11245: =item *
11246:
11247: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11248: replaces a &store() version of data with a replacement set of data
11249: for a particular resource in a namespace passed in the $storehash hash
11250: reference
11251:
11252: =item *
11253:
1.243 albertel 11254: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11255: works very similar to store/cstore, but all data is stored in a
11256: temporary location and can be reset using tmpreset, $storehash should
11257: be a hash reference, returns nothing on success
1.191 harris41 11258:
11259: =item *
11260:
1.243 albertel 11261: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11262: similar to restore, but all data is stored in a temporary location and
11263: can be reset using tmpreset. Returns a hash of values on success,
11264: error string otherwise.
1.191 harris41 11265:
11266: =item *
11267:
1.243 albertel 11268: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11269: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11270:
11271: =item *
11272:
1.243 albertel 11273: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11274: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11275:
11276: =item *
11277:
1.243 albertel 11278: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11279: namesp ($udom and $uname are optional)
1.191 harris41 11280:
11281: =item *
11282:
1.702 albertel 11283: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11284: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11285: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11286:
1.702 albertel 11287: $range should be either an integer '100' (give me the first 100
11288: matching records)
11289: or be two integers sperated by a - with no spaces
11290: '30-50' (give me the 30th through the 50th matching
11291: records)
1.449 matthew 11292: =item *
11293:
11294: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11295: $store can be a scalar, an array reference, or if the amount to be
11296: incremented is > 1, a hash reference.
11297:
11298: ($udom and $uname are optional)
1.191 harris41 11299:
11300: =item *
11301:
1.243 albertel 11302: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11303: ($udom and $uname are optional)
1.191 harris41 11304:
11305: =item *
11306:
1.243 albertel 11307: cput($namespace,$storehash,$udom,$uname) : critical put
11308: ($udom and $uname are optional)
1.191 harris41 11309:
11310: =item *
11311:
1.748 albertel 11312: newput($namespace,$storehash,$udom,$uname) :
11313:
11314: Attempts to store the items in the $storehash, but only if they don't
11315: currently exist, if this succeeds you can be certain that you have
11316: successfully created a new key value pair in the $namespace db.
11317:
11318:
11319: Args:
11320: $namespace: name of database to store values to
11321: $storehash: hashref to store to the db
11322: $udom: (optional) domain of user containing the db
11323: $uname: (optional) name of user caontaining the db
11324:
11325: Returns:
11326: 'ok' -> succeeded in storing all keys of $storehash
11327: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11328: least <key> already existed in the db (other
11329: requested keys may also already exist)
1.967 bisitz 11330: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11331: 'con_lost' -> unable to contact request server
11332: 'refused' -> action was not allowed by remote machine
11333:
11334:
11335: =item *
11336:
1.243 albertel 11337: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11338: reference filled in from namesp (encrypts the return communication)
11339: ($udom and $uname are optional)
1.191 harris41 11340:
11341: =item *
11342:
1.243 albertel 11343: log($udom,$name,$home,$message) : write to permanent log for user; use
11344: critical subroutine
11345:
1.806 raeburn 11346: =item *
11347:
1.860 raeburn 11348: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11349: array reference filled in from namespace found in domain level on either
11350: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11351:
11352: =item *
11353:
1.860 raeburn 11354: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11355: domain level either on specified domain server ($uhome) or primary domain
11356: server ($udom and $uhome are optional)
1.806 raeburn 11357:
1.943 raeburn 11358: =item *
11359:
11360: get_domain_defaults($target_domain) : returns hash with defaults for
11361: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11362: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11363: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11364: Values are retrieved from cache (if current), or from domain's configuration.db
11365: (if available), or lastly from values in lonTabs/dns_domain,tab,
11366: or lonTabs/domain.tab.
11367:
11368: %domdefaults = &get_auth_defaults($target_domain);
11369:
1.243 albertel 11370: =back
11371:
11372: =head2 Network Status Functions
11373:
11374: =over 4
1.191 harris41 11375:
11376: =item *
11377:
11378: dirlist($uri) : return directory list based on URI
11379:
11380: =item *
11381:
1.243 albertel 11382: spareserver() : find server with least workload from spare.tab
11383:
1.986 foxr 11384:
11385: =item *
11386:
11387: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11388: if there is no corresponding loncapa host.
11389:
1.243 albertel 11390: =back
11391:
1.986 foxr 11392:
1.243 albertel 11393: =head2 Apache Request
11394:
11395: =over 4
1.191 harris41 11396:
11397: =item *
11398:
1.243 albertel 11399: ssi($url,%hash) : server side include, does a complete request cycle on url to
11400: localhost, posts hash
11401:
11402: =back
11403:
11404: =head2 Data to String to Data
11405:
11406: =over 4
1.191 harris41 11407:
11408: =item *
11409:
1.243 albertel 11410: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11411: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11412:
11413: =item *
11414:
1.243 albertel 11415: hashref2str($hashref) : convert a hashref into a string complete with
11416: escaping and '=' and '&' separators, supports elements that are
11417: arrayrefs and hashrefs
1.191 harris41 11418:
11419: =item *
11420:
1.243 albertel 11421: arrayref2str($arrayref) : convert an arrayref into a string complete
11422: with escaping and '&' separators, supports elements that are arrayrefs
11423: and hashrefs
1.191 harris41 11424:
11425: =item *
11426:
1.243 albertel 11427: str2hash($string) : convert string to hash using unescaping and
11428: splitting on '=' and '&', supports elements that are arrayrefs and
11429: hashrefs
1.191 harris41 11430:
11431: =item *
11432:
1.243 albertel 11433: str2array($string) : convert string to hash using unescaping and
11434: splitting on '&', supports elements that are arrayrefs and hashrefs
11435:
11436: =back
11437:
11438: =head2 Logging Routines
11439:
11440: These routines allow one to make log messages in the lonnet.log and
11441: lonnet.perm logfiles.
1.191 harris41 11442:
1.1056.4.31 raeburn 11443: =over 4
11444:
1.191 harris41 11445: =item *
11446:
1.243 albertel 11447: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11448:
11449: =item *
11450:
1.243 albertel 11451: logthis() : append message to the normal lonnet.log file, it gets
11452: preiodically rolled over and deleted.
1.191 harris41 11453:
11454: =item *
11455:
1.243 albertel 11456: logperm() : append a permanent message to lonnet.perm.log, this log
11457: file never gets deleted by any automated portion of the system, only
11458: messages of critical importance should go in here.
11459:
11460: =back
11461:
11462: =head2 General File Helper Routines
11463:
11464: =over 4
1.191 harris41 11465:
11466: =item *
11467:
1.481 raeburn 11468: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11469: (a) files in /uploaded
11470: (i) If a local copy of the file exists -
11471: compares modification date of local copy with last-modified date for
11472: definitive version stored on home server for course. If local copy is
11473: stale, requests a new version from the home server and stores it.
11474: If the original has been removed from the home server, then local copy
11475: is unlinked.
11476: (ii) If local copy does not exist -
11477: requests the file from the home server and stores it.
11478:
11479: If $caller is 'uploadrep':
11480: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11481: for request for files originally uploaded via DOCS.
11482: - returns 'ok' if fresh local copy now available, -1 otherwise.
11483:
11484: Otherwise:
11485: This indicates a call from the content generation phase of the request.
11486: - returns the entire contents of the file or -1.
11487:
11488: (b) files in /res
11489: - returns the entire contents of a file or -1;
11490: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11491:
1.712 albertel 11492:
11493: =item *
11494:
11495: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11496: reference
11497:
11498: returns either a stat() list of data about the file or an empty list
11499: if the file doesn't exist or couldn't find out about it (connection
11500: problems or user unknown)
11501:
1.191 harris41 11502: =item *
11503:
1.243 albertel 11504: filelocation($dir,$file) : returns file system location of a file
11505: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11506: directory that relative $file lookups are to looked in ($dir of /a/dir
11507: and a file of ../bob will become /a/bob)
1.191 harris41 11508:
11509: =item *
11510:
11511: hreflocation($dir,$file) : returns file system location or a URL; same as
11512: filelocation except for hrefs
11513:
11514: =item *
11515:
11516: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11517:
1.243 albertel 11518: =back
11519:
1.608 albertel 11520: =head2 Usererfile file routines (/uploaded*)
11521:
11522: =over 4
11523:
11524: =item *
11525:
11526: userfileupload(): main rotine for putting a file in a user or course's
11527: filespace, arguments are,
11528:
1.620 albertel 11529: formname - required - this is the name of the element in $env where the
1.608 albertel 11530: filename, and the contents of the file to create/modifed exist
1.620 albertel 11531: the filename is in $env{'form.'.$formname.'.filename'} and the
11532: contents of the file is located in $env{'form.'.$formname}
1.1056.4.13 raeburn 11533: context - if coursedoc, store the file in the course of the active role
11534: of the current user;
11535: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11536: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11537: subdir - required - subdirectory to put the file in under ../userfiles/
11538: if undefined, it will be placed in "unknown"
11539:
11540: (This routine calls clean_filename() to remove any dangerous
11541: characters from the filename, and then calls finuserfileupload() to
11542: complete the transaction)
11543:
11544: returns either the url of the uploaded file (/uploaded/....) if successful
11545: and /adm/notfound.html if unsuccessful
11546:
11547: =item *
11548:
11549: clean_filename(): routine for cleaing a filename up for storage in
11550: userfile space, argument is:
11551:
11552: filename - proposed filename
11553:
11554: returns: the new clean filename
11555:
11556: =item *
11557:
1.1056.4.13 raeburn 11558: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11559: userspace, probably shouldn't be called directly
11560:
11561: docuname: username or courseid of destination for the file
11562: docudom: domain of user/course of destination for the file
11563: formname: same as for userfileupload()
1.1056.4.13 raeburn 11564: fname: filename (including subdirectories) for the file
11565: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11566: allfiles: reference to hash used to store objects found by parser
11567: codebase: reference to hash used for codebases of java objects found by parser
11568: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11569: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11570: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11571: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11572: context: if 'overwrite', will move the uploaded file from its temporary location to
11573: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1056.4.16 raeburn 11574: mimetype: reference to scalar to accommodate mime type determined
11575: from File::MMagic if $parser = parse.
1.608 albertel 11576:
11577: returns either the url of the uploaded file (/uploaded/....) if successful
1.1056.4.13 raeburn 11578: and /adm/notfound.html if unsuccessful (or an error message if context
11579: was 'overwrite').
11580:
1.608 albertel 11581:
11582: =item *
11583:
11584: renameuserfile(): renames an existing userfile to a new name
11585:
11586: Args:
11587: docuname: username or courseid of destination for the file
11588: docudom: domain of user/course of destination for the file
11589: old: current file name (including any subdirs under userfiles)
11590: new: desired file name (including any subdirs under userfiles)
11591:
11592: =item *
11593:
11594: mkdiruserfile(): creates a directory is a userfiles dir
11595:
11596: Args:
11597: docuname: username or courseid of destination for the file
11598: docudom: domain of user/course of destination for the file
11599: dir: dir to create (including any subdirs under userfiles)
11600:
11601: =item *
11602:
11603: removeuserfile(): removes a file that exists in userfiles
11604:
11605: Args:
11606: docuname: username or courseid of destination for the file
11607: docudom: domain of user/course of destination for the file
11608: fname: filname to delete (including any subdirs under userfiles)
11609:
11610: =item *
11611:
11612: removeuploadedurl(): convience function for removeuserfile()
11613:
11614: Args:
11615: url: a full /uploaded/... url to delete
11616:
1.747 albertel 11617: =item *
11618:
11619: get_portfile_permissions():
11620: Args:
11621: domain: domain of user or course contain the portfolio files
11622: user: name of user or num of course contain the portfolio files
11623: Returns:
11624: hashref of a dump of the proper file_permissions.db
11625:
11626:
11627: =item *
11628:
11629: get_access_controls():
11630:
11631: Args:
11632: current_permissions: the hash ref returned from get_portfile_permissions()
11633: group: (optional) the group you want the files associated with
11634: file: (optional) the file you want access info on
11635:
11636: Returns:
1.749 raeburn 11637: a hash (keys are file names) of hashes containing
11638: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11639: values are XML containing access control settings (see below)
1.747 albertel 11640:
11641: Internal notes:
11642:
1.749 raeburn 11643: access controls are stored in file_permissions.db as key=value pairs.
11644: key -> path to file/file_name\0uniqueID:scope_end_start
11645: where scope -> public,guest,course,group,domains or users.
11646: end -> UNIX time for end of access (0 -> no end date)
11647: start -> UNIX time for start of access
11648:
11649: value -> XML description of access control
11650: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11651: <start></start>
11652: <end></end>
11653:
11654: <password></password> for scope type = guest
11655:
11656: <domain></domain> for scope type = course or group
11657: <number></number>
11658: <roles id="">
11659: <role></role>
11660: <access></access>
11661: <section></section>
11662: <group></group>
11663: </roles>
11664:
11665: <dom></dom> for scope type = domains
11666:
11667: <users> for scope type = users
11668: <user>
11669: <uname></uname>
11670: <udom></udom>
11671: </user>
11672: </users>
11673: </scope>
11674:
11675: Access data is also aggregated for each file in an additional key=value pair:
11676: key -> path to file/file_name\0accesscontrol
11677: value -> reference to hash
11678: hash contains key = value pairs
11679: where key = uniqueID:scope_end_start
11680: value = UNIX time record was last updated
11681:
11682: Used to improve speed of look-ups of access controls for each file.
11683:
11684: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11685:
11686: modify_access_controls():
11687:
11688: Modifies access controls for a portfolio file
11689: Args
11690: 1. file name
11691: 2. reference to hash of required changes,
11692: 3. domain
11693: 4. username
11694: where domain,username are the domain of the portfolio owner
11695: (either a user or a course)
11696:
11697: Returns:
11698: 1. result of additions or updates ('ok' or 'error', with error message).
11699: 2. result of deletions ('ok' or 'error', with error message).
11700: 3. reference to hash of any new or updated access controls.
11701: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11702: key = integer (inbound ID)
11703: value = uniqueID
1.747 albertel 11704:
1.608 albertel 11705: =back
11706:
1.243 albertel 11707: =head2 HTTP Helper Routines
11708:
11709: =over 4
11710:
1.191 harris41 11711: =item *
11712:
11713: escape() : unpack non-word characters into CGI-compatible hex codes
11714:
11715: =item *
11716:
11717: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11718:
1.243 albertel 11719: =back
11720:
11721: =head1 PRIVATE SUBROUTINES
11722:
11723: =head2 Underlying communication routines (Shouldn't call)
11724:
11725: =over 4
11726:
11727: =item *
11728:
11729: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11730:
11731: =item *
11732:
11733: reply() : uses subreply to send a message to remote machine, logs all failures
11734:
11735: =item *
11736:
11737: critical() : passes a critical message to another server; if cannot
11738: get through then place message in connection buffer directory and
11739: returns con_delayed, if incapable of saving message, returns
11740: con_failed
11741:
11742: =item *
11743:
11744: reconlonc() : tries to reconnect lonc client processes.
11745:
11746: =back
11747:
11748: =head2 Resource Access Logging
11749:
11750: =over 4
11751:
11752: =item *
11753:
11754: flushcourselogs() : flush (save) buffer logs and access logs
11755:
11756: =item *
11757:
11758: courselog($what) : save message for course in hash
11759:
11760: =item *
11761:
11762: courseacclog($what) : save message for course using &courselog(). Perform
11763: special processing for specific resource types (problems, exams, quizzes, etc).
11764:
1.191 harris41 11765: =item *
11766:
11767: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11768: as a PerlChildExitHandler
1.243 albertel 11769:
11770: =back
11771:
11772: =head2 Other
11773:
11774: =over 4
11775:
11776: =item *
11777:
11778: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11779:
11780: =back
11781:
11782: =cut
1.877 foxr 11783:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>