Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.4.25
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.4.25! raeburn 4: # $Id: lonnet.pm,v 1.1056.4.24 2011/03/10 23:51:52 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.3 raeburn 834: return; #didn't get a number from the server
1.784 albertel 835: }
836:
837: my $load;
838: if ($loadans =~ /\d/) {
839: if ($userloadans =~ /\d/) {
840: #both are numbers, pick the bigger one
841: $load = ($loadans > $userloadans) ? $loadans
842: : $userloadans;
1.411 albertel 843: } else {
1.784 albertel 844: $load = $loadans;
1.411 albertel 845: }
1.784 albertel 846: } else {
847: $load = $userloadans;
848: }
849:
850: if (($load =~ /\d/) && ($load < $lowest_load)) {
851: $spare_server = $try_server;
852: $lowest_load = $load;
1.370 albertel 853: }
1.784 albertel 854: return ($spare_server,$lowest_load);
1.202 matthew 855: }
1.914 albertel 856:
857: # --------------------------- ask offload servers if user already has a session
858: sub find_existing_session {
859: my ($udom,$uname) = @_;
860: foreach my $try_server (@{ $spareid{'primary'} },
861: @{ $spareid{'default'} }) {
862: return $try_server if (&has_user_session($try_server, $udom, $uname));
863: }
864: return;
865: }
866:
867: # -------------------------------- ask if server already has a session for user
868: sub has_user_session {
869: my ($lonid,$udom,$uname) = @_;
870: my $result = &reply(join(':','userhassession',
871: map {&escape($_)} ($udom,$uname)),$lonid);
872: return 1 if ($result eq 'ok');
873:
874: return 0;
875: }
876:
1.1056.4.3 raeburn 877: # --------- determine least loaded server in a user's domain which allows login
878:
879: sub choose_server {
880: my ($udom) = @_;
881: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
882: my %servers = &get_servers($udom);
883: my $lowest_load = 30000;
884: my ($login_host,$hostname);
885: foreach my $lonhost (keys(%servers)) {
886: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
887: if ($loginvia eq '') {
888: ($login_host, $lowest_load) =
889: &compare_server_load($lonhost, $login_host, $lowest_load);
890: }
891: }
892: if ($login_host ne '') {
893: $hostname = $servers{$login_host};
894: }
895: return ($login_host,$hostname);
896: }
897:
1.202 matthew 898: # --------------------------------------------- Try to change a user's password
899:
900: sub changepass {
1.799 raeburn 901: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 902: $currentpass = &escape($currentpass);
903: $newpass = &escape($newpass);
1.1030 raeburn 904: my $lonhost = $perlvar{'lonHostID'};
905: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 906: $server);
907: if (! $answer) {
908: &logthis("No reply on password change request to $server ".
909: "by $uname in domain $udom.");
910: } elsif ($answer =~ "^ok") {
911: &logthis("$uname in $udom successfully changed their password ".
912: "on $server.");
913: } elsif ($answer =~ "^pwchange_failure") {
914: &logthis("$uname in $udom was unable to change their password ".
915: "on $server. The action was blocked by either lcpasswd ".
916: "or pwchange");
917: } elsif ($answer =~ "^non_authorized") {
918: &logthis("$uname in $udom did not get their password correct when ".
919: "attempting to change it on $server.");
920: } elsif ($answer =~ "^auth_mode_error") {
921: &logthis("$uname in $udom attempted to change their password despite ".
922: "not being locally or internally authenticated on $server.");
923: } elsif ($answer =~ "^unknown_user") {
924: &logthis("$uname in $udom attempted to change their password ".
925: "on $server but were unable to because $server is not ".
926: "their home server.");
927: } elsif ($answer =~ "^refused") {
928: &logthis("$server refused to change $uname in $udom password because ".
929: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 930: } elsif ($answer =~ "invalid_client") {
931: &logthis("$server refused to change $uname in $udom password because ".
932: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 933: }
934: return $answer;
1.1 albertel 935: }
936:
1.169 harris41 937: # ----------------------- Try to determine user's current authentication scheme
938:
939: sub queryauthenticate {
940: my ($uname,$udom)=@_;
1.456 albertel 941: my $uhome=&homeserver($uname,$udom);
942: if (!$uhome) {
943: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
944: return 'no_host';
945: }
946: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
947: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
948: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 949: }
1.456 albertel 950: return $answer;
1.169 harris41 951: }
952:
1.1 albertel 953: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 954:
1.1 albertel 955: sub authenticate {
1.1056.4.3 raeburn 956: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 957: $upass=&escape($upass);
958: $uname= &LONCAPA::clean_username($uname);
1.836 www 959: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 960: my $newhome;
1.836 www 961: if ((!$uhome) || ($uhome eq 'no_host')) {
962: # Maybe the machine was offline and only re-appeared again recently?
963: &reconlonc();
964: # One more
1.952 raeburn 965: $uhome=&homeserver($uname,$udom,1);
966: if (($uhome eq 'no_host') && $checkdefauth) {
967: if (defined(&domain($udom,'primary'))) {
968: $newhome=&domain($udom,'primary');
969: }
970: if ($newhome ne '') {
971: $uhome = $newhome;
972: }
973: }
1.836 www 974: if ((!$uhome) || ($uhome eq 'no_host')) {
975: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 976: return 'no_host';
977: }
1.1 albertel 978: }
1.1056.4.3 raeburn 979: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 980: if ($answer eq 'authorized') {
1.952 raeburn 981: if ($newhome) {
982: &logthis("User $uname at $udom authorized by $uhome, but needs account");
983: return 'no_account_on_host';
984: } else {
985: &logthis("User $uname at $udom authorized by $uhome");
986: return $uhome;
987: }
1.471 albertel 988: }
989: if ($answer eq 'non_authorized') {
990: &logthis("User $uname at $udom rejected by $uhome");
991: return 'no_host';
1.9 www 992: }
1.471 albertel 993: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 994: return 'no_host';
995: }
996:
1.1056.4.3 raeburn 997: sub can_host_session {
998: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
999: my $canhost = 1;
1000: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1001: if (ref($remotesessions) eq 'HASH') {
1002: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1003: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1004: $canhost = 0;
1005: } else {
1006: $canhost = 1;
1007: }
1008: }
1009: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1010: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1011: $canhost = 1;
1012: } else {
1013: $canhost = 0;
1014: }
1015: }
1016: if ($canhost) {
1017: if ($remotesessions->{'version'} ne '') {
1018: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1019: if ($reqmajor ne '' && $reqminor ne '') {
1020: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1021: my $major = $1;
1022: my $minor = $2;
1023: if (($major < $reqmajor ) ||
1024: (($major == $reqmajor) && ($minor < $reqminor))) {
1025: $canhost = 0;
1026: }
1027: } else {
1028: $canhost = 0;
1029: }
1030: }
1031: }
1032: }
1033: }
1034: if ($canhost) {
1035: if (ref($hostedsessions) eq 'HASH') {
1036: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1037: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
1038: $canhost = 0;
1039: } else {
1040: $canhost = 1;
1041: }
1042: }
1043: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1044: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
1045: $canhost = 1;
1046: } else {
1047: $canhost = 0;
1048: }
1049: }
1050: }
1051: }
1052: return $canhost;
1053: }
1054:
1.1056.4.8 raeburn 1055: sub spare_can_host {
1056: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1057: my $canhost=1;
1058: my @intdoms;
1059: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1060: if (ref($internet_names) eq 'ARRAY') {
1061: @intdoms = @{$internet_names};
1062: }
1063: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1064: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1065: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1066: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1067: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1068: $canhost = &can_host_session($udom,$try_server,$remoterev,
1069: $remotesessions,
1070: $defdomdefaults{'hostedsessions'});
1071: }
1072: return $canhost;
1073: }
1074:
1.1 albertel 1075: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1076:
1.599 albertel 1077: my %homecache;
1.1 albertel 1078: sub homeserver {
1.230 stredwic 1079: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1080: my $index="$uname:$udom";
1.426 albertel 1081:
1.599 albertel 1082: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1083:
1084: my %servers = &get_servers($udom,'library');
1085: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1086: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1087: exists($badServerCache{$tryserver}));
1.841 albertel 1088:
1089: my $answer=reply("home:$udom:$uname",$tryserver);
1090: if ($answer eq 'found') {
1091: delete($badServerCache{$tryserver});
1092: return $homecache{$index}=$tryserver;
1093: } elsif ($answer eq 'no_host') {
1094: $badServerCache{$tryserver}=1;
1095: }
1.1 albertel 1096: }
1097: return 'no_host';
1.70 www 1098: }
1099:
1100: # ------------------------------------- Find the usernames behind a list of IDs
1101:
1102: sub idget {
1103: my ($udom,@ids)=@_;
1104: my %returnhash=();
1105:
1.841 albertel 1106: my %servers = &get_servers($udom,'library');
1107: foreach my $tryserver (keys(%servers)) {
1108: my $idlist=join('&',@ids);
1109: $idlist=~tr/A-Z/a-z/;
1110: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1111: my @answer=();
1112: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1113: @answer=split(/\&/,$reply);
1114: } ;
1115: my $i;
1116: for ($i=0;$i<=$#ids;$i++) {
1117: if ($answer[$i]) {
1118: $returnhash{$ids[$i]}=$answer[$i];
1119: }
1120: }
1121: }
1.70 www 1122: return %returnhash;
1123: }
1124:
1125: # ------------------------------------- Find the IDs behind a list of usernames
1126:
1127: sub idrget {
1128: my ($udom,@unames)=@_;
1129: my %returnhash=();
1.800 albertel 1130: foreach my $uname (@unames) {
1131: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1132: }
1.70 www 1133: return %returnhash;
1134: }
1135:
1136: # ------------------------------- Store away a list of names and associated IDs
1137:
1138: sub idput {
1139: my ($udom,%ids)=@_;
1140: my %servers=();
1.800 albertel 1141: foreach my $uname (keys(%ids)) {
1142: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1143: my $uhom=&homeserver($uname,$udom);
1.70 www 1144: if ($uhom ne 'no_host') {
1.800 albertel 1145: my $id=&escape($ids{$uname});
1.70 www 1146: $id=~tr/A-Z/a-z/;
1.800 albertel 1147: my $esc_unam=&escape($uname);
1.70 www 1148: if ($servers{$uhom}) {
1.800 albertel 1149: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1150: } else {
1.800 albertel 1151: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1152: }
1153: }
1.191 harris41 1154: }
1.800 albertel 1155: foreach my $server (keys(%servers)) {
1156: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1157: }
1.344 www 1158: }
1159:
1.1023 raeburn 1160: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1161: sub dump_dom {
1.1023 raeburn 1162: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1163: if (!$udom) {
1164: $udom=$env{'user.domain'};
1165: }
1166: my %returnhash;
1.1023 raeburn 1167: if ($udom) {
1168: my $uname = &get_domainconfiguser($udom);
1169: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1170: }
1171: return %returnhash;
1172: }
1173:
1.1023 raeburn 1174: # ------------------------------------------ get items from domain db files
1.806 raeburn 1175:
1176: sub get_dom {
1.860 raeburn 1177: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1178: my $items='';
1179: foreach my $item (@$storearr) {
1180: $items.=&escape($item).'&';
1181: }
1182: $items=~s/\&$//;
1.860 raeburn 1183: if (!$udom) {
1184: $udom=$env{'user.domain'};
1185: if (defined(&domain($udom,'primary'))) {
1186: $uhome=&domain($udom,'primary');
1187: } else {
1.874 albertel 1188: undef($uhome);
1.860 raeburn 1189: }
1190: } else {
1191: if (!$uhome) {
1192: if (defined(&domain($udom,'primary'))) {
1193: $uhome=&domain($udom,'primary');
1194: }
1195: }
1196: }
1197: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1198: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1199: my %returnhash;
1.875 albertel 1200: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1201: return %returnhash;
1202: }
1.806 raeburn 1203: my @pairs=split(/\&/,$rep);
1204: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1205: return @pairs;
1206: }
1207: my $i=0;
1208: foreach my $item (@$storearr) {
1209: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1210: $i++;
1211: }
1212: return %returnhash;
1213: } else {
1.880 banghart 1214: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1215: }
1216: }
1217:
1218: # -------------------------------------------- put items in domain db files
1219:
1220: sub put_dom {
1.860 raeburn 1221: my ($namespace,$storehash,$udom,$uhome)=@_;
1222: if (!$udom) {
1223: $udom=$env{'user.domain'};
1224: if (defined(&domain($udom,'primary'))) {
1225: $uhome=&domain($udom,'primary');
1226: } else {
1.874 albertel 1227: undef($uhome);
1.860 raeburn 1228: }
1229: } else {
1230: if (!$uhome) {
1231: if (defined(&domain($udom,'primary'))) {
1232: $uhome=&domain($udom,'primary');
1233: }
1234: }
1235: }
1236: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1237: my $items='';
1238: foreach my $item (keys(%$storehash)) {
1239: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1240: }
1241: $items=~s/\&$//;
1242: return &reply("putdom:$udom:$namespace:$items",$uhome);
1243: } else {
1.860 raeburn 1244: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1245: }
1246: }
1247:
1.1023 raeburn 1248: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1249: sub newput_dom {
1.1023 raeburn 1250: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1251: my $result;
1252: if (!$udom) {
1253: $udom=$env{'user.domain'};
1254: }
1.1023 raeburn 1255: if ($udom) {
1256: my $uname = &get_domainconfiguser($udom);
1257: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1258: }
1259: return $result;
1260: }
1261:
1.1023 raeburn 1262: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1263: sub del_dom {
1.1023 raeburn 1264: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1265: if (ref($storearr) eq 'ARRAY') {
1266: if (!$udom) {
1267: $udom=$env{'user.domain'};
1268: }
1.1023 raeburn 1269: if ($udom) {
1270: my $uname = &get_domainconfiguser($udom);
1271: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1272: }
1273: }
1274: }
1275:
1.1023 raeburn 1276: # ----------------------------------construct domainconfig user for a domain
1277: sub get_domainconfiguser {
1278: my ($udom) = @_;
1279: return $udom.'-domainconfig';
1280: }
1281:
1.837 raeburn 1282: sub retrieve_inst_usertypes {
1283: my ($udom) = @_;
1284: my (%returnhash,@order);
1.989 raeburn 1285: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1286: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1287: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1288: %returnhash = %{$domdefs{'inststatustypes'}};
1289: @order = @{$domdefs{'inststatusorder'}};
1290: } else {
1291: if (defined(&domain($udom,'primary'))) {
1292: my $uhome=&domain($udom,'primary');
1293: my $rep=&reply("inst_usertypes:$udom",$uhome);
1294: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1295: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1296: return (\%returnhash,\@order);
1297: }
1298: my ($hashitems,$orderitems) = split(/:/,$rep);
1299: my @pairs=split(/\&/,$hashitems);
1300: foreach my $item (@pairs) {
1301: my ($key,$value)=split(/=/,$item,2);
1302: $key = &unescape($key);
1303: next if ($key =~ /^error: 2 /);
1304: $returnhash{$key}=&thaw_unescape($value);
1305: }
1306: my @esc_order = split(/\&/,$orderitems);
1307: foreach my $item (@esc_order) {
1308: push(@order,&unescape($item));
1309: }
1310: } else {
1311: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1312: }
1313: }
1314: return (\%returnhash,\@order);
1315: }
1316:
1.868 raeburn 1317: sub is_domainimage {
1318: my ($url) = @_;
1319: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1320: if (&domain($1) ne '') {
1321: return '1';
1322: }
1323: }
1324: return;
1325: }
1326:
1.899 raeburn 1327: sub inst_directory_query {
1328: my ($srch) = @_;
1329: my $udom = $srch->{'srchdomain'};
1330: my %results;
1331: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1332: my $outcome;
1.899 raeburn 1333: if ($homeserver ne '') {
1.904 albertel 1334: my $queryid=&reply("querysend:instdirsearch:".
1335: &escape($srch->{'srchby'}).':'.
1336: &escape($srch->{'srchterm'}).':'.
1337: &escape($srch->{'srchtype'}),$homeserver);
1338: my $host=&hostname($homeserver);
1339: if ($queryid !~/^\Q$host\E\_/) {
1340: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1341: return;
1342: }
1343: my $response = &get_query_reply($queryid);
1344: my $maxtries = 5;
1345: my $tries = 1;
1346: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1347: $response = &get_query_reply($queryid);
1348: $tries ++;
1349: }
1350:
1351: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1352: if ($response eq 'unavailable') {
1353: $outcome = $response;
1354: } else {
1355: $outcome = 'ok';
1356: my @matches = split(/\n/,$response);
1357: foreach my $match (@matches) {
1358: my ($key,$value) = split(/=/,$match);
1359: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1360: }
1.899 raeburn 1361: }
1362: }
1363: }
1.909 raeburn 1364: return ($outcome,%results);
1.899 raeburn 1365: }
1366:
1367: sub usersearch {
1368: my ($srch) = @_;
1369: my $dom = $srch->{'srchdomain'};
1370: my %results;
1371: my %libserv = &all_library();
1372: my $query = 'usersearch';
1373: foreach my $tryserver (keys(%libserv)) {
1374: if (&host_domain($tryserver) eq $dom) {
1375: my $host=&hostname($tryserver);
1376: my $queryid=
1.911 raeburn 1377: &reply("querysend:".&escape($query).':'.
1378: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1379: &escape($srch->{'srchtype'}).':'.
1380: &escape($srch->{'srchterm'}),$tryserver);
1381: if ($queryid !~/^\Q$host\E\_/) {
1382: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1383: next;
1.899 raeburn 1384: }
1385: my $reply = &get_query_reply($queryid);
1386: my $maxtries = 1;
1387: my $tries = 1;
1388: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1389: $reply = &get_query_reply($queryid);
1390: $tries ++;
1391: }
1392: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1393: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1394: } else {
1.911 raeburn 1395: my @matches;
1396: if ($reply =~ /\n/) {
1397: @matches = split(/\n/,$reply);
1398: } else {
1399: @matches = split(/\&/,$reply);
1400: }
1.899 raeburn 1401: foreach my $match (@matches) {
1402: my ($uname,$udom,%userhash);
1.911 raeburn 1403: foreach my $entry (split(/:/,$match)) {
1404: my ($key,$value) =
1405: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1406: $userhash{$key} = $value;
1407: if ($key eq 'username') {
1408: $uname = $value;
1409: } elsif ($key eq 'domain') {
1410: $udom = $value;
1.911 raeburn 1411: }
1.899 raeburn 1412: }
1413: $results{$uname.':'.$udom} = \%userhash;
1414: }
1415: }
1416: }
1417: }
1418: return %results;
1419: }
1420:
1.912 raeburn 1421: sub get_instuser {
1422: my ($udom,$uname,$id) = @_;
1423: my $homeserver = &domain($udom,'primary');
1424: my ($outcome,%results);
1425: if ($homeserver ne '') {
1426: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1427: &escape($id).':'.&escape($udom),$homeserver);
1428: my $host=&hostname($homeserver);
1429: if ($queryid !~/^\Q$host\E\_/) {
1430: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1431: return;
1432: }
1433: my $response = &get_query_reply($queryid);
1434: my $maxtries = 5;
1435: my $tries = 1;
1436: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1437: $response = &get_query_reply($queryid);
1438: $tries ++;
1439: }
1440: if (!&error($response) && $response ne 'refused') {
1441: if ($response eq 'unavailable') {
1442: $outcome = $response;
1443: } else {
1444: $outcome = 'ok';
1445: my @matches = split(/\n/,$response);
1446: foreach my $match (@matches) {
1447: my ($key,$value) = split(/=/,$match);
1448: $results{&unescape($key)} = &thaw_unescape($value);
1449: }
1450: }
1451: }
1452: }
1453: my %userinfo;
1454: if (ref($results{$uname}) eq 'HASH') {
1455: %userinfo = %{$results{$uname}};
1456: }
1457: return ($outcome,%userinfo);
1458: }
1459:
1460: sub inst_rulecheck {
1.923 raeburn 1461: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1462: my %returnhash;
1463: if ($udom ne '') {
1464: if (ref($rules) eq 'ARRAY') {
1465: @{$rules} = map {&escape($_);} (@{$rules});
1466: my $rulestr = join(':',@{$rules});
1467: my $homeserver=&domain($udom,'primary');
1468: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1469: my $response;
1470: if ($item eq 'username') {
1471: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1472: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1473: $homeserver));
1.923 raeburn 1474: } elsif ($item eq 'id') {
1475: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1476: ':'.&escape($id).':'.$rulestr,
1477: $homeserver));
1.945 raeburn 1478: } elsif ($item eq 'selfcreate') {
1479: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1480: &escape($udom).':'.&escape($uname).
1481: ':'.$rulestr,$homeserver));
1.923 raeburn 1482: }
1.912 raeburn 1483: if ($response ne 'refused') {
1484: my @pairs=split(/\&/,$response);
1485: foreach my $item (@pairs) {
1486: my ($key,$value)=split(/=/,$item,2);
1487: $key = &unescape($key);
1488: next if ($key =~ /^error: 2 /);
1489: $returnhash{$key}=&thaw_unescape($value);
1490: }
1491: }
1492: }
1493: }
1494: }
1495: return %returnhash;
1496: }
1497:
1498: sub inst_userrules {
1.923 raeburn 1499: my ($udom,$check) = @_;
1.912 raeburn 1500: my (%ruleshash,@ruleorder);
1501: if ($udom ne '') {
1502: my $homeserver=&domain($udom,'primary');
1503: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1504: my $response;
1505: if ($check eq 'id') {
1506: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1507: $homeserver);
1.943 raeburn 1508: } elsif ($check eq 'email') {
1509: $response=&reply('instemailrules:'.&escape($udom),
1510: $homeserver);
1.923 raeburn 1511: } else {
1512: $response=&reply('instuserrules:'.&escape($udom),
1513: $homeserver);
1514: }
1.912 raeburn 1515: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1516: ($response ne 'unknown_cmd') &&
1.912 raeburn 1517: ($response ne 'no_such_host')) {
1518: my ($hashitems,$orderitems) = split(/:/,$response);
1519: my @pairs=split(/\&/,$hashitems);
1520: foreach my $item (@pairs) {
1521: my ($key,$value)=split(/=/,$item,2);
1522: $key = &unescape($key);
1523: next if ($key =~ /^error: 2 /);
1524: $ruleshash{$key}=&thaw_unescape($value);
1525: }
1526: my @esc_order = split(/\&/,$orderitems);
1527: foreach my $item (@esc_order) {
1528: push(@ruleorder,&unescape($item));
1529: }
1530: }
1531: }
1532: }
1533: return (\%ruleshash,\@ruleorder);
1534: }
1535:
1.976 raeburn 1536: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1537:
1538: sub get_domain_defaults {
1539: my ($domain) = @_;
1540: my $cachetime = 60*60*24;
1541: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1542: if (defined($cached)) {
1543: if (ref($result) eq 'HASH') {
1544: return %{$result};
1545: }
1546: }
1547: my %domdefaults;
1548: my %domconfig =
1.989 raeburn 1549: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1550: 'requestcourses','inststatus',
1.1056.4.3 raeburn 1551: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1552: if (ref($domconfig{'defaults'}) eq 'HASH') {
1553: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1554: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1555: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1556: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1557: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1558: } else {
1559: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1560: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1561: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1562: }
1.976 raeburn 1563: if (ref($domconfig{'quotas'}) eq 'HASH') {
1564: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1565: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1566: } else {
1567: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1568: }
1569: my @usertools = ('aboutme','blog','portfolio');
1570: foreach my $item (@usertools) {
1571: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1572: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1573: }
1574: }
1575: }
1.985 raeburn 1576: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1577: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1578: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1579: }
1580: }
1.989 raeburn 1581: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1582: foreach my $item ('inststatustypes','inststatusorder') {
1583: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1584: }
1585: }
1.1047 raeburn 1586: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1587: foreach my $item ('canuse_pdfforms') {
1588: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1589: }
1590: }
1.1056.4.3 raeburn 1591: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1592: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1593: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1594: }
1595: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1596: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1597: }
1598: }
1.943 raeburn 1599: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1600: $cachetime);
1601: return %domdefaults;
1602: }
1603:
1.344 www 1604: # --------------------------------------------------- Assign a key to a student
1605:
1606: sub assign_access_key {
1.364 www 1607: #
1608: # a valid key looks like uname:udom#comments
1609: # comments are being appended
1610: #
1.498 www 1611: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1612: $kdom=
1.620 albertel 1613: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1614: $knum=
1.620 albertel 1615: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1616: $cdom=
1.620 albertel 1617: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1618: $cnum=
1.620 albertel 1619: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1620: $udom=$env{'user.name'} unless (defined($udom));
1621: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1622: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1623: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1624: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1625: # assigned to this person
1626: # - this should not happen,
1.345 www 1627: # unless something went wrong
1628: # the first time around
1629: # ready to assign
1.364 www 1630: $logentry=$1.'; '.$logentry;
1.496 www 1631: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1632: $kdom,$knum) eq 'ok') {
1.345 www 1633: # key now belongs to user
1.346 www 1634: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1635: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1636: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1637: return 'ok';
1638: } else {
1639: return
1640: 'error: Count not permanently assign key, will need to be re-entered later.';
1641: }
1642: } else {
1643: return 'error: Could not assign key, try again later.';
1644: }
1.364 www 1645: } elsif (!$existing{$ckey}) {
1.345 www 1646: # the key does not exist
1647: return 'error: The key does not exist';
1648: } else {
1649: # the key is somebody else's
1650: return 'error: The key is already in use';
1651: }
1.344 www 1652: }
1653:
1.364 www 1654: # ------------------------------------------ put an additional comment on a key
1655:
1656: sub comment_access_key {
1657: #
1658: # a valid key looks like uname:udom#comments
1659: # comments are being appended
1660: #
1661: my ($ckey,$cdom,$cnum,$logentry)=@_;
1662: $cdom=
1.620 albertel 1663: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1664: $cnum=
1.620 albertel 1665: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1666: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1667: if ($existing{$ckey}) {
1668: $existing{$ckey}.='; '.$logentry;
1669: # ready to assign
1.367 www 1670: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1671: $cdom,$cnum) eq 'ok') {
1672: return 'ok';
1673: } else {
1674: return 'error: Count not store comment.';
1675: }
1676: } else {
1677: # the key does not exist
1678: return 'error: The key does not exist';
1679: }
1680: }
1681:
1.344 www 1682: # ------------------------------------------------------ Generate a set of keys
1683:
1684: sub generate_access_keys {
1.364 www 1685: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1686: $cdom=
1.620 albertel 1687: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1688: $cnum=
1.620 albertel 1689: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1690: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1691: unless (($cdom) && ($cnum)) { return 0; }
1692: if ($number>10000) { return 0; }
1693: sleep(2); # make sure don't get same seed twice
1694: srand(time()^($$+($$<<15))); # from "Programming Perl"
1695: my $total=0;
1696: for (my $i=1;$i<=$number;$i++) {
1697: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1698: sprintf("%lx",int(100000*rand)).'-'.
1699: sprintf("%lx",int(100000*rand));
1700: $newkey=~s/1/g/g; # folks mix up 1 and l
1701: $newkey=~s/0/h/g; # and also 0 and O
1702: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1703: if ($existing{$newkey}) {
1704: $i--;
1705: } else {
1.364 www 1706: if (&put('accesskeys',
1707: { $newkey => '# generated '.localtime().
1.620 albertel 1708: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1709: '; '.$logentry },
1710: $cdom,$cnum) eq 'ok') {
1.344 www 1711: $total++;
1712: }
1713: }
1714: }
1.620 albertel 1715: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1716: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1717: return $total;
1718: }
1719:
1720: # ------------------------------------------------------- Validate an accesskey
1721:
1722: sub validate_access_key {
1723: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1724: $cdom=
1.620 albertel 1725: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1726: $cnum=
1.620 albertel 1727: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1728: $udom=$env{'user.domain'} unless (defined($udom));
1729: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1730: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1731: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1732: }
1733:
1734: # ------------------------------------- Find the section of student in a course
1.652 albertel 1735: sub devalidate_getsection_cache {
1736: my ($udom,$unam,$courseid)=@_;
1737: my $hashid="$udom:$unam:$courseid";
1738: &devalidate_cache_new('getsection',$hashid);
1739: }
1.298 matthew 1740:
1.815 albertel 1741: sub courseid_to_courseurl {
1742: my ($courseid) = @_;
1743: #already url style courseid
1744: return $courseid if ($courseid =~ m{^/});
1745:
1746: if (exists($env{'course.'.$courseid.'.num'})) {
1747: my $cnum = $env{'course.'.$courseid.'.num'};
1748: my $cdom = $env{'course.'.$courseid.'.domain'};
1749: return "/$cdom/$cnum";
1750: }
1751:
1752: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1753: if (exists($courseinfo{'num'})) {
1754: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1755: }
1756:
1757: return undef;
1758: }
1759:
1.298 matthew 1760: sub getsection {
1761: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1762: my $cachetime=1800;
1.551 albertel 1763:
1764: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1765: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1766: if (defined($cached)) { return $result; }
1767:
1.298 matthew 1768: my %Pending;
1769: my %Expired;
1770: #
1771: # Each role can either have not started yet (pending), be active,
1772: # or have expired.
1773: #
1774: # If there is an active role, we are done.
1775: #
1776: # If there is more than one role which has not started yet,
1777: # choose the one which will start sooner
1778: # If there is one role which has not started yet, return it.
1779: #
1780: # If there is more than one expired role, choose the one which ended last.
1781: # If there is a role which has expired, return it.
1782: #
1.815 albertel 1783: $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 1784: my $extra = &freeze_escape({'skipcheck' => 1});
1785: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1786: foreach my $key (keys(%roleshash)) {
1.479 albertel 1787: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1788: my $section=$1;
1789: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1790: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1791: my $now=time;
1.548 albertel 1792: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1793: $Expired{$end}=$section;
1794: next;
1795: }
1.548 albertel 1796: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1797: $Pending{$start}=$section;
1798: next;
1799: }
1.599 albertel 1800: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1801: }
1802: #
1803: # Presumedly there will be few matching roles from the above
1804: # loop and the sorting time will be negligible.
1805: if (scalar(keys(%Pending))) {
1806: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1807: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1808: }
1809: if (scalar(keys(%Expired))) {
1810: my @sorted = sort {$a <=> $b} keys(%Expired);
1811: my $time = pop(@sorted);
1.599 albertel 1812: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1813: }
1.599 albertel 1814: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1815: }
1.70 www 1816:
1.599 albertel 1817: sub save_cache {
1818: &purge_remembered();
1.722 albertel 1819: #&Apache::loncommon::validate_page();
1.620 albertel 1820: undef(%env);
1.780 albertel 1821: undef($env_loaded);
1.599 albertel 1822: }
1.452 albertel 1823:
1.599 albertel 1824: my $to_remember=-1;
1825: my %remembered;
1826: my %accessed;
1827: my $kicks=0;
1828: my $hits=0;
1.849 albertel 1829: sub make_key {
1830: my ($name,$id) = @_;
1.872 albertel 1831: if (length($id) > 65
1832: && length(&escape($id)) > 200) {
1833: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1834: }
1.849 albertel 1835: return &escape($name.':'.$id);
1836: }
1837:
1.599 albertel 1838: sub devalidate_cache_new {
1839: my ($name,$id,$debug) = @_;
1840: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1841: $id=&make_key($name,$id);
1.599 albertel 1842: $memcache->delete($id);
1843: delete($remembered{$id});
1844: delete($accessed{$id});
1845: }
1846:
1847: sub is_cached_new {
1848: my ($name,$id,$debug) = @_;
1.849 albertel 1849: $id=&make_key($name,$id);
1.599 albertel 1850: if (exists($remembered{$id})) {
1851: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1852: $accessed{$id}=[&gettimeofday()];
1853: $hits++;
1854: return ($remembered{$id},1);
1855: }
1856: my $value = $memcache->get($id);
1857: if (!(defined($value))) {
1858: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1859: return (undef,undef);
1.416 albertel 1860: }
1.599 albertel 1861: if ($value eq '__undef__') {
1862: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1863: $value=undef;
1864: }
1865: &make_room($id,$value,$debug);
1866: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1867: return ($value,1);
1868: }
1869:
1870: sub do_cache_new {
1871: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1872: $id=&make_key($name,$id);
1.599 albertel 1873: my $setvalue=$value;
1874: if (!defined($setvalue)) {
1875: $setvalue='__undef__';
1876: }
1.623 albertel 1877: if (!defined($time) ) {
1878: $time=600;
1879: }
1.599 albertel 1880: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1881: my $result = $memcache->set($id,$setvalue,$time);
1882: if (! $result) {
1.872 albertel 1883: &logthis("caching of id -> $id failed");
1.910 albertel 1884: $memcache->disconnect_all();
1.872 albertel 1885: }
1.600 albertel 1886: # need to make a copy of $value
1.919 albertel 1887: &make_room($id,$value,$debug);
1.599 albertel 1888: return $value;
1889: }
1890:
1891: sub make_room {
1892: my ($id,$value,$debug)=@_;
1.919 albertel 1893:
1894: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1895: : $value;
1.599 albertel 1896: if ($to_remember<0) { return; }
1897: $accessed{$id}=[&gettimeofday()];
1898: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1899: my $to_kick;
1900: my $max_time=0;
1901: foreach my $other (keys(%accessed)) {
1902: if (&tv_interval($accessed{$other}) > $max_time) {
1903: $to_kick=$other;
1904: $max_time=&tv_interval($accessed{$other});
1905: }
1906: }
1907: delete($remembered{$to_kick});
1908: delete($accessed{$to_kick});
1909: $kicks++;
1910: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1911: return;
1912: }
1913:
1.599 albertel 1914: sub purge_remembered {
1.604 albertel 1915: #&logthis("Tossing ".scalar(keys(%remembered)));
1916: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1917: undef(%remembered);
1918: undef(%accessed);
1.428 albertel 1919: }
1.70 www 1920: # ------------------------------------- Read an entry from a user's environment
1921:
1922: sub userenvironment {
1923: my ($udom,$unam,@what)=@_;
1.976 raeburn 1924: my $items;
1925: foreach my $item (@what) {
1926: $items.=&escape($item).'&';
1927: }
1928: $items=~s/\&$//;
1.70 www 1929: my %returnhash=();
1.1009 raeburn 1930: my $uhome = &homeserver($unam,$udom);
1931: unless ($uhome eq 'no_host') {
1932: my @answer=split(/\&/,
1933: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1934: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1935: return %returnhash;
1936: }
1.1009 raeburn 1937: my $i;
1938: for ($i=0;$i<=$#what;$i++) {
1939: $returnhash{$what[$i]}=&unescape($answer[$i]);
1940: }
1.70 www 1941: }
1942: return %returnhash;
1.1 albertel 1943: }
1944:
1.617 albertel 1945: # ---------------------------------------------------------- Get a studentphoto
1946: sub studentphoto {
1947: my ($udom,$unam,$ext) = @_;
1948: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1949: if (defined($env{'request.course.id'})) {
1.708 raeburn 1950: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1951: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1952: return(&retrievestudentphoto($udom,$unam,$ext));
1953: } else {
1954: my ($result,$perm_reqd)=
1.707 albertel 1955: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1956: if ($result eq 'ok') {
1957: if (!($perm_reqd eq 'yes')) {
1958: return(&retrievestudentphoto($udom,$unam,$ext));
1959: }
1960: }
1961: }
1962: }
1963: } else {
1964: my ($result,$perm_reqd) =
1.707 albertel 1965: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1966: if ($result eq 'ok') {
1967: if (!($perm_reqd eq 'yes')) {
1968: return(&retrievestudentphoto($udom,$unam,$ext));
1969: }
1970: }
1971: }
1972: return '/adm/lonKaputt/lonlogo_broken.gif';
1973: }
1974:
1975: sub retrievestudentphoto {
1976: my ($udom,$unam,$ext,$type) = @_;
1977: my $home=&Apache::lonnet::homeserver($unam,$udom);
1978: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1979: if ($ret eq 'ok') {
1980: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1981: if ($type eq 'thumbnail') {
1982: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1983: }
1984: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1985: return $tokenurl;
1986: } else {
1987: if ($type eq 'thumbnail') {
1988: return '/adm/lonKaputt/genericstudent_tn.gif';
1989: } else {
1990: return '/adm/lonKaputt/lonlogo_broken.gif';
1991: }
1.617 albertel 1992: }
1993: }
1994:
1.263 www 1995: # -------------------------------------------------------------------- New chat
1996:
1997: sub chatsend {
1.724 raeburn 1998: my ($newentry,$anon,$group)=@_;
1.620 albertel 1999: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2000: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2001: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2002: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2003: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2004: &escape($newentry)).':'.$group,$chome);
1.292 www 2005: }
2006:
2007: # ------------------------------------------ Find current version of a resource
2008:
2009: sub getversion {
2010: my $fname=&clutter(shift);
2011: unless ($fname=~/^\/res\//) { return -1; }
2012: return ¤tversion(&filelocation('',$fname));
2013: }
2014:
2015: sub currentversion {
2016: my $fname=shift;
1.599 albertel 2017: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 2018: if (defined($cached)) { return $result; }
1.292 www 2019: my $author=$fname;
2020: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2021: my ($udom,$uname)=split(/\//,$author);
2022: my $home=homeserver($uname,$udom);
2023: if ($home eq 'no_host') {
2024: return -1;
2025: }
2026: my $answer=reply("currentversion:$fname",$home);
2027: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2028: return -1;
2029: }
1.599 albertel 2030: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 2031: }
2032:
1.1 albertel 2033: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2034:
1.1 albertel 2035: sub subscribe {
2036: my $fname=shift;
1.761 raeburn 2037: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2038: $fname=~s/[\n\r]//g;
1.1 albertel 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);
1.335 albertel 2043: if ($home eq 'no_host') {
2044: return 'not_found';
1.1 albertel 2045: }
2046: my $answer=reply("sub:$fname",$home);
1.64 www 2047: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2048: $answer.=' by '.$home;
2049: }
1.1 albertel 2050: return $answer;
2051: }
2052:
1.8 www 2053: # -------------------------------------------------------------- Replicate file
2054:
2055: sub repcopy {
2056: my $filename=shift;
1.23 www 2057: $filename=~s/\/+/\//g;
1.607 raeburn 2058: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2059: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2060: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2061: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2062: return &repcopy_userfile($filename);
2063: }
1.532 albertel 2064: $filename=~s/[\n\r]//g;
1.8 www 2065: my $transname="$filename.in.transfer";
1.828 www 2066: # FIXME: this should flock
1.607 raeburn 2067: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2068: my $remoteurl=subscribe($filename);
1.64 www 2069: if ($remoteurl =~ /^con_lost by/) {
2070: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2071: return 'unavailable';
1.8 www 2072: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2073: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2074: return 'not_found';
1.64 www 2075: } elsif ($remoteurl =~ /^rejected by/) {
2076: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2077: return 'forbidden';
1.20 www 2078: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2079: return 'ok';
1.8 www 2080: } else {
1.290 www 2081: my $author=$filename;
2082: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2083: my ($udom,$uname)=split(/\//,$author);
2084: my $home=homeserver($uname,$udom);
2085: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2086: my @parts=split(/\//,$filename);
2087: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2088: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2089: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2090: return 'bad_request';
1.8 www 2091: }
2092: my $count;
2093: for ($count=5;$count<$#parts;$count++) {
2094: $path.="/$parts[$count]";
2095: if ((-e $path)!=1) {
2096: mkdir($path,0777);
2097: }
2098: }
2099: my $ua=new LWP::UserAgent;
2100: my $request=new HTTP::Request('GET',"$remoteurl");
2101: my $response=$ua->request($request,$transname);
2102: if ($response->is_error()) {
2103: unlink($transname);
2104: my $message=$response->status_line;
1.672 albertel 2105: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2106: ." LWP get: $message: $filename</font>");
1.607 raeburn 2107: return 'unavailable';
1.8 www 2108: } else {
1.16 www 2109: if ($remoteurl!~/\.meta$/) {
2110: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2111: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2112: if ($mresponse->is_error()) {
2113: unlink($filename.'.meta');
2114: &logthis(
1.672 albertel 2115: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2116: }
2117: }
1.8 www 2118: rename($transname,$filename);
1.607 raeburn 2119: return 'ok';
1.8 www 2120: }
1.290 www 2121: }
1.8 www 2122: }
1.330 www 2123: }
2124:
2125: # ------------------------------------------------ Get server side include body
2126: sub ssi_body {
1.381 albertel 2127: my ($filelink,%form)=@_;
1.606 matthew 2128: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2129: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2130: }
1.953 www 2131: my $output='';
2132: my $response;
1.980 raeburn 2133: if ($filelink=~/^https?\:/) {
1.954 raeburn 2134: ($output,$response)=&externalssi($filelink);
1.953 www 2135: } else {
1.1004 droeschl 2136: $filelink .= $filelink=~/\?/ ? '&' : '?';
2137: $filelink .= 'inhibitmenu=yes';
1.953 www 2138: ($output,$response)=&ssi($filelink,%form);
2139: }
1.778 albertel 2140: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2141: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2142: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2143: if (wantarray) {
2144: return ($output, $response);
2145: } else {
2146: return $output;
2147: }
1.8 www 2148: }
2149:
1.15 www 2150: # --------------------------------------------------------- Server Side Include
2151:
1.782 albertel 2152: sub absolute_url {
2153: my ($host_name) = @_;
2154: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2155: if ($host_name eq '') {
2156: $host_name = $ENV{'SERVER_NAME'};
2157: }
2158: return $protocol.$host_name;
2159: }
2160:
1.942 foxr 2161: #
2162: # Server side include.
2163: # Parameters:
2164: # fn Possibly encrypted resource name/id.
2165: # form Hash that describes how the rendering should be done
2166: # and other things.
1.944 foxr 2167: # Returns:
1.950 raeburn 2168: # Scalar context: The content of the response.
2169: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2170: #
1.15 www 2171: sub ssi {
2172:
1.944 foxr 2173: my ($fn,%form)=@_;
1.15 www 2174: my $ua=new LWP::UserAgent;
1.23 www 2175: my $request;
1.711 albertel 2176:
2177: $form{'no_update_last_known'}=1;
1.895 albertel 2178: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2179: if (%form) {
1.782 albertel 2180: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2181: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2182: } else {
1.782 albertel 2183: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2184: }
2185:
1.15 www 2186: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2187: my $response=$ua->request($request);
2188:
1.944 foxr 2189: if (wantarray) {
2190: return ($response->content, $response);
2191: } else {
2192: return $response->content;
1.942 foxr 2193: }
1.324 www 2194: }
2195:
2196: sub externalssi {
2197: my ($url)=@_;
2198: my $ua=new LWP::UserAgent;
2199: my $request=new HTTP::Request('GET',$url);
2200: my $response=$ua->request($request);
1.954 raeburn 2201: if (wantarray) {
2202: return ($response->content, $response);
2203: } else {
2204: return $response->content;
2205: }
1.15 www 2206: }
1.254 www 2207:
1.492 albertel 2208: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2209:
2210: sub allowuploaded {
2211: my ($srcurl,$url)=@_;
2212: $url=&clutter(&declutter($url));
2213: my $dir=$url;
2214: $dir=~s/\/[^\/]+$//;
2215: my %httpref=();
2216: my $httpurl=&hreflocation('',$url);
2217: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2218: &Apache::lonnet::appenv(\%httpref);
1.254 www 2219: }
1.477 raeburn 2220:
1.478 albertel 2221: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2222: # input: action, courseID, current domain, intended
1.637 raeburn 2223: # path to file, source of file, instruction to parse file for objects,
2224: # ref to hash for embedded objects,
2225: # ref to hash for codebase of java objects.
1.1056.4.16 raeburn 2226: # reference to scalar to accommodate mime type determined
2227: # from File::MMagic if $parser = parse.
1.637 raeburn 2228: #
1.485 raeburn 2229: # output: url to file (if action was uploaddoc),
2230: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2231: #
1.478 albertel 2232: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2233: # course.
1.477 raeburn 2234: #
1.478 albertel 2235: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2236: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2237: # course's home server.
1.477 raeburn 2238: #
1.478 albertel 2239: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2240: # be copied from $source (current location) to
2241: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2242: # and will then be copied to
2243: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2244: # course's home server.
1.485 raeburn 2245: #
1.481 raeburn 2246: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2247: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2248: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2249: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2250: # in course's home server.
1.637 raeburn 2251: #
1.477 raeburn 2252:
2253: sub process_coursefile {
1.1056.4.16 raeburn 2254: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2255: $mimetype)=@_;
1.477 raeburn 2256: my $fetchresult;
1.638 albertel 2257: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2258: if ($action eq 'propagate') {
1.638 albertel 2259: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2260: $home);
1.481 raeburn 2261: } else {
1.477 raeburn 2262: my $fpath = '';
2263: my $fname = $file;
1.478 albertel 2264: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2265: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2266: my $filepath = &build_filepath($fpath);
1.481 raeburn 2267: if ($action eq 'copy') {
2268: if ($source eq '') {
2269: $fetchresult = 'no source file';
2270: return $fetchresult;
2271: } else {
2272: my $destination = $filepath.'/'.$fname;
2273: rename($source,$destination);
2274: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2275: $home);
1.481 raeburn 2276: }
2277: } elsif ($action eq 'uploaddoc') {
2278: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2279: print $fh $env{'form.'.$source};
1.481 raeburn 2280: close($fh);
1.637 raeburn 2281: if ($parser eq 'parse') {
1.1024 raeburn 2282: my $mm = new File::MMagic;
1.1056.4.16 raeburn 2283: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2284: if ($type eq 'text/html') {
1.1024 raeburn 2285: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2286: unless ($parse_result eq 'ok') {
2287: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2288: }
1.637 raeburn 2289: }
1.1056.4.16 raeburn 2290: if (ref($mimetype)) {
2291: $$mimetype = $type;
2292: }
1.637 raeburn 2293: }
1.477 raeburn 2294: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2295: $home);
1.481 raeburn 2296: if ($fetchresult eq 'ok') {
2297: return '/uploaded/'.$fpath.'/'.$fname;
2298: } else {
2299: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2300: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2301: return '/adm/notfound.html';
2302: }
1.477 raeburn 2303: }
2304: }
1.485 raeburn 2305: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2306: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2307: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2308: }
2309: return $fetchresult;
2310: }
2311:
1.637 raeburn 2312: sub build_filepath {
2313: my ($fpath) = @_;
2314: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2315: unless ($fpath eq '') {
2316: my @parts=split('/',$fpath);
2317: foreach my $part (@parts) {
2318: $filepath.= '/'.$part;
2319: if ((-e $filepath)!=1) {
2320: mkdir($filepath,0777);
2321: }
2322: }
2323: }
2324: return $filepath;
2325: }
2326:
2327: sub store_edited_file {
1.638 albertel 2328: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2329: my $file = $primary_url;
2330: $file =~ s#^/uploaded/$docudom/$docuname/##;
2331: my $fpath = '';
2332: my $fname = $file;
2333: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2334: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2335: my $filepath = &build_filepath($fpath);
2336: open(my $fh,'>'.$filepath.'/'.$fname);
2337: print $fh $content;
2338: close($fh);
1.638 albertel 2339: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2340: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2341: $home);
1.637 raeburn 2342: if ($$fetchresult eq 'ok') {
2343: return '/uploaded/'.$fpath.'/'.$fname;
2344: } else {
1.638 albertel 2345: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2346: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2347: return '/adm/notfound.html';
2348: }
2349: }
2350:
1.531 albertel 2351: sub clean_filename {
1.831 albertel 2352: my ($fname,$args)=@_;
1.315 www 2353: # Replace Windows backslashes by forward slashes
1.257 www 2354: $fname=~s/\\/\//g;
1.831 albertel 2355: if (!$args->{'keep_path'}) {
2356: # Get rid of everything but the actual filename
2357: $fname=~s/^.*\/([^\/]+)$/$1/;
2358: }
1.315 www 2359: # Replace spaces by underscores
2360: $fname=~s/\s+/\_/g;
2361: # Replace all other weird characters by nothing
1.831 albertel 2362: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2363: # Replace all .\d. sequences with _\d. so they no longer look like version
2364: # numbers
2365: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2366: return $fname;
2367: }
1.1051 raeburn 2368: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2369: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2370: # image with the same aspect ratio as the original, but with dimensions which do
2371: # not exceed $resizewidth and $resizeheight.
2372:
1.984 neumanie 2373: sub resizeImage {
1.1051 raeburn 2374: my ($img_path,$resizewidth,$resizeheight) = @_;
2375: my $ima = Image::Magick->new;
2376: my $resized;
2377: if (-e $img_path) {
2378: $ima->Read($img_path);
2379: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2380: my $width = $ima->Get('width');
2381: my $height = $ima->Get('height');
2382: if ($width > $resizewidth) {
2383: my $factor = $width/$resizewidth;
2384: my $newheight = $height/$factor;
2385: $ima->Scale(width=>$resizewidth,height=>$newheight);
2386: $resized = 1;
2387: }
2388: }
2389: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2390: my $width = $ima->Get('width');
2391: my $height = $ima->Get('height');
2392: if ($height > $resizeheight) {
2393: my $factor = $height/$resizeheight;
2394: my $newwidth = $width/$factor;
2395: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2396: $resized = 1;
2397: }
2398: }
2399: if ($resized) {
2400: $ima->Write($img_path);
2401: }
2402: }
2403: return;
1.977 amueller 2404: }
2405:
1.608 albertel 2406: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2407: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13 raeburn 2408: # the desired filename is in $env{"form.$formname.filename"}
2409: # $context - possible values: coursedoc, existingfile, overwrite,
2410: # canceloverwrite, or ''.
2411: # if 'coursedoc': upload to the current course
2412: # if 'existingfile': write file to tmp/overwrites directory
2413: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2414: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2415: # $subdir - directory in userfile to store the file into
1.858 raeburn 2416: # $parser - instruction to parse file for objects ($parser = parse)
2417: # $allfiles - reference to hash for embedded objects
2418: # $codebase - reference to hash for codebase of java objects
2419: # $desuname - username for permanent storage of uploaded file
2420: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2421: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2422: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2423: # $resizewidth - width (pixels) to which to resize uploaded image
2424: # $resizeheight - height (pixels) to which to resize uploaded image
1.1056.4.16 raeburn 2425: # $mimetype - reference to scalar to accommodate mime type determined
2426: # from File::MMagic if $parser = parse.
1.858 raeburn 2427: #
1.686 albertel 2428: # output: url of file in userspace, or error: <message>
2429: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2430:
1.531 albertel 2431: sub userfileupload {
1.1056.4.13 raeburn 2432: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1056.4.16 raeburn 2433: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2434: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2435: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2436: $fname=&clean_filename($fname);
1.1056.4.13 raeburn 2437: # See if there is anything left
1.257 www 2438: unless ($fname) { return 'error: no uploaded file'; }
1.1056.4.13 raeburn 2439: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2440: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2441: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2442: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2443: my $now = time;
1.1056.4.13 raeburn 2444: my $filepath;
2445: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2446: $filepath = 'tmp/helprequests/'.$now;
2447: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2448: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2449: '_'.$env{'user.domain'}.'/pending';
2450: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2451: my ($docuname,$docudom);
2452: if ($destudom) {
2453: $docudom = $destudom;
2454: } else {
2455: $docudom = $env{'user.domain'};
2456: }
2457: if ($destuname) {
2458: $docuname = $destuname;
2459: } else {
2460: $docuname = $env{'user.name'};
2461: }
2462: if (exists($env{'form.group'})) {
2463: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2464: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2465: }
2466: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2467: if ($context eq 'canceloverwrite') {
2468: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2469: if (-e $tempfile) {
2470: my @info = stat($tempfile);
2471: if ($info[9] eq $env{'form.timestamp'}) {
2472: unlink($tempfile);
2473: }
2474: }
2475: return;
1.523 raeburn 2476: }
2477: }
1.1056.4.13 raeburn 2478: # Create the directory if not present
1.741 raeburn 2479: my @parts=split(/\//,$filepath);
2480: my $fullpath = $perlvar{'lonDaemons'};
2481: for (my $i=0;$i<@parts;$i++) {
2482: $fullpath .= '/'.$parts[$i];
2483: if ((-e $fullpath)!=1) {
2484: mkdir($fullpath,0777);
2485: }
2486: }
2487: open(my $fh,'>'.$fullpath.'/'.$fname);
2488: print $fh $env{'form.'.$formname};
2489: close($fh);
1.1056.4.13 raeburn 2490: if ($context eq 'existingfile') {
2491: my @info = stat($fullpath.'/'.$fname);
2492: return ($fullpath.'/'.$fname,$info[9]);
2493: } else {
2494: return $fullpath.'/'.$fname;
2495: }
1.523 raeburn 2496: }
1.995 raeburn 2497: if ($subdir eq 'scantron') {
2498: $fname = 'scantron_orig_'.$fname;
1.1056.4.14 raeburn 2499: } else {
1.995 raeburn 2500: $fname="$subdir/$fname";
2501: }
1.1056.4.13 raeburn 2502: if ($context eq 'coursedoc') {
1.638 albertel 2503: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2504: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2505: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2506: return &finishuserfileupload($docuname,$docudom,
2507: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2508: $codebase,$thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2509: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2510: } else {
1.620 albertel 2511: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2512: return &process_coursefile('uploaddoc',$docuname,$docudom,
2513: $fname,$formname,$parser,
1.1056.4.16 raeburn 2514: $allfiles,$codebase,$mimetype);
1.481 raeburn 2515: }
1.719 banghart 2516: } elsif (defined($destuname)) {
2517: my $docuname=$destuname;
2518: my $docudom=$destudom;
1.860 raeburn 2519: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2520: $parser,$allfiles,$codebase,
1.1051 raeburn 2521: $thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2522: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2523: } else {
1.638 albertel 2524: my $docuname=$env{'user.name'};
2525: my $docudom=$env{'user.domain'};
1.714 raeburn 2526: if (exists($env{'form.group'})) {
2527: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2528: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2529: }
1.860 raeburn 2530: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2531: $parser,$allfiles,$codebase,
1.1051 raeburn 2532: $thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2533: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2534: }
1.271 www 2535: }
2536:
2537: sub finishuserfileupload {
1.860 raeburn 2538: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.16 raeburn 2539: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2540: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2541: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2542:
1.860 raeburn 2543: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2544: $file=$fname;
2545: if ($fname=~m|/|) {
2546: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2547: $path.=$fnamepath.'/';
2548: }
1.259 www 2549: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2550: my $count;
2551: for ($count=4;$count<=$#parts;$count++) {
2552: $filepath.="/$parts[$count]";
2553: if ((-e $filepath)!=1) {
2554: mkdir($filepath,0777);
2555: }
2556: }
1.984 neumanie 2557:
1.258 www 2558: # Save the file
2559: {
1.701 albertel 2560: if (!open(FH,'>'.$filepath.'/'.$file)) {
2561: &logthis('Failed to create '.$filepath.'/'.$file);
2562: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2563: return '/adm/notfound.html';
2564: }
1.1056.4.13 raeburn 2565: if ($context eq 'overwrite') {
2566: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2567: my $target = $filepath.'/'.$file;
2568: if (-e $source) {
2569: my @info = stat($source);
2570: if ($info[9] eq $env{'form.timestamp'}) {
2571: unless (&File::Copy::move($source,$target)) {
2572: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2573: return "Moving from $source failed";
2574: }
2575: } else {
2576: return "Temporary file: $source had unexpected date/time for last modification";
2577: }
2578: } else {
2579: return "Temporary file: $source missing";
2580: }
2581: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2582: &logthis('Failed to write to '.$filepath.'/'.$file);
2583: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2584: return '/adm/notfound.html';
2585: }
1.570 albertel 2586: close(FH);
1.1051 raeburn 2587: if ($resizewidth && $resizeheight) {
2588: my $mm = new File::MMagic;
2589: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2590: if ($mime_type =~ m{^image/}) {
2591: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2592: }
1.977 amueller 2593: }
1.258 www 2594: }
1.637 raeburn 2595: if ($parser eq 'parse') {
1.1024 raeburn 2596: my $mm = new File::MMagic;
1.1056.4.16 raeburn 2597: my $type = $mm->checktype_filename($filepath.'/'.$file);
2598: if ($type eq 'text/html') {
1.1024 raeburn 2599: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2600: $allfiles,$codebase);
2601: unless ($parse_result eq 'ok') {
2602: &logthis('Failed to parse '.$filepath.$file.
2603: ' for embedded media: '.$parse_result);
2604: }
1.637 raeburn 2605: }
1.1056.4.16 raeburn 2606: if (ref($mimetype)) {
2607: $$mimetype = $type;
2608: }
1.637 raeburn 2609: }
1.860 raeburn 2610: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2611: my $input = $filepath.'/'.$file;
2612: my $output = $filepath.'/'.'tn-'.$file;
2613: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2614: system("convert -sample $thumbsize $input $output");
2615: if (-e $filepath.'/'.'tn-'.$file) {
2616: $fetchthumb = 1;
2617: }
2618: }
1.858 raeburn 2619:
1.259 www 2620: # Notify homeserver to grep it
2621: #
1.984 neumanie 2622: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2623: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2624: if ($fetchresult eq 'ok') {
1.860 raeburn 2625: if ($fetchthumb) {
2626: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2627: if ($thumbresult ne 'ok') {
2628: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2629: $docuhome.': '.$thumbresult);
2630: }
2631: }
1.259 www 2632: #
1.258 www 2633: # Return the URL to it
1.494 albertel 2634: return '/uploaded/'.$path.$file;
1.263 www 2635: } else {
1.494 albertel 2636: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2637: ': '.$fetchresult);
1.263 www 2638: return '/adm/notfound.html';
1.858 raeburn 2639: }
1.493 albertel 2640: }
2641:
1.637 raeburn 2642: sub extract_embedded_items {
1.961 raeburn 2643: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2644: my @state = ();
2645: my %javafiles = (
2646: codebase => '',
2647: code => '',
2648: archive => ''
2649: );
2650: my %mediafiles = (
2651: src => '',
2652: movie => '',
2653: );
1.648 raeburn 2654: my $p;
2655: if ($content) {
2656: $p = HTML::LCParser->new($content);
2657: } else {
1.961 raeburn 2658: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2659: }
1.641 albertel 2660: while (my $t=$p->get_token()) {
1.640 albertel 2661: if ($t->[0] eq 'S') {
2662: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2663: push(@state, $tagname);
1.648 raeburn 2664: if (lc($tagname) eq 'allow') {
2665: &add_filetype($allfiles,$attr->{'src'},'src');
2666: }
1.640 albertel 2667: if (lc($tagname) eq 'img') {
2668: &add_filetype($allfiles,$attr->{'src'},'src');
2669: }
1.886 albertel 2670: if (lc($tagname) eq 'a') {
2671: &add_filetype($allfiles,$attr->{'href'},'href');
2672: }
1.645 raeburn 2673: if (lc($tagname) eq 'script') {
2674: if ($attr->{'archive'} =~ /\.jar$/i) {
2675: &add_filetype($allfiles,$attr->{'archive'},'archive');
2676: } else {
2677: &add_filetype($allfiles,$attr->{'src'},'src');
2678: }
2679: }
2680: if (lc($tagname) eq 'link') {
2681: if (lc($attr->{'rel'}) eq 'stylesheet') {
2682: &add_filetype($allfiles,$attr->{'href'},'href');
2683: }
2684: }
1.640 albertel 2685: if (lc($tagname) eq 'object' ||
2686: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2687: foreach my $item (keys(%javafiles)) {
2688: $javafiles{$item} = '';
2689: }
2690: }
2691: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2692: my $name = lc($attr->{'name'});
2693: foreach my $item (keys(%javafiles)) {
2694: if ($name eq $item) {
2695: $javafiles{$item} = $attr->{'value'};
2696: last;
2697: }
2698: }
2699: foreach my $item (keys(%mediafiles)) {
2700: if ($name eq $item) {
2701: &add_filetype($allfiles, $attr->{'value'}, 'value');
2702: last;
2703: }
2704: }
2705: }
2706: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2707: foreach my $item (keys(%javafiles)) {
2708: if ($attr->{$item}) {
2709: $javafiles{$item} = $attr->{$item};
2710: last;
2711: }
2712: }
2713: foreach my $item (keys(%mediafiles)) {
2714: if ($attr->{$item}) {
2715: &add_filetype($allfiles,$attr->{$item},$item);
2716: last;
2717: }
2718: }
2719: }
2720: } elsif ($t->[0] eq 'E') {
2721: my ($tagname) = ($t->[1]);
2722: if ($javafiles{'codebase'} ne '') {
2723: $javafiles{'codebase'} .= '/';
2724: }
2725: if (lc($tagname) eq 'applet' ||
2726: lc($tagname) eq 'object' ||
2727: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2728: ) {
2729: foreach my $item (keys(%javafiles)) {
2730: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2731: my $file=$javafiles{'codebase'}.$javafiles{$item};
2732: &add_filetype($allfiles,$file,$item);
2733: }
2734: }
2735: }
2736: pop @state;
2737: }
2738: }
1.637 raeburn 2739: return 'ok';
2740: }
2741:
1.639 albertel 2742: sub add_filetype {
2743: my ($allfiles,$file,$type)=@_;
2744: if (exists($allfiles->{$file})) {
2745: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2746: push(@{$allfiles->{$file}}, &escape($type));
2747: }
2748: } else {
2749: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2750: }
2751: }
2752:
1.493 albertel 2753: sub removeuploadedurl {
1.984 neumanie 2754: my ($url)=@_;
2755: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2756: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2757: }
2758:
2759: sub removeuserfile {
2760: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2761: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2762: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2763: if ($result eq 'ok') {
1.798 raeburn 2764: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2765: my $metafile = $fname.'.meta';
2766: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2767: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2768: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2769: my $sqlresult =
1.823 albertel 2770: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2771: 'portfolio_metadata',$group,
2772: 'delete');
1.798 raeburn 2773: }
2774: }
2775: return $result;
1.257 www 2776: }
1.15 www 2777:
1.530 albertel 2778: sub mkdiruserfile {
2779: my ($docuname,$docudom,$dir)=@_;
2780: my $home=&homeserver($docuname,$docudom);
2781: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2782: }
2783:
1.531 albertel 2784: sub renameuserfile {
2785: my ($docuname,$docudom,$old,$new)=@_;
2786: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2787: my $result = &reply("renameuserfile:$docudom:$docuname:".
2788: &escape("$old").':'.&escape("$new"),$home);
2789: if ($result eq 'ok') {
2790: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2791: my $oldmeta = $old.'.meta';
2792: my $newmeta = $new.'.meta';
2793: my $metaresult =
2794: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2795: my $url = "/uploaded/$docudom/$docuname/$old";
2796: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2797: my $sqlresult =
1.823 albertel 2798: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2799: 'portfolio_metadata',$group,
2800: 'delete');
1.798 raeburn 2801: }
2802: }
2803: return $result;
1.531 albertel 2804: }
2805:
1.14 www 2806: # ------------------------------------------------------------------------- Log
2807:
2808: sub log {
2809: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2810: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2811: }
2812:
2813: # ------------------------------------------------------------------ Course Log
1.352 www 2814: #
2815: # This routine flushes several buffers of non-mission-critical nature
2816: #
1.157 www 2817:
2818: sub flushcourselogs {
1.352 www 2819: &logthis('Flushing log buffers');
2820: #
2821: # course logs
2822: # This is a log of all transactions in a course, which can be used
2823: # for data mining purposes
2824: #
2825: # It also collects the courseid database, which lists last transaction
2826: # times and course titles for all courseids
2827: #
2828: my %courseidbuffer=();
1.921 raeburn 2829: foreach my $crsid (keys(%courselogs)) {
1.352 www 2830: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2831: &escape($courselogs{$crsid}),
2832: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2833: delete $courselogs{$crsid};
2834: } else {
2835: &logthis('Failed to flush log buffer for '.$crsid);
2836: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2837: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2838: " exceeded maximum size, deleting.</font>");
2839: delete $courselogs{$crsid};
2840: }
1.352 www 2841: }
1.920 raeburn 2842: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2843: 'description' => $coursedescrbuf{$crsid},
2844: 'inst_code' => $courseinstcodebuf{$crsid},
2845: 'type' => $coursetypebuf{$crsid},
2846: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2847: };
1.191 harris41 2848: }
1.352 www 2849: #
2850: # Write course id database (reverse lookup) to homeserver of courses
2851: # Is used in pickcourse
2852: #
1.840 albertel 2853: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2854: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2855: $courseidbuffer{$crs_home},
2856: $crs_home,'timeonly');
1.352 www 2857: }
2858: #
2859: # File accesses
2860: # Writes to the dynamic metadata of resources to get hit counts, etc.
2861: #
1.449 matthew 2862: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2863: if ($entry =~ /___count$/) {
2864: my ($dom,$name);
1.807 albertel 2865: ($dom,$name,undef)=
1.811 albertel 2866: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2867: if (! defined($dom) || $dom eq '' ||
2868: ! defined($name) || $name eq '') {
1.620 albertel 2869: my $cid = $env{'request.course.id'};
2870: $dom = $env{'request.'.$cid.'.domain'};
2871: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2872: }
1.450 matthew 2873: my $value = $accesshash{$entry};
2874: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2875: my %temphash=($url => $value);
1.449 matthew 2876: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2877: if ($result eq 'ok') {
2878: delete $accesshash{$entry};
2879: } elsif ($result eq 'unknown_cmd') {
2880: # Target server has old code running on it.
1.450 matthew 2881: my %temphash=($entry => $value);
1.449 matthew 2882: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2883: delete $accesshash{$entry};
2884: }
2885: }
2886: } else {
1.811 albertel 2887: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2888: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2889: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2890: delete $accesshash{$entry};
2891: }
1.185 www 2892: }
1.191 harris41 2893: }
1.352 www 2894: #
2895: # Roles
2896: # Reverse lookup of user roles for course faculty/staff and co-authorship
2897: #
1.800 albertel 2898: foreach my $entry (keys(%userrolehash)) {
1.351 www 2899: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2900: split(/\:/,$entry);
2901: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2902: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2903: $rudom,$runame) eq 'ok') {
2904: delete $userrolehash{$entry};
2905: }
2906: }
1.662 raeburn 2907: #
2908: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2909: #
2910: my %domrolebuffer = ();
1.1000 raeburn 2911: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2912: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2913: if ($domrolebuffer{$rudom}) {
2914: $domrolebuffer{$rudom}.='&'.&escape($entry).
2915: '='.&escape($domainrolehash{$entry});
2916: } else {
2917: $domrolebuffer{$rudom}.=&escape($entry).
2918: '='.&escape($domainrolehash{$entry});
2919: }
2920: delete $domainrolehash{$entry};
2921: }
2922: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2923: my %servers = &get_servers($dom,'library');
2924: foreach my $tryserver (keys(%servers)) {
2925: unless (&reply('domroleput:'.$dom.':'.
2926: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2927: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2928: }
1.662 raeburn 2929: }
2930: }
1.186 www 2931: $dumpcount++;
1.157 www 2932: }
2933:
2934: sub courselog {
2935: my $what=shift;
1.158 www 2936: $what=time.':'.$what;
1.620 albertel 2937: unless ($env{'request.course.id'}) { return ''; }
2938: $coursedombuf{$env{'request.course.id'}}=
2939: $env{'course.'.$env{'request.course.id'}.'.domain'};
2940: $coursenumbuf{$env{'request.course.id'}}=
2941: $env{'course.'.$env{'request.course.id'}.'.num'};
2942: $coursehombuf{$env{'request.course.id'}}=
2943: $env{'course.'.$env{'request.course.id'}.'.home'};
2944: $coursedescrbuf{$env{'request.course.id'}}=
2945: $env{'course.'.$env{'request.course.id'}.'.description'};
2946: $courseinstcodebuf{$env{'request.course.id'}}=
2947: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2948: $courseownerbuf{$env{'request.course.id'}}=
2949: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2950: $coursetypebuf{$env{'request.course.id'}}=
2951: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2952: if (defined $courselogs{$env{'request.course.id'}}) {
2953: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2954: } else {
1.620 albertel 2955: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2956: }
1.620 albertel 2957: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2958: &flushcourselogs();
2959: }
1.158 www 2960: }
2961:
2962: sub courseacclog {
2963: my $fnsymb=shift;
1.620 albertel 2964: unless ($env{'request.course.id'}) { return ''; }
2965: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2966: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2967: $what.=':POST';
1.583 matthew 2968: # FIXME: Probably ought to escape things....
1.800 albertel 2969: foreach my $key (keys(%env)) {
2970: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2971: my $formitem = $1;
2972: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2973: $what.=':'.$formitem.'='.$env{$key};
2974: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2975: $what.=':'.$formitem.'='.$env{$key};
2976: }
1.158 www 2977: }
1.191 harris41 2978: }
1.583 matthew 2979: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2980: # FIXME: We should not be depending on a form parameter that someone
2981: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2982: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2983: $what.= ':POST';
2984: # FIXME: Probably ought to escape things....
2985: foreach my $element ('courseexp','crsfulltext','crsrelated',
2986: 'crsdiscuss') {
1.620 albertel 2987: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2988: }
2989: }
1.158 www 2990: }
2991: &courselog($what);
1.149 www 2992: }
2993:
1.185 www 2994: sub countacc {
2995: my $url=&declutter(shift);
1.458 matthew 2996: return if (! defined($url) || $url eq '');
1.620 albertel 2997: unless ($env{'request.course.id'}) { return ''; }
2998: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2999: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3000: $accesshash{$key}++;
1.185 www 3001: }
1.349 www 3002:
1.361 www 3003: sub linklog {
3004: my ($from,$to)=@_;
3005: $from=&declutter($from);
3006: $to=&declutter($to);
3007: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3008: $accesshash{$to.'___'.$from.'___goto'}=1;
3009: }
3010:
1.349 www 3011: sub userrolelog {
3012: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3013: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3014: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3015: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3016: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3017: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3018: $userrolehash
3019: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3020: =$tend.':'.$tstart;
1.662 raeburn 3021: }
1.898 albertel 3022: if (($env{'request.role'} =~ /dc\./) &&
3023: (($trole=~/^au/) || ($trole=~/^in/) ||
3024: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3025: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3026: ($trole=~/^co/))) {
1.898 albertel 3027: $userrolehash
3028: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3029: =$tend.':'.$tstart;
3030: }
1.662 raeburn 3031: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3032: ($trole=~/^li/) || ($trole=~/^li/) ||
3033: ($trole=~/^au/) || ($trole=~/^dg/) ||
3034: ($trole=~/^sc/)) {
3035: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3036: $domainrolehash
3037: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3038: = $tend.':'.$tstart;
3039: }
1.351 www 3040: }
3041:
1.957 raeburn 3042: sub courserolelog {
3043: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3044: if (($trole eq 'cc') || ($trole eq 'in') ||
3045: ($trole eq 'ep') || ($trole eq 'ad') ||
3046: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3047: ($trole=~/^cr/) || ($trole eq 'gr') ||
3048: ($trole eq 'co')) {
1.957 raeburn 3049: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3050: my $cdom = $1;
3051: my $cnum = $2;
3052: my $sec = $3;
3053: my $namespace = 'rolelog';
3054: my %storehash = (
3055: role => $trole,
3056: start => $tstart,
3057: end => $tend,
3058: selfenroll => $selfenroll,
3059: context => $context,
3060: );
3061: if ($trole eq 'gr') {
3062: $namespace = 'groupslog';
3063: $storehash{'group'} = $sec;
3064: } else {
3065: $storehash{'section'} = $sec;
3066: }
3067: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3068: if (($trole ne 'st') || ($sec ne '')) {
3069: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3070: }
1.957 raeburn 3071: }
3072: }
3073: return;
3074: }
3075:
1.351 www 3076: sub get_course_adv_roles {
1.948 raeburn 3077: my ($cid,$codes) = @_;
1.620 albertel 3078: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3079: my %coursehash=&coursedescription($cid);
1.988 raeburn 3080: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3081: my %nothide=();
1.800 albertel 3082: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3083: if ($user !~ /:/) {
3084: $nothide{join(':',split(/[\@]/,$user))}=1;
3085: } else {
3086: $nothide{$user}=1;
3087: }
1.470 www 3088: }
1.351 www 3089: my %returnhash=();
3090: my %dumphash=
3091: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3092: my $now=time;
1.997 raeburn 3093: my %privileged;
1.1000 raeburn 3094: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3095: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3096: if (($tstart) && ($tstart<0)) { next; }
3097: if (($tend) && ($tend<$now)) { next; }
3098: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3099: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3100: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3101: unless (ref($privileged{$domain}) eq 'HASH') {
3102: my %dompersonnel =
1.998 raeburn 3103: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3104: $privileged{$domain} = {};
3105: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3106: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3107: foreach my $user (keys(%{$dompersonnel{$server}})) {
3108: my ($trole,$uname,$udom) = split(/:/,$user);
3109: $privileged{$udom}{$uname} = 1;
3110: }
3111: }
3112: }
3113: }
3114: if ((exists($privileged{$domain}{$username})) &&
3115: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3116: if ($role eq 'cr') { next; }
1.948 raeburn 3117: if ($codes) {
3118: if ($section) { $role .= ':'.$section; }
3119: if ($returnhash{$role}) {
3120: $returnhash{$role}.=','.$username.':'.$domain;
3121: } else {
3122: $returnhash{$role}=$username.':'.$domain;
3123: }
1.351 www 3124: } else {
1.988 raeburn 3125: my $key=&plaintext($role,$crstype);
1.973 bisitz 3126: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3127: if ($returnhash{$key}) {
3128: $returnhash{$key}.=','.$username.':'.$domain;
3129: } else {
3130: $returnhash{$key}=$username.':'.$domain;
3131: }
1.351 www 3132: }
1.948 raeburn 3133: }
1.400 www 3134: return %returnhash;
3135: }
3136:
3137: sub get_my_roles {
1.937 raeburn 3138: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3139: unless (defined($uname)) { $uname=$env{'user.name'}; }
3140: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3141: my (%dumphash,%nothide);
1.858 raeburn 3142: if ($context eq 'userroles') {
1.1056.4.10 raeburn 3143: my $extra = &freeze_escape({'skipcheck' => 1});
3144: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3145: } else {
3146: %dumphash=
1.400 www 3147: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3148: if ($hidepriv) {
3149: my %coursehash=&coursedescription($udom.'_'.$uname);
3150: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3151: if ($user !~ /:/) {
3152: $nothide{join(':',split(/[\@]/,$user))} = 1;
3153: } else {
3154: $nothide{$user} = 1;
3155: }
3156: }
3157: }
1.858 raeburn 3158: }
1.400 www 3159: my %returnhash=();
3160: my $now=time;
1.999 raeburn 3161: my %privileged;
1.800 albertel 3162: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3163: my ($role,$tend,$tstart);
3164: if ($context eq 'userroles') {
3165: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3166: } else {
3167: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3168: }
1.400 www 3169: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3170: my $status = 'active';
1.939 raeburn 3171: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3172: $status = 'previous';
3173: }
3174: if (($tstart) && ($now<$tstart)) {
3175: $status = 'future';
3176: }
3177: if (ref($types) eq 'ARRAY') {
3178: if (!grep(/^\Q$status\E$/,@{$types})) {
3179: next;
3180: }
3181: } else {
3182: if ($status ne 'active') {
3183: next;
3184: }
3185: }
1.867 raeburn 3186: my ($rolecode,$username,$domain,$section,$area);
3187: if ($context eq 'userroles') {
3188: ($area,$rolecode) = split(/_/,$entry);
3189: (undef,$domain,$username,$section) = split(/\//,$area);
3190: } else {
3191: ($role,$username,$domain,$section) = split(/\:/,$entry);
3192: }
1.832 raeburn 3193: if (ref($roledoms) eq 'ARRAY') {
3194: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3195: next;
3196: }
3197: }
3198: if (ref($roles) eq 'ARRAY') {
3199: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3200: if ($role =~ /^cr\//) {
3201: if (!grep(/^cr$/,@{$roles})) {
3202: next;
3203: }
3204: } else {
3205: next;
3206: }
1.832 raeburn 3207: }
1.867 raeburn 3208: }
1.937 raeburn 3209: if ($hidepriv) {
1.999 raeburn 3210: if ($context eq 'userroles') {
3211: if ((&privileged($username,$domain)) &&
3212: (!$nothide{$username.':'.$domain})) {
3213: next;
3214: }
3215: } else {
3216: unless (ref($privileged{$domain}) eq 'HASH') {
3217: my %dompersonnel =
3218: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3219: $privileged{$domain} = {};
3220: if (keys(%dompersonnel)) {
3221: foreach my $server (keys(%dompersonnel)) {
3222: if (ref($dompersonnel{$server}) eq 'HASH') {
3223: foreach my $user (keys(%{$dompersonnel{$server}})) {
3224: my ($trole,$uname,$udom) = split(/:/,$user);
3225: $privileged{$udom}{$uname} = $trole;
3226: }
3227: }
3228: }
3229: }
3230: }
3231: if (exists($privileged{$domain}{$username})) {
3232: if (!$nothide{$username.':'.$domain}) {
3233: next;
3234: }
3235: }
1.937 raeburn 3236: }
3237: }
1.933 raeburn 3238: if ($withsec) {
3239: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3240: $tstart.':'.$tend;
3241: } else {
3242: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3243: }
1.832 raeburn 3244: }
1.373 www 3245: return %returnhash;
1.399 www 3246: }
3247:
3248: # ----------------------------------------------------- Frontpage Announcements
3249: #
3250: #
3251:
3252: sub postannounce {
3253: my ($server,$text)=@_;
1.844 albertel 3254: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3255: unless ($text=~/\w/) { $text=''; }
3256: return &reply('setannounce:'.&escape($text),$server);
3257: }
3258:
3259: sub getannounce {
1.448 albertel 3260:
3261: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3262: my $announcement='';
1.800 albertel 3263: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3264: close($fh);
1.399 www 3265: if ($announcement=~/\w/) {
3266: return
3267: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3268: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3269: } else {
3270: return '';
3271: }
3272: } else {
3273: return '';
3274: }
1.351 www 3275: }
1.353 www 3276:
3277: # ---------------------------------------------------------- Course ID routines
3278: # Deal with domain's nohist_courseid.db files
3279: #
3280:
3281: sub courseidput {
1.921 raeburn 3282: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3283: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3284: my $outcome;
3285: if ($caller eq 'timeonly') {
3286: my $cids = '';
3287: foreach my $item (keys(%$storehash)) {
3288: $cids.=&escape($item).'&';
3289: }
3290: $cids=~s/\&$//;
3291: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3292: $coursehome);
3293: } else {
3294: my $items = '';
3295: foreach my $item (keys(%$storehash)) {
3296: $items.= &escape($item).'='.
3297: &freeze_escape($$storehash{$item}).'&';
3298: }
3299: $items=~s/\&$//;
3300: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3301: $coursehome);
1.918 raeburn 3302: }
3303: if ($outcome eq 'unknown_cmd') {
3304: my $what;
3305: foreach my $cid (keys(%$storehash)) {
3306: $what .= &escape($cid).'=';
1.921 raeburn 3307: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3308: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3309: }
3310: $what =~ s/\:$/&/;
3311: }
3312: $what =~ s/\&$//;
3313: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3314: } else {
3315: return $outcome;
3316: }
1.353 www 3317: }
3318:
3319: sub courseiddump {
1.921 raeburn 3320: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3321: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3322: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3 raeburn 3323: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3324: my $as_hash = 1;
3325: my %returnhash;
3326: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3327: my %libserv = &all_library();
3328: foreach my $tryserver (keys(%libserv)) {
3329: if ( ( $hostidflag == 1
3330: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3331: || (!defined($hostidflag)) ) {
3332:
1.918 raeburn 3333: if (($domfilter eq '') ||
3334: (&host_domain($tryserver) eq $domfilter)) {
3335: my $rep =
3336: &reply('courseiddump:'.&host_domain($tryserver).':'.
3337: $sincefilter.':'.&escape($descfilter).':'.
3338: &escape($instcodefilter).':'.&escape($ownerfilter).
3339: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3340: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3341: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3342: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3343: &escape($cc_clone).':'.$cloneonly.':'.
3344: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3 raeburn 3345: &escape($creationcontext).':'.$domcloner,
3346: $tryserver);
1.918 raeburn 3347: my @pairs=split(/\&/,$rep);
3348: foreach my $item (@pairs) {
3349: my ($key,$value)=split(/\=/,$item,2);
3350: $key = &unescape($key);
3351: next if ($key =~ /^error: 2 /);
3352: my $result = &thaw_unescape($value);
3353: if (ref($result) eq 'HASH') {
3354: $returnhash{$key}=$result;
3355: } else {
1.921 raeburn 3356: my @responses = split(/:/,$value);
3357: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3358: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3359: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3360: }
1.1008 raeburn 3361: }
1.353 www 3362: }
3363: }
3364: }
3365: }
3366: return %returnhash;
3367: }
3368:
1.1055 raeburn 3369: sub courselastaccess {
3370: my ($cdom,$cnum,$hostidref) = @_;
3371: my %returnhash;
3372: if ($cdom && $cnum) {
3373: my $chome = &homeserver($cnum,$cdom);
3374: if ($chome ne 'no_host') {
3375: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3376: &extract_lastaccess(\%returnhash,$rep);
3377: }
3378: } else {
3379: if (!$cdom) { $cdom=''; }
3380: my %libserv = &all_library();
3381: foreach my $tryserver (keys(%libserv)) {
3382: if (ref($hostidref) eq 'ARRAY') {
3383: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3384: }
3385: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3386: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3387: &extract_lastaccess(\%returnhash,$rep);
3388: }
3389: }
3390: }
3391: return %returnhash;
3392: }
3393:
3394: sub extract_lastaccess {
3395: my ($returnhash,$rep) = @_;
3396: if (ref($returnhash) eq 'HASH') {
3397: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3398: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3399: $rep eq '') {
3400: my @pairs=split(/\&/,$rep);
3401: foreach my $item (@pairs) {
3402: my ($key,$value)=split(/\=/,$item,2);
3403: $key = &unescape($key);
3404: next if ($key =~ /^error: 2 /);
3405: $returnhash->{$key} = &thaw_unescape($value);
3406: }
3407: }
3408: }
3409: return;
3410: }
3411:
1.658 raeburn 3412: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3413:
3414: sub dcmailput {
1.685 raeburn 3415: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3416: my $status = &Apache::lonnet::critical(
1.740 www 3417: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3418: &escape($message),$server);
1.662 raeburn 3419: return $status;
3420: }
3421:
1.658 raeburn 3422: sub dcmaildump {
3423: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3424: my %returnhash=();
1.846 albertel 3425:
3426: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3427: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3428: &escape($enddate).':';
3429: my @esc_senders=map { &escape($_)} @$senders;
3430: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3431: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3432: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3433: if (($key) && ($value)) {
3434: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3435: }
3436: }
3437: }
3438: return %returnhash;
3439: }
1.662 raeburn 3440: # ---------------------------------------------------------- Domain roles
3441:
3442: sub get_domain_roles {
3443: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3444: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3445: $startdate = '.';
3446: }
1.1018 raeburn 3447: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3448: $enddate = '.';
3449: }
1.922 raeburn 3450: my $rolelist;
3451: if (ref($roles) eq 'ARRAY') {
3452: $rolelist = join(':',@{$roles});
3453: }
1.662 raeburn 3454: my %personnel = ();
1.841 albertel 3455:
3456: my %servers = &get_servers($dom,'library');
3457: foreach my $tryserver (keys(%servers)) {
3458: %{$personnel{$tryserver}}=();
3459: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3460: &escape($startdate).':'.
3461: &escape($enddate).':'.
3462: &escape($rolelist), $tryserver))) {
3463: my ($key,$value) = split(/\=/,$line,2);
3464: if (($key) && ($value)) {
3465: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3466: }
3467: }
1.662 raeburn 3468: }
3469: return %personnel;
3470: }
1.658 raeburn 3471:
1.149 www 3472: # ----------------------------------------------------------- Check out an item
3473:
1.504 albertel 3474: sub get_first_access {
3475: my ($type,$argsymb)=@_;
1.790 albertel 3476: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3477: if ($argsymb) { $symb=$argsymb; }
3478: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3479: if ($type eq 'course') {
3480: $res='course';
3481: } elsif ($type eq 'map') {
1.588 albertel 3482: $res=&symbread($map);
3483: } else {
3484: $res=$symb;
3485: }
3486: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3487: return $times{"$courseid\0$res"};
1.504 albertel 3488: }
3489:
3490: sub set_first_access {
3491: my ($type)=@_;
1.790 albertel 3492: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3493: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3494: if ($type eq 'course') {
3495: $res='course';
3496: } elsif ($type eq 'map') {
1.588 albertel 3497: $res=&symbread($map);
3498: } else {
3499: $res=$symb;
3500: }
3501: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3502: if (!$firstaccess) {
1.588 albertel 3503: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3504: }
3505: return 'already_set';
1.504 albertel 3506: }
3507:
1.149 www 3508: sub checkout {
3509: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3510: my $now=time;
3511: my $lonhost=$perlvar{'lonHostID'};
3512: my $infostr=&escape(
1.234 www 3513: 'CHECKOUTTOKEN&'.
1.149 www 3514: $tuname.'&'.
3515: $tudom.'&'.
3516: $tcrsid.'&'.
3517: $symb.'&'.
3518: $now.'&'.$ENV{'REMOTE_ADDR'});
3519: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3520: if ($token=~/^error\:/) {
1.672 albertel 3521: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3522: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3523: "</font>");
3524: return '';
3525: }
3526:
1.149 www 3527: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3528: $token=~tr/a-z/A-Z/;
3529:
1.153 www 3530: my %infohash=('resource.0.outtoken' => $token,
3531: 'resource.0.checkouttime' => $now,
3532: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3533:
3534: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3535: return '';
1.151 www 3536: } else {
1.672 albertel 3537: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3538: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3539: "</font>");
1.149 www 3540: }
3541:
3542: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3543: &escape('Checkout '.$infostr.' - '.
3544: $token)) ne 'ok') {
3545: return '';
1.151 www 3546: } else {
1.672 albertel 3547: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3548: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3549: "</font>");
1.149 www 3550: }
1.151 www 3551: return $token;
1.149 www 3552: }
3553:
3554: # ------------------------------------------------------------ Check in an item
3555:
3556: sub checkin {
3557: my $token=shift;
1.150 www 3558: my $now=time;
3559: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3560: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3561: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3562: $dtoken=~s/\W/\_/g;
1.234 www 3563: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3564: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3565:
1.154 www 3566: unless (($tuname) && ($tudom)) {
3567: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3568: return '';
3569: }
3570:
3571: unless (&allowed('mgr',$tcrsid)) {
3572: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3573: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3574: return '';
3575: }
3576:
1.153 www 3577: my %infohash=('resource.0.intoken' => $token,
3578: 'resource.0.checkintime' => $now,
3579: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3580:
3581: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3582: return '';
3583: }
3584:
3585: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3586: &escape('Checkin - '.$token)) ne 'ok') {
3587: return '';
3588: }
3589:
3590: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3591: }
3592:
3593: # --------------------------------------------- Set Expire Date for Spreadsheet
3594:
3595: sub expirespread {
3596: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3597: my $cid=$env{'request.course.id'};
1.110 www 3598: if ($cid) {
3599: my $now=time;
3600: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3601: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3602: $env{'course.'.$cid.'.num'}.
1.110 www 3603: ':nohist_expirationdates:'.
3604: &escape($key).'='.$now,
1.620 albertel 3605: $env{'course.'.$cid.'.home'})
1.110 www 3606: }
3607: return 'ok';
1.14 www 3608: }
3609:
1.109 www 3610: # ----------------------------------------------------- Devalidate Spreadsheets
3611:
3612: sub devalidate {
1.325 www 3613: my ($symb,$uname,$udom)=@_;
1.620 albertel 3614: my $cid=$env{'request.course.id'};
1.109 www 3615: if ($cid) {
1.391 matthew 3616: # delete the stored spreadsheets for
3617: # - the student level sheet of this user in course's homespace
3618: # - the assessment level sheet for this resource
3619: # for this user in user's homespace
1.553 albertel 3620: # - current conditional state info
1.325 www 3621: my $key=$uname.':'.$udom.':';
1.109 www 3622: my $status=
1.299 matthew 3623: &del('nohist_calculatedsheets',
1.391 matthew 3624: [$key.'studentcalc:'],
1.620 albertel 3625: $env{'course.'.$cid.'.domain'},
3626: $env{'course.'.$cid.'.num'})
1.133 albertel 3627: .' '.
3628: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3629: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3630: unless ($status eq 'ok ok') {
3631: &logthis('Could not devalidate spreadsheet '.
1.325 www 3632: $uname.' at '.$udom.' for '.
1.109 www 3633: $symb.': '.$status);
1.133 albertel 3634: }
1.553 albertel 3635: &delenv('user.state.'.$cid);
1.109 www 3636: }
3637: }
3638:
1.265 albertel 3639: sub get_scalar {
3640: my ($string,$end) = @_;
3641: my $value;
3642: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3643: $value = $1;
3644: } elsif ($$string =~ s/^([^&]*?)&//) {
3645: $value = $1;
3646: }
3647: return &unescape($value);
3648: }
3649:
3650: sub array2str {
3651: my (@array) = @_;
3652: my $result=&arrayref2str(\@array);
3653: $result=~s/^__ARRAY_REF__//;
3654: $result=~s/__END_ARRAY_REF__$//;
3655: return $result;
3656: }
3657:
1.204 albertel 3658: sub arrayref2str {
3659: my ($arrayref) = @_;
1.265 albertel 3660: my $result='__ARRAY_REF__';
1.204 albertel 3661: foreach my $elem (@$arrayref) {
1.265 albertel 3662: if(ref($elem) eq 'ARRAY') {
3663: $result.=&arrayref2str($elem).'&';
3664: } elsif(ref($elem) eq 'HASH') {
3665: $result.=&hashref2str($elem).'&';
3666: } elsif(ref($elem)) {
3667: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3668: } else {
3669: $result.=&escape($elem).'&';
3670: }
3671: }
3672: $result=~s/\&$//;
1.265 albertel 3673: $result .= '__END_ARRAY_REF__';
1.204 albertel 3674: return $result;
3675: }
3676:
1.168 albertel 3677: sub hash2str {
1.204 albertel 3678: my (%hash) = @_;
3679: my $result=&hashref2str(\%hash);
1.265 albertel 3680: $result=~s/^__HASH_REF__//;
3681: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3682: return $result;
3683: }
3684:
3685: sub hashref2str {
3686: my ($hashref)=@_;
1.265 albertel 3687: my $result='__HASH_REF__';
1.800 albertel 3688: foreach my $key (sort(keys(%$hashref))) {
3689: if (ref($key) eq 'ARRAY') {
3690: $result.=&arrayref2str($key).'=';
3691: } elsif (ref($key) eq 'HASH') {
3692: $result.=&hashref2str($key).'=';
3693: } elsif (ref($key)) {
1.265 albertel 3694: $result.='=';
1.800 albertel 3695: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3696: } else {
1.800 albertel 3697: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3698: }
3699:
1.800 albertel 3700: if(ref($hashref->{$key}) eq 'ARRAY') {
3701: $result.=&arrayref2str($hashref->{$key}).'&';
3702: } elsif(ref($hashref->{$key}) eq 'HASH') {
3703: $result.=&hashref2str($hashref->{$key}).'&';
3704: } elsif(ref($hashref->{$key})) {
1.265 albertel 3705: $result.='&';
1.800 albertel 3706: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3707: } else {
1.800 albertel 3708: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3709: }
3710: }
1.168 albertel 3711: $result=~s/\&$//;
1.265 albertel 3712: $result .= '__END_HASH_REF__';
1.168 albertel 3713: return $result;
3714: }
3715:
3716: sub str2hash {
1.265 albertel 3717: my ($string)=@_;
3718: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3719: return %$hash;
3720: }
3721:
3722: sub str2hashref {
1.168 albertel 3723: my ($string) = @_;
1.265 albertel 3724:
3725: my %hash;
3726:
3727: if($string !~ /^__HASH_REF__/) {
3728: if (! ($string eq '' || !defined($string))) {
3729: $hash{'error'}='Not hash reference';
3730: }
3731: return (\%hash, $string);
3732: }
3733:
3734: $string =~ s/^__HASH_REF__//;
3735:
3736: while($string !~ /^__END_HASH_REF__/) {
3737: #key
3738: my $key='';
3739: if($string =~ /^__HASH_REF__/) {
3740: ($key, $string)=&str2hashref($string);
3741: if(defined($key->{'error'})) {
3742: $hash{'error'}='Bad data';
3743: return (\%hash, $string);
3744: }
3745: } elsif($string =~ /^__ARRAY_REF__/) {
3746: ($key, $string)=&str2arrayref($string);
3747: if($key->[0] eq 'Array reference error') {
3748: $hash{'error'}='Bad data';
3749: return (\%hash, $string);
3750: }
3751: } else {
3752: $string =~ s/^(.*?)=//;
1.267 albertel 3753: $key=&unescape($1);
1.265 albertel 3754: }
3755: $string =~ s/^=//;
3756:
3757: #value
3758: my $value='';
3759: if($string =~ /^__HASH_REF__/) {
3760: ($value, $string)=&str2hashref($string);
3761: if(defined($value->{'error'})) {
3762: $hash{'error'}='Bad data';
3763: return (\%hash, $string);
3764: }
3765: } elsif($string =~ /^__ARRAY_REF__/) {
3766: ($value, $string)=&str2arrayref($string);
3767: if($value->[0] eq 'Array reference error') {
3768: $hash{'error'}='Bad data';
3769: return (\%hash, $string);
3770: }
3771: } else {
3772: $value=&get_scalar(\$string,'__END_HASH_REF__');
3773: }
3774: $string =~ s/^&//;
3775:
3776: $hash{$key}=$value;
1.204 albertel 3777: }
1.265 albertel 3778:
3779: $string =~ s/^__END_HASH_REF__//;
3780:
3781: return (\%hash, $string);
1.204 albertel 3782: }
3783:
3784: sub str2array {
1.265 albertel 3785: my ($string)=@_;
3786: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3787: return @$array;
3788: }
3789:
3790: sub str2arrayref {
1.204 albertel 3791: my ($string) = @_;
1.265 albertel 3792: my @array;
3793:
3794: if($string !~ /^__ARRAY_REF__/) {
3795: if (! ($string eq '' || !defined($string))) {
3796: $array[0]='Array reference error';
3797: }
3798: return (\@array, $string);
3799: }
3800:
3801: $string =~ s/^__ARRAY_REF__//;
3802:
3803: while($string !~ /^__END_ARRAY_REF__/) {
3804: my $value='';
3805: if($string =~ /^__HASH_REF__/) {
3806: ($value, $string)=&str2hashref($string);
3807: if(defined($value->{'error'})) {
3808: $array[0] ='Array reference error';
3809: return (\@array, $string);
3810: }
3811: } elsif($string =~ /^__ARRAY_REF__/) {
3812: ($value, $string)=&str2arrayref($string);
3813: if($value->[0] eq 'Array reference error') {
3814: $array[0] ='Array reference error';
3815: return (\@array, $string);
3816: }
3817: } else {
3818: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3819: }
3820: $string =~ s/^&//;
3821:
3822: push(@array, $value);
1.191 harris41 3823: }
1.265 albertel 3824:
3825: $string =~ s/^__END_ARRAY_REF__//;
3826:
3827: return (\@array, $string);
1.168 albertel 3828: }
3829:
1.167 albertel 3830: # -------------------------------------------------------------------Temp Store
3831:
1.168 albertel 3832: sub tmpreset {
3833: my ($symb,$namespace,$domain,$stuname) = @_;
3834: if (!$symb) {
3835: $symb=&symbread();
1.620 albertel 3836: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3837: }
3838: $symb=escape($symb);
3839:
1.620 albertel 3840: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3841: $namespace=~s/\//\_/g;
3842: $namespace=~s/\W//g;
3843:
1.620 albertel 3844: if (!$domain) { $domain=$env{'user.domain'}; }
3845: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3846: if ($domain eq 'public' && $stuname eq 'public') {
3847: $stuname=$ENV{'REMOTE_ADDR'};
3848: }
1.168 albertel 3849: my $path=$perlvar{'lonDaemons'}.'/tmp';
3850: my %hash;
3851: if (tie(%hash,'GDBM_File',
3852: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3853: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3854: foreach my $key (keys(%hash)) {
1.180 albertel 3855: if ($key=~ /:$symb/) {
1.168 albertel 3856: delete($hash{$key});
3857: }
3858: }
3859: }
3860: }
3861:
1.167 albertel 3862: sub tmpstore {
1.168 albertel 3863: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3864:
3865: if (!$symb) {
3866: $symb=&symbread();
1.620 albertel 3867: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3868: }
3869: $symb=escape($symb);
3870:
3871: if (!$namespace) {
3872: # I don't think we would ever want to store this for a course.
3873: # it seems this will only be used if we don't have a course.
1.620 albertel 3874: #$namespace=$env{'request.course.id'};
1.168 albertel 3875: #if (!$namespace) {
1.620 albertel 3876: $namespace=$env{'request.state'};
1.168 albertel 3877: #}
3878: }
3879: $namespace=~s/\//\_/g;
3880: $namespace=~s/\W//g;
1.620 albertel 3881: if (!$domain) { $domain=$env{'user.domain'}; }
3882: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3883: if ($domain eq 'public' && $stuname eq 'public') {
3884: $stuname=$ENV{'REMOTE_ADDR'};
3885: }
1.168 albertel 3886: my $now=time;
3887: my %hash;
3888: my $path=$perlvar{'lonDaemons'}.'/tmp';
3889: if (tie(%hash,'GDBM_File',
3890: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3891: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3892: $hash{"version:$symb"}++;
3893: my $version=$hash{"version:$symb"};
3894: my $allkeys='';
3895: foreach my $key (keys(%$storehash)) {
3896: $allkeys.=$key.':';
1.591 albertel 3897: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3898: }
3899: $hash{"$version:$symb:timestamp"}=$now;
3900: $allkeys.='timestamp';
3901: $hash{"$version:keys:$symb"}=$allkeys;
3902: if (untie(%hash)) {
3903: return 'ok';
3904: } else {
3905: return "error:$!";
3906: }
3907: } else {
3908: return "error:$!";
3909: }
3910: }
1.167 albertel 3911:
1.168 albertel 3912: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3913:
1.168 albertel 3914: sub tmprestore {
3915: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3916:
1.168 albertel 3917: if (!$symb) {
3918: $symb=&symbread();
1.620 albertel 3919: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3920: }
3921: $symb=escape($symb);
3922:
1.620 albertel 3923: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3924:
1.620 albertel 3925: if (!$domain) { $domain=$env{'user.domain'}; }
3926: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3927: if ($domain eq 'public' && $stuname eq 'public') {
3928: $stuname=$ENV{'REMOTE_ADDR'};
3929: }
1.168 albertel 3930: my %returnhash;
3931: $namespace=~s/\//\_/g;
3932: $namespace=~s/\W//g;
3933: my %hash;
3934: my $path=$perlvar{'lonDaemons'}.'/tmp';
3935: if (tie(%hash,'GDBM_File',
3936: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3937: &GDBM_READER(),0640)) {
1.168 albertel 3938: my $version=$hash{"version:$symb"};
3939: $returnhash{'version'}=$version;
3940: my $scope;
3941: for ($scope=1;$scope<=$version;$scope++) {
3942: my $vkeys=$hash{"$scope:keys:$symb"};
3943: my @keys=split(/:/,$vkeys);
3944: my $key;
3945: $returnhash{"$scope:keys"}=$vkeys;
3946: foreach $key (@keys) {
1.591 albertel 3947: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3948: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3949: }
3950: }
1.168 albertel 3951: if (!(untie(%hash))) {
3952: return "error:$!";
3953: }
3954: } else {
3955: return "error:$!";
3956: }
3957: return %returnhash;
1.167 albertel 3958: }
3959:
1.9 www 3960: # ----------------------------------------------------------------------- Store
3961:
3962: sub store {
1.124 www 3963: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3964: my $home='';
3965:
1.168 albertel 3966: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3967:
1.213 www 3968: $symb=&symbclean($symb);
1.122 albertel 3969: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3970:
1.620 albertel 3971: if (!$domain) { $domain=$env{'user.domain'}; }
3972: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3973:
3974: &devalidate($symb,$stuname,$domain);
1.109 www 3975:
3976: $symb=escape($symb);
1.187 www 3977: if (!$namespace) {
1.620 albertel 3978: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3979: return '';
3980: }
3981: }
1.620 albertel 3982: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3983:
3984: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3985: $$storehash{'host'}=$perlvar{'lonHostID'};
3986:
1.12 www 3987: my $namevalue='';
1.800 albertel 3988: foreach my $key (keys(%$storehash)) {
3989: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3990: }
1.12 www 3991: $namevalue=~s/\&$//;
1.187 www 3992: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3993: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3994: }
3995:
1.47 www 3996: # -------------------------------------------------------------- Critical Store
3997:
3998: sub cstore {
1.124 www 3999: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4000: my $home='';
4001:
1.168 albertel 4002: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4003:
1.213 www 4004: $symb=&symbclean($symb);
1.122 albertel 4005: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4006:
1.620 albertel 4007: if (!$domain) { $domain=$env{'user.domain'}; }
4008: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4009:
4010: &devalidate($symb,$stuname,$domain);
1.109 www 4011:
4012: $symb=escape($symb);
1.187 www 4013: if (!$namespace) {
1.620 albertel 4014: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4015: return '';
4016: }
4017: }
1.620 albertel 4018: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4019:
4020: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4021: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4022:
1.47 www 4023: my $namevalue='';
1.800 albertel 4024: foreach my $key (keys(%$storehash)) {
4025: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4026: }
1.47 www 4027: $namevalue=~s/\&$//;
1.187 www 4028: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4029: return critical
4030: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4031: }
4032:
1.9 www 4033: # --------------------------------------------------------------------- Restore
4034:
4035: sub restore {
1.124 www 4036: my ($symb,$namespace,$domain,$stuname) = @_;
4037: my $home='';
4038:
1.168 albertel 4039: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4040:
1.122 albertel 4041: if (!$symb) {
4042: unless ($symb=escape(&symbread())) { return ''; }
4043: } else {
1.213 www 4044: $symb=&escape(&symbclean($symb));
1.122 albertel 4045: }
1.188 www 4046: if (!$namespace) {
1.620 albertel 4047: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4048: return '';
4049: }
4050: }
1.620 albertel 4051: if (!$domain) { $domain=$env{'user.domain'}; }
4052: if (!$stuname) { $stuname=$env{'user.name'}; }
4053: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4054: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4055:
1.12 www 4056: my %returnhash=();
1.800 albertel 4057: foreach my $line (split(/\&/,$answer)) {
4058: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4059: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4060: }
1.75 www 4061: my $version;
4062: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4063: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4064: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4065: }
1.75 www 4066: }
1.13 www 4067: return %returnhash;
1.34 www 4068: }
4069:
4070: # ---------------------------------------------------------- Course Description
4071:
4072: sub coursedescription {
1.731 albertel 4073: my ($courseid,$args)=@_;
1.34 www 4074: $courseid=~s/^\///;
1.49 www 4075: $courseid=~s/\_/\//g;
1.34 www 4076: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4077: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4078: my $normalid=$cdomain.'_'.$cnum;
4079: # need to always cache even if we get errors otherwise we keep
4080: # trying and trying and trying to get the course description.
4081: my %envhash=();
4082: my %returnhash=();
1.731 albertel 4083:
4084: my $expiretime=600;
4085: if ($env{'request.course.id'} eq $normalid) {
4086: $expiretime=120;
4087: }
4088:
4089: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4090: if (!$args->{'freshen_cache'}
4091: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4092: foreach my $key (keys(%env)) {
4093: next if ($key !~ /^\Q$prefix\E(.*)/);
4094: my ($setting) = $1;
4095: $returnhash{$setting} = $env{$key};
4096: }
4097: return %returnhash;
4098: }
4099:
4100: # get the data agin
4101: if (!$args->{'one_time'}) {
4102: $envhash{'course.'.$normalid.'.last_cache'}=time;
4103: }
1.811 albertel 4104:
1.34 www 4105: if ($chome ne 'no_host') {
1.302 albertel 4106: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4107: if (!exists($returnhash{'con_lost'})) {
4108: $returnhash{'home'}= $chome;
4109: $returnhash{'domain'} = $cdomain;
4110: $returnhash{'num'} = $cnum;
1.741 raeburn 4111: if (!defined($returnhash{'type'})) {
4112: $returnhash{'type'} = 'Course';
4113: }
1.130 albertel 4114: while (my ($name,$value) = each %returnhash) {
1.53 www 4115: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4116: }
1.270 www 4117: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4118: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4119: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4120: $envhash{'course.'.$normalid.'.home'}=$chome;
4121: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4122: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4123: }
4124: }
1.731 albertel 4125: if (!$args->{'one_time'}) {
1.949 raeburn 4126: &appenv(\%envhash);
1.731 albertel 4127: }
1.302 albertel 4128: return %returnhash;
1.461 www 4129: }
4130:
1.1056.4.5 raeburn 4131: sub update_released_required {
4132: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4133: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4134: $cid = $env{'request.course.id'};
4135: $cdom = $env{'course.'.$cid.'.domain'};
4136: $cnum = $env{'course.'.$cid.'.num'};
4137: $chome = $env{'course.'.$cid.'.home'};
4138: }
4139: if ($needsrelease) {
4140: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4141: my $needsupdate;
4142: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4143: $needsupdate = 1;
4144: } else {
4145: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4146: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4147: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4148: $needsupdate = 1;
4149: }
4150: }
4151: if ($needsupdate) {
4152: my %needshash = (
4153: 'internal.releaserequired' => $needsrelease,
4154: );
4155: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4156: if ($putresult eq 'ok') {
4157: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4158: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4159: if (ref($crsinfo{$cid}) eq 'HASH') {
4160: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4161: &courseidput($cdom,\%crsinfo,$chome,'notime');
4162: }
4163: }
4164: }
4165: }
4166: return;
4167: }
4168:
1.461 www 4169: # -------------------------------------------------See if a user is privileged
4170:
4171: sub privileged {
4172: my ($username,$domain)=@_;
4173: my $rolesdump=&reply("dump:$domain:$username:roles",
4174: &homeserver($username,$domain));
1.1033 raeburn 4175: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4176: ($rolesdump =~ /^error:/)) {
4177: return 0;
4178: }
1.461 www 4179: my $now=time;
4180: if ($rolesdump ne '') {
1.800 albertel 4181: foreach my $entry (split(/&/,$rolesdump)) {
4182: if ($entry!~/^rolesdef_/) {
4183: my ($area,$role)=split(/=/,$entry);
1.461 www 4184: $area=~s/\_\w\w$//;
4185: my ($trole,$tend,$tstart)=split(/_/,$role);
4186: if (($trole eq 'dc') || ($trole eq 'su')) {
4187: my $active=1;
4188: if ($tend) {
4189: if ($tend<$now) { $active=0; }
4190: }
4191: if ($tstart) {
4192: if ($tstart>$now) { $active=0; }
4193: }
4194: if ($active) { return 1; }
4195: }
4196: }
4197: }
4198: }
4199: return 0;
1.9 www 4200: }
1.1 albertel 4201:
1.103 harris41 4202: # -------------------------------------------------------- Get user privileges
1.11 www 4203:
4204: sub rolesinit {
4205: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4206: my $now=time;
4207: my %userroles = ('user.login.time' => $now);
1.1056.4.10 raeburn 4208: my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3 raeburn 4209: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4210: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1056.4.3 raeburn 4211: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4212: return \%userroles;
4213: }
1.11 www 4214: my %allroles=();
1.678 raeburn 4215: my %allgroups=();
4216: my $group_privs;
1.11 www 4217:
4218: if ($rolesdump ne '') {
1.800 albertel 4219: foreach my $entry (split(/&/,$rolesdump)) {
4220: if ($entry!~/^rolesdef_/) {
4221: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4222: $area=~s/\_\w\w$//;
1.678 raeburn 4223: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4224: if ($role=~/^cr/) {
1.807 albertel 4225: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4226: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4227: ($tend,$tstart)=split('_',$trest);
4228: } else {
4229: $trole=$role;
4230: }
1.678 raeburn 4231: } elsif ($role =~ m|^gr/|) {
4232: ($trole,$tend,$tstart) = split(/_/,$role);
4233: ($trole,$group_privs) = split(/\//,$trole);
4234: $group_privs = &unescape($group_privs);
1.587 albertel 4235: } else {
4236: ($trole,$tend,$tstart)=split(/_/,$role);
4237: }
1.743 albertel 4238: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4239: $username);
4240: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4241: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4242: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4243: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4244: my $spec=$trole.'.'.$area;
4245: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4246: if ($trole =~ /^cr\//) {
1.567 raeburn 4247: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4248: } elsif ($trole eq 'gr') {
4249: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4250: } else {
1.567 raeburn 4251: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4252: }
1.12 www 4253: }
1.662 raeburn 4254: }
1.191 harris41 4255: }
1.743 albertel 4256: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4257: $userroles{'user.adv'} = $adv;
4258: $userroles{'user.author'} = $author;
1.620 albertel 4259: $env{'user.adv'}=$adv;
1.11 www 4260: }
1.743 albertel 4261: return \%userroles;
1.11 www 4262: }
4263:
1.567 raeburn 4264: sub set_arearole {
4265: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4266: # log the associated role with the area
4267: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4268: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4269: }
4270:
4271: sub custom_roleprivs {
4272: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4273: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4274: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4275: if (&hostname($homsvr) ne '') {
1.567 raeburn 4276: my ($rdummy,$roledef)=
4277: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4278: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4279: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4280: if (defined($syspriv)) {
1.1043 raeburn 4281: if ($trest =~ /^$match_community$/) {
4282: $syspriv =~ s/bre\&S//;
4283: }
1.567 raeburn 4284: $$allroles{'cm./'}.=':'.$syspriv;
4285: $$allroles{$spec.'./'}.=':'.$syspriv;
4286: }
4287: if ($tdomain ne '') {
4288: if (defined($dompriv)) {
4289: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4290: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4291: }
4292: if (($trest ne '') && (defined($coursepriv))) {
4293: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4294: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4295: }
4296: }
4297: }
4298: }
4299: }
4300:
1.678 raeburn 4301: sub group_roleprivs {
4302: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4303: my $access = 1;
4304: my $now = time;
4305: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4306: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4307: if ($access) {
1.811 albertel 4308: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4309: $$allgroups{$course}{$group} .=':'.$group_privs;
4310: }
4311: }
1.567 raeburn 4312:
4313: sub standard_roleprivs {
4314: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4315: if (defined($pr{$trole.':s'})) {
4316: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4317: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4318: }
4319: if ($tdomain ne '') {
4320: if (defined($pr{$trole.':d'})) {
4321: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4322: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4323: }
4324: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4325: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4326: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4327: }
4328: }
4329: }
4330:
4331: sub set_userprivs {
1.1056.4.2 raeburn 4332: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4333: my $author=0;
4334: my $adv=0;
1.678 raeburn 4335: my %grouproles = ();
4336: if (keys(%{$allgroups}) > 0) {
1.1056.4.2 raeburn 4337: my @groupkeys;
1.1000 raeburn 4338: foreach my $role (keys(%{$allroles})) {
1.1056.4.2 raeburn 4339: push(@groupkeys,$role);
4340: }
4341: if (ref($groups_roles) eq 'HASH') {
4342: foreach my $key (keys(%{$groups_roles})) {
4343: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4344: push(@groupkeys,$key);
4345: }
4346: }
4347: }
4348: if (@groupkeys > 0) {
4349: foreach my $role (@groupkeys) {
4350: my ($trole,$area,$sec,$extendedarea);
4351: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4352: $trole = $1;
4353: $area = $2;
4354: $sec = $3;
4355: $extendedarea = $area.$sec;
4356: if (exists($$allgroups{$area})) {
4357: foreach my $group (keys(%{$$allgroups{$area}})) {
4358: my $spec = $trole.'.'.$extendedarea;
4359: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4360: $$allgroups{$area}{$group};
1.1056.4.2 raeburn 4361: }
1.678 raeburn 4362: }
4363: }
4364: }
4365: }
4366: }
1.800 albertel 4367: foreach my $group (keys(%grouproles)) {
4368: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4369: }
1.800 albertel 4370: foreach my $role (keys(%{$allroles})) {
4371: my %thesepriv;
1.941 raeburn 4372: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4373: foreach my $item (split(/:/,$$allroles{$role})) {
4374: if ($item ne '') {
4375: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4376: if ($restrictions eq '') {
4377: $thesepriv{$privilege}='F';
4378: } elsif ($thesepriv{$privilege} ne 'F') {
4379: $thesepriv{$privilege}.=$restrictions;
4380: }
4381: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4382: }
4383: }
4384: my $thesestr='';
1.800 albertel 4385: foreach my $priv (keys(%thesepriv)) {
4386: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4387: }
4388: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4389: }
4390: return ($author,$adv);
4391: }
4392:
1.994 raeburn 4393: sub role_status {
1.1002 raeburn 4394: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4395: my @pwhere = ();
4396: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4397: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4398: unless (!defined($$role) || $$role eq '') {
4399: $$where=join('.',@pwhere);
4400: $$trolecode=$$role.'.'.$$where;
4401: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4402: $$tstatus='is';
4403: if ($$tstart && $$tstart>$then) {
4404: $$tstatus='future';
1.1034 raeburn 4405: if ($$tstart<$now) {
4406: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4407: if (($$where ne '') && ($$role ne '')) {
1.1056.4.2 raeburn 4408: my (%allroles,%allgroups,$group_privs,
4409: %groups_roles,@rolecodes);
1.1002 raeburn 4410: my %userroles = (
4411: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4412: );
1.1056.4.2 raeburn 4413: @rolecodes = ('cm');
1.1002 raeburn 4414: my $spec=$$role.'.'.$$where;
4415: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4416: if ($$role =~ /^cr\//) {
4417: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2 raeburn 4418: push(@rolecodes,'cr');
1.1002 raeburn 4419: } elsif ($$role eq 'gr') {
1.1056.4.2 raeburn 4420: push(@rolecodes,$$role);
1.1002 raeburn 4421: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4422: $env{'user.name'});
1.1056.4.2 raeburn 4423: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4424: (undef,my $group_privs) = split(/\//,$trole);
4425: $group_privs = &unescape($group_privs);
4426: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2 raeburn 4427: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4428: if (keys(%course_roles) > 0) {
4429: my ($tnum) = ($trest =~ /^($match_courseid)/);
4430: if ($tdomain ne '' && $tnum ne '') {
4431: foreach my $key (keys(%course_roles)) {
4432: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4433: my $crsrole = $1;
4434: my $crssec = $2;
4435: if ($crsrole =~ /^cr/) {
4436: unless (grep(/^cr$/,@rolecodes)) {
4437: push(@rolecodes,'cr');
4438: }
4439: } else {
4440: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4441: push(@rolecodes,$crsrole);
4442: }
4443: }
4444: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4445: if ($crssec ne '') {
4446: $rolekey .= '/'.$crssec;
4447: }
4448: $rolekey .= './';
4449: $groups_roles{$rolekey} = \@rolecodes;
4450: }
4451: }
4452: }
4453: }
1.1002 raeburn 4454: } else {
1.1056.4.2 raeburn 4455: push(@rolecodes,$$role);
1.1002 raeburn 4456: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4457: }
1.1056.4.2 raeburn 4458: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4459: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4460: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4461: }
4462: }
1.1034 raeburn 4463: $$tstatus = 'is';
1.1002 raeburn 4464: }
1.994 raeburn 4465: }
4466: if ($$tend) {
4467: if ($$tend<$then) {
4468: $$tstatus='expired';
4469: } elsif ($$tend<$now) {
4470: $$tstatus='will_not';
4471: }
4472: }
4473: }
4474: }
4475: }
4476:
4477: sub check_adhoc_privs {
1.1056.4.12 raeburn 4478: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4479: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4480: if ($env{$cckey}) {
4481: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4482: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4483: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12 raeburn 4484: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4485: }
4486: } else {
1.1056.4.12 raeburn 4487: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4488: }
4489: }
4490:
4491: sub set_adhoc_privileges {
4492: # role can be cc or ca
1.1056.4.12 raeburn 4493: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4494: my $area = '/'.$dcdom.'/'.$pickedcourse;
4495: my $spec = $role.'.'.$area;
4496: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4497: $env{'user.name'});
4498: my %ccrole = ();
4499: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4500: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4501: &appenv(\%userroles,[$role,'cm']);
4502: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12 raeburn 4503: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4504: &appenv( {'request.role' => $spec,
4505: 'request.role.domain' => $dcdom,
4506: 'request.course.sec' => ''
4507: }
4508: );
4509: my $tadv=0;
4510: if (&allowed('adv') eq 'F') { $tadv=1; }
4511: &appenv({'request.role.adv' => $tadv});
4512: }
1.994 raeburn 4513: }
4514:
1.12 www 4515: # --------------------------------------------------------------- get interface
4516:
4517: sub get {
1.131 albertel 4518: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4519: my $items='';
1.800 albertel 4520: foreach my $item (@$storearr) {
4521: $items.=&escape($item).'&';
1.191 harris41 4522: }
1.12 www 4523: $items=~s/\&$//;
1.620 albertel 4524: if (!$udomain) { $udomain=$env{'user.domain'}; }
4525: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4526: my $uhome=&homeserver($uname,$udomain);
4527:
1.133 albertel 4528: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4529: my @pairs=split(/\&/,$rep);
1.273 albertel 4530: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4531: return @pairs;
4532: }
1.15 www 4533: my %returnhash=();
1.42 www 4534: my $i=0;
1.800 albertel 4535: foreach my $item (@$storearr) {
4536: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4537: $i++;
1.191 harris41 4538: }
1.15 www 4539: return %returnhash;
1.27 www 4540: }
4541:
4542: # --------------------------------------------------------------- del interface
4543:
4544: sub del {
1.133 albertel 4545: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4546: my $items='';
1.800 albertel 4547: foreach my $item (@$storearr) {
4548: $items.=&escape($item).'&';
1.191 harris41 4549: }
1.984 neumanie 4550:
1.27 www 4551: $items=~s/\&$//;
1.620 albertel 4552: if (!$udomain) { $udomain=$env{'user.domain'}; }
4553: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4554: my $uhome=&homeserver($uname,$udomain);
4555: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4556: }
4557:
4558: # -------------------------------------------------------------- dump interface
4559:
4560: sub dump {
1.1056.4.10 raeburn 4561: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4562: if (!$udomain) { $udomain=$env{'user.domain'}; }
4563: if (!$uname) { $uname=$env{'user.name'}; }
4564: my $uhome=&homeserver($uname,$udomain);
4565: if ($regexp) {
4566: $regexp=&escape($regexp);
4567: } else {
4568: $regexp='.';
4569: }
1.1056.4.10 raeburn 4570: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4571: my @pairs=split(/\&/,$rep);
4572: my %returnhash=();
4573: foreach my $item (@pairs) {
4574: my ($key,$value)=split(/=/,$item,2);
4575: $key = &unescape($key);
4576: next if ($key =~ /^error: 2 /);
4577: $returnhash{$key}=&thaw_unescape($value);
4578: }
4579: return %returnhash;
1.407 www 4580: }
4581:
1.717 albertel 4582: # --------------------------------------------------------- dumpstore interface
4583:
4584: sub dumpstore {
4585: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4586: if (!$udomain) { $udomain=$env{'user.domain'}; }
4587: if (!$uname) { $uname=$env{'user.name'}; }
4588: my $uhome=&homeserver($uname,$udomain);
4589: if ($regexp) {
4590: $regexp=&escape($regexp);
4591: } else {
4592: $regexp='.';
4593: }
4594: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4595: my @pairs=split(/\&/,$rep);
4596: my %returnhash=();
4597: foreach my $item (@pairs) {
4598: my ($key,$value)=split(/=/,$item,2);
4599: next if ($key =~ /^error: 2 /);
4600: $returnhash{$key}=&thaw_unescape($value);
4601: }
4602: return %returnhash;
1.717 albertel 4603: }
4604:
1.407 www 4605: # -------------------------------------------------------------- keys interface
4606:
4607: sub getkeys {
4608: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4609: if (!$udomain) { $udomain=$env{'user.domain'}; }
4610: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4611: my $uhome=&homeserver($uname,$udomain);
4612: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4613: my @keyarray=();
1.800 albertel 4614: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4615: next if ($key =~ /^error: 2 /);
1.800 albertel 4616: push(@keyarray,&unescape($key));
1.407 www 4617: }
4618: return @keyarray;
1.318 matthew 4619: }
4620:
1.319 matthew 4621: # --------------------------------------------------------------- currentdump
4622: sub currentdump {
1.328 matthew 4623: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4624: $courseid = $env{'request.course.id'} if (! defined($courseid));
4625: $sdom = $env{'user.domain'} if (! defined($sdom));
4626: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4627: my $uhome = &homeserver($sname,$sdom);
4628: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4629: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4630: #
1.318 matthew 4631: my %returnhash=();
1.319 matthew 4632: #
4633: if ($rep eq "unknown_cmd") {
4634: # an old lond will not know currentdump
4635: # Do a dump and make it look like a currentdump
1.822 albertel 4636: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4637: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4638: my %hash = @tmp;
4639: @tmp=();
1.424 matthew 4640: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4641: } else {
4642: my @pairs=split(/\&/,$rep);
1.800 albertel 4643: foreach my $pair (@pairs) {
4644: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4645: my ($symb,$param) = split(/:/,$key);
4646: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4647: &thaw_unescape($value);
1.319 matthew 4648: }
1.191 harris41 4649: }
1.12 www 4650: return %returnhash;
1.424 matthew 4651: }
4652:
4653: sub convert_dump_to_currentdump{
4654: my %hash = %{shift()};
4655: my %returnhash;
4656: # Code ripped from lond, essentially. The only difference
4657: # here is the unescaping done by lonnet::dump(). Conceivably
4658: # we might run in to problems with parameter names =~ /^v\./
4659: while (my ($key,$value) = each(%hash)) {
4660: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4661: $symb = &unescape($symb);
4662: $param = &unescape($param);
1.424 matthew 4663: next if ($v eq 'version' || $symb eq 'keys');
4664: next if (exists($returnhash{$symb}) &&
4665: exists($returnhash{$symb}->{$param}) &&
4666: $returnhash{$symb}->{'v.'.$param} > $v);
4667: $returnhash{$symb}->{$param}=$value;
4668: $returnhash{$symb}->{'v.'.$param}=$v;
4669: }
4670: #
4671: # Remove all of the keys in the hashes which keep track of
4672: # the version of the parameter.
4673: while (my ($symb,$param_hash) = each(%returnhash)) {
4674: # use a foreach because we are going to delete from the hash.
4675: foreach my $key (keys(%$param_hash)) {
4676: delete($param_hash->{$key}) if ($key =~ /^v\./);
4677: }
4678: }
4679: return \%returnhash;
1.12 www 4680: }
4681:
1.627 albertel 4682: # ------------------------------------------------------ critical inc interface
4683:
4684: sub cinc {
4685: return &inc(@_,'critical');
4686: }
4687:
1.449 matthew 4688: # --------------------------------------------------------------- inc interface
4689:
4690: sub inc {
1.627 albertel 4691: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4692: if (!$udomain) { $udomain=$env{'user.domain'}; }
4693: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4694: my $uhome=&homeserver($uname,$udomain);
4695: my $items='';
4696: if (! ref($store)) {
4697: # got a single value, so use that instead
4698: $items = &escape($store).'=&';
4699: } elsif (ref($store) eq 'SCALAR') {
4700: $items = &escape($$store).'=&';
4701: } elsif (ref($store) eq 'ARRAY') {
4702: $items = join('=&',map {&escape($_);} @{$store});
4703: } elsif (ref($store) eq 'HASH') {
4704: while (my($key,$value) = each(%{$store})) {
4705: $items.= &escape($key).'='.&escape($value).'&';
4706: }
4707: }
4708: $items=~s/\&$//;
1.627 albertel 4709: if ($critical) {
4710: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4711: } else {
4712: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4713: }
1.449 matthew 4714: }
4715:
1.12 www 4716: # --------------------------------------------------------------- put interface
4717:
4718: sub put {
1.134 albertel 4719: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4720: if (!$udomain) { $udomain=$env{'user.domain'}; }
4721: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4722: my $uhome=&homeserver($uname,$udomain);
1.12 www 4723: my $items='';
1.800 albertel 4724: foreach my $item (keys(%$storehash)) {
4725: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4726: }
1.12 www 4727: $items=~s/\&$//;
1.134 albertel 4728: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4729: }
4730:
1.631 albertel 4731: # ------------------------------------------------------------ newput interface
4732:
4733: sub newput {
4734: my ($namespace,$storehash,$udomain,$uname)=@_;
4735: if (!$udomain) { $udomain=$env{'user.domain'}; }
4736: if (!$uname) { $uname=$env{'user.name'}; }
4737: my $uhome=&homeserver($uname,$udomain);
4738: my $items='';
4739: foreach my $key (keys(%$storehash)) {
4740: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4741: }
4742: $items=~s/\&$//;
4743: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4744: }
4745:
4746: # --------------------------------------------------------- putstore interface
4747:
1.524 raeburn 4748: sub putstore {
1.715 albertel 4749: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4750: if (!$udomain) { $udomain=$env{'user.domain'}; }
4751: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4752: my $uhome=&homeserver($uname,$udomain);
4753: my $items='';
1.715 albertel 4754: foreach my $key (keys(%$storehash)) {
4755: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4756: }
1.715 albertel 4757: $items=~s/\&$//;
1.716 albertel 4758: my $esc_symb=&escape($symb);
4759: my $esc_v=&escape($version);
1.715 albertel 4760: my $reply =
1.716 albertel 4761: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4762: $uhome);
4763: if ($reply eq 'unknown_cmd') {
1.716 albertel 4764: # gfall back to way things use to be done
1.715 albertel 4765: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4766: $uname);
1.524 raeburn 4767: }
1.715 albertel 4768: return $reply;
4769: }
4770:
4771: sub old_putstore {
1.716 albertel 4772: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4773: if (!$udomain) { $udomain=$env{'user.domain'}; }
4774: if (!$uname) { $uname=$env{'user.name'}; }
4775: my $uhome=&homeserver($uname,$udomain);
4776: my %newstorehash;
1.800 albertel 4777: foreach my $item (keys(%$storehash)) {
4778: my $key = $version.':'.&escape($symb).':'.$item;
4779: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4780: }
4781: my $items='';
4782: my %allitems = ();
1.800 albertel 4783: foreach my $item (keys(%newstorehash)) {
4784: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4785: my $key = $1.':keys:'.$2;
4786: $allitems{$key} .= $3.':';
4787: }
1.800 albertel 4788: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4789: }
1.800 albertel 4790: foreach my $item (keys(%allitems)) {
4791: $allitems{$item} =~ s/\:$//;
4792: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4793: }
4794: $items=~s/\&$//;
4795: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4796: }
4797:
1.47 www 4798: # ------------------------------------------------------ critical put interface
4799:
4800: sub cput {
1.134 albertel 4801: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4802: if (!$udomain) { $udomain=$env{'user.domain'}; }
4803: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4804: my $uhome=&homeserver($uname,$udomain);
1.47 www 4805: my $items='';
1.800 albertel 4806: foreach my $item (keys(%$storehash)) {
4807: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4808: }
1.47 www 4809: $items=~s/\&$//;
1.134 albertel 4810: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4811: }
4812:
4813: # -------------------------------------------------------------- eget interface
4814:
4815: sub eget {
1.133 albertel 4816: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4817: my $items='';
1.800 albertel 4818: foreach my $item (@$storearr) {
4819: $items.=&escape($item).'&';
1.191 harris41 4820: }
1.12 www 4821: $items=~s/\&$//;
1.620 albertel 4822: if (!$udomain) { $udomain=$env{'user.domain'}; }
4823: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4824: my $uhome=&homeserver($uname,$udomain);
4825: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4826: my @pairs=split(/\&/,$rep);
4827: my %returnhash=();
1.42 www 4828: my $i=0;
1.800 albertel 4829: foreach my $item (@$storearr) {
4830: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4831: $i++;
1.191 harris41 4832: }
1.12 www 4833: return %returnhash;
4834: }
4835:
1.667 albertel 4836: # ------------------------------------------------------------ tmpput interface
4837: sub tmpput {
1.802 raeburn 4838: my ($storehash,$server,$context)=@_;
1.667 albertel 4839: my $items='';
1.800 albertel 4840: foreach my $item (keys(%$storehash)) {
4841: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4842: }
4843: $items=~s/\&$//;
1.802 raeburn 4844: if (defined($context)) {
4845: $items .= ':'.&escape($context);
4846: }
1.667 albertel 4847: return &reply("tmpput:$items",$server);
4848: }
4849:
4850: # ------------------------------------------------------------ tmpget interface
4851: sub tmpget {
1.688 albertel 4852: my ($token,$server)=@_;
4853: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4854: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4855: my %returnhash;
4856: foreach my $item (split(/\&/,$rep)) {
4857: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4858: next if ($key =~ /^error: 2 /);
1.667 albertel 4859: $returnhash{&unescape($key)}=&thaw_unescape($value);
4860: }
4861: return %returnhash;
4862: }
4863:
1.688 albertel 4864: # ------------------------------------------------------------ tmpget interface
4865: sub tmpdel {
4866: my ($token,$server)=@_;
4867: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4868: return &reply("tmpdel:$token",$server);
4869: }
4870:
1.765 albertel 4871: # -------------------------------------------------- portfolio access checking
4872:
4873: sub portfolio_access {
1.766 albertel 4874: my ($requrl) = @_;
1.765 albertel 4875: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4876: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4877: if ($result) {
4878: my %setters;
4879: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4880: my ($startblock,$endblock) =
4881: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4882: if ($startblock && $endblock) {
4883: return 'B';
4884: }
4885: } else {
4886: my ($startblock,$endblock) =
4887: &Apache::loncommon::blockcheck(\%setters,'port');
4888: if ($startblock && $endblock) {
4889: return 'B';
4890: }
4891: }
4892: }
1.765 albertel 4893: if ($result eq 'ok') {
1.766 albertel 4894: return 'F';
1.765 albertel 4895: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4896: return 'A';
1.765 albertel 4897: }
1.766 albertel 4898: return '';
1.765 albertel 4899: }
4900:
4901: sub get_portfolio_access {
1.767 albertel 4902: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4903:
4904: if (!ref($access_hash)) {
4905: my $current_perms = &get_portfile_permissions($udom,$unum);
4906: my %access_controls = &get_access_controls($current_perms,$group,
4907: $file_name);
4908: $access_hash = $access_controls{$file_name};
4909: }
4910:
1.765 albertel 4911: my ($public,$guest,@domains,@users,@courses,@groups);
4912: my $now = time;
4913: if (ref($access_hash) eq 'HASH') {
4914: foreach my $key (keys(%{$access_hash})) {
4915: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4916: if ($start > $now) {
4917: next;
4918: }
4919: if ($end && $end<$now) {
4920: next;
4921: }
4922: if ($scope eq 'public') {
4923: $public = $key;
4924: last;
4925: } elsif ($scope eq 'guest') {
4926: $guest = $key;
4927: } elsif ($scope eq 'domains') {
4928: push(@domains,$key);
4929: } elsif ($scope eq 'users') {
4930: push(@users,$key);
4931: } elsif ($scope eq 'course') {
4932: push(@courses,$key);
4933: } elsif ($scope eq 'group') {
4934: push(@groups,$key);
4935: }
4936: }
4937: if ($public) {
4938: return 'ok';
4939: }
4940: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4941: if ($guest) {
4942: return $guest;
4943: }
4944: } else {
4945: if (@domains > 0) {
4946: foreach my $domkey (@domains) {
4947: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4948: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4949: return 'ok';
4950: }
4951: }
4952: }
4953: }
4954: if (@users > 0) {
4955: foreach my $userkey (@users) {
1.865 raeburn 4956: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4957: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4958: if (ref($item) eq 'HASH') {
4959: if (($item->{'uname'} eq $env{'user.name'}) &&
4960: ($item->{'udom'} eq $env{'user.domain'})) {
4961: return 'ok';
4962: }
4963: }
4964: }
4965: }
1.765 albertel 4966: }
4967: }
4968: my %roleshash;
4969: my @courses_and_groups = @courses;
4970: push(@courses_and_groups,@groups);
4971: if (@courses_and_groups > 0) {
4972: my (%allgroups,%allroles);
4973: my ($start,$end,$role,$sec,$group);
4974: foreach my $envkey (%env) {
1.1056.4.1 raeburn 4975: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4976: my $cid = $2.'_'.$3;
4977: if ($1 eq 'gr') {
4978: $group = $4;
4979: $allgroups{$cid}{$group} = $env{$envkey};
4980: } else {
4981: if ($4 eq '') {
4982: $sec = 'none';
4983: } else {
4984: $sec = $4;
4985: }
4986: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4987: }
1.811 albertel 4988: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4989: my $cid = $2.'_'.$3;
4990: if ($4 eq '') {
4991: $sec = 'none';
4992: } else {
4993: $sec = $4;
4994: }
4995: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4996: }
4997: }
4998: if (keys(%allroles) == 0) {
4999: return;
5000: }
5001: foreach my $key (@courses_and_groups) {
5002: my %content = %{$$access_hash{$key}};
5003: my $cnum = $content{'number'};
5004: my $cdom = $content{'domain'};
5005: my $cid = $cdom.'_'.$cnum;
5006: if (!exists($allroles{$cid})) {
5007: next;
5008: }
5009: foreach my $role_id (keys(%{$content{'roles'}})) {
5010: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5011: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5012: my @status = @{$content{'roles'}{$role_id}{'access'}};
5013: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5014: foreach my $role (keys(%{$allroles{$cid}})) {
5015: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5016: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5017: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5018: if (grep/^all$/,@sections) {
5019: return 'ok';
5020: } else {
5021: if (grep/^$sec$/,@sections) {
5022: return 'ok';
5023: }
5024: }
5025: }
5026: }
5027: if (keys(%{$allgroups{$cid}}) == 0) {
5028: if (grep/^none$/,@groups) {
5029: return 'ok';
5030: }
5031: } else {
5032: if (grep/^all$/,@groups) {
5033: return 'ok';
5034: }
5035: foreach my $group (keys(%{$allgroups{$cid}})) {
5036: if (grep/^$group$/,@groups) {
5037: return 'ok';
5038: }
5039: }
5040: }
5041: }
5042: }
5043: }
5044: }
5045: }
5046: if ($guest) {
5047: return $guest;
5048: }
5049: }
5050: }
5051: return;
5052: }
5053:
5054: sub course_group_datechecker {
5055: my ($dates,$now,$status) = @_;
5056: my ($start,$end) = split(/\./,$dates);
5057: if (!$start && !$end) {
5058: return 'ok';
5059: }
5060: if (grep/^active$/,@{$status}) {
5061: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5062: return 'ok';
5063: }
5064: }
5065: if (grep/^previous$/,@{$status}) {
5066: if ($end > $now ) {
5067: return 'ok';
5068: }
5069: }
5070: if (grep/^future$/,@{$status}) {
5071: if ($start > $now) {
5072: return 'ok';
5073: }
5074: }
5075: return;
5076: }
5077:
5078: sub parse_portfolio_url {
5079: my ($url) = @_;
5080:
5081: my ($type,$udom,$unum,$group,$file_name);
5082:
1.823 albertel 5083: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5084: $type = 1;
5085: $udom = $1;
5086: $unum = $2;
5087: $file_name = $3;
1.823 albertel 5088: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5089: $type = 2;
5090: $udom = $1;
5091: $unum = $2;
5092: $group = $3;
5093: $file_name = $3.'/'.$4;
5094: }
5095: if (wantarray) {
5096: return ($type,$udom,$unum,$file_name,$group);
5097: }
5098: return $type;
5099: }
5100:
5101: sub is_portfolio_url {
5102: my ($url) = @_;
5103: return scalar(&parse_portfolio_url($url));
5104: }
5105:
1.798 raeburn 5106: sub is_portfolio_file {
5107: my ($file) = @_;
1.820 raeburn 5108: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5109: return 1;
5110: }
5111: return;
5112: }
5113:
1.976 raeburn 5114: sub usertools_access {
1.1056.4.9 raeburn 5115: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985 raeburn 5116: my ($access,%tools);
5117: if ($context eq '') {
5118: $context = 'tools';
5119: }
5120: if ($context eq 'requestcourses') {
5121: %tools = (
5122: official => 1,
5123: unofficial => 1,
1.1006 raeburn 5124: community => 1,
1.985 raeburn 5125: );
5126: } else {
5127: %tools = (
5128: aboutme => 1,
5129: blog => 1,
5130: portfolio => 1,
5131: );
5132: }
1.976 raeburn 5133: return if (!defined($tools{$tool}));
5134:
5135: if ((!defined($udom)) || (!defined($uname))) {
5136: $udom = $env{'user.domain'};
5137: $uname = $env{'user.name'};
5138: }
5139:
1.978 raeburn 5140: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5141: if ($action ne 'reload') {
1.985 raeburn 5142: if ($context eq 'requestcourses') {
5143: return $env{'environment.canrequest.'.$tool};
5144: } else {
5145: return $env{'environment.availabletools.'.$tool};
5146: }
5147: }
1.976 raeburn 5148: }
5149:
5150: my ($toolstatus,$inststatus);
5151:
1.985 raeburn 5152: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5153: ($action ne 'reload')) {
5154: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5155: $inststatus = $env{'environment.inststatus'};
5156: } else {
1.1056.4.9 raeburn 5157: if (ref($userenvref) eq 'HASH') {
5158: $toolstatus = $userenvref->{$context.'.'.$tool};
5159: $inststatus = $userenvref->{'inststatus'};
5160: } else {
5161: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5162: $toolstatus = $userenv{$context.'.'.$tool};
5163: $inststatus = $userenv{'inststatus'};
5164: }
1.976 raeburn 5165: }
5166:
5167: if ($toolstatus ne '') {
5168: if ($toolstatus) {
5169: $access = 1;
5170: } else {
5171: $access = 0;
5172: }
5173: return $access;
5174: }
5175:
1.1056.4.9 raeburn 5176: my ($is_adv,%domdef);
5177: if (ref($is_advref) eq 'HASH') {
5178: $is_adv = $is_advref->{'is_adv'};
5179: } else {
5180: $is_adv = &is_advanced_user($udom,$uname);
5181: }
5182: if (ref($domdefref) eq 'HASH') {
5183: %domdef = %{$domdefref};
5184: } else {
5185: %domdef = &get_domain_defaults($udom);
5186: }
1.976 raeburn 5187: if (ref($domdef{$tool}) eq 'HASH') {
5188: if ($is_adv) {
5189: if ($domdef{$tool}{'_LC_adv'} ne '') {
5190: if ($domdef{$tool}{'_LC_adv'}) {
5191: $access = 1;
5192: } else {
5193: $access = 0;
5194: }
5195: return $access;
5196: }
5197: }
5198: if ($inststatus ne '') {
5199: my ($hasaccess,$hasnoaccess);
5200: foreach my $affiliation (split(/:/,$inststatus)) {
5201: if ($domdef{$tool}{$affiliation} ne '') {
5202: if ($domdef{$tool}{$affiliation}) {
5203: $hasaccess = 1;
5204: } else {
5205: $hasnoaccess = 1;
5206: }
5207: }
5208: }
5209: if ($hasaccess || $hasnoaccess) {
5210: if ($hasaccess) {
5211: $access = 1;
5212: } elsif ($hasnoaccess) {
5213: $access = 0;
5214: }
5215: return $access;
5216: }
5217: } else {
5218: if ($domdef{$tool}{'default'} ne '') {
5219: if ($domdef{$tool}{'default'}) {
5220: $access = 1;
5221: } elsif ($domdef{$tool}{'default'} == 0) {
5222: $access = 0;
5223: }
5224: return $access;
5225: }
5226: }
5227: } else {
1.985 raeburn 5228: if ($context eq 'tools') {
5229: $access = 1;
5230: } else {
5231: $access = 0;
5232: }
1.976 raeburn 5233: return $access;
5234: }
5235: }
5236:
1.1050 raeburn 5237: sub is_course_owner {
5238: my ($cdom,$cnum,$udom,$uname) = @_;
5239: if (($udom eq '') || ($uname eq '')) {
5240: $udom = $env{'user.domain'};
5241: $uname = $env{'user.name'};
5242: }
5243: unless (($udom eq '') || ($uname eq '')) {
5244: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5245: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5246: return 1;
5247: } else {
5248: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5249: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5250: return 1;
5251: }
5252: }
5253: }
5254: }
5255: return;
5256: }
5257:
1.976 raeburn 5258: sub is_advanced_user {
5259: my ($udom,$uname) = @_;
1.1056.4.10 raeburn 5260: if ($udom ne '' && $uname ne '') {
5261: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5262: return $env{'user.adv'};
5263: }
5264: }
1.976 raeburn 5265: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5266: my %allroles;
5267: my $is_adv;
5268: foreach my $role (keys(%roleshash)) {
5269: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5270: my $area = '/'.$tdomain.'/'.$trest;
5271: if ($sec ne '') {
5272: $area .= '/'.$sec;
5273: }
5274: if (($area ne '') && ($trole ne '')) {
5275: my $spec=$trole.'.'.$area;
5276: if ($trole =~ /^cr\//) {
5277: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5278: } elsif ($trole ne 'gr') {
5279: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5280: }
5281: }
5282: }
5283: foreach my $role (keys(%allroles)) {
5284: last if ($is_adv);
5285: foreach my $item (split(/:/,$allroles{$role})) {
5286: if ($item ne '') {
5287: my ($privilege,$restrictions)=split(/&/,$item);
5288: if ($privilege eq 'adv') {
5289: $is_adv = 1;
5290: last;
5291: }
5292: }
5293: }
5294: }
5295: return $is_adv;
5296: }
1.798 raeburn 5297:
1.1035 raeburn 5298: sub check_can_request {
1.1036 raeburn 5299: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5300: my $canreq = 0;
5301: my ($types,$typename) = &Apache::loncommon::course_types();
5302: my @options = ('approval','validate','autolimit');
5303: my $optregex = join('|',@options);
5304: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5305: foreach my $type (@{$types}) {
5306: if (&usertools_access($env{'user.name'},
5307: $env{'user.domain'},
5308: $type,undef,'requestcourses')) {
5309: $canreq ++;
1.1036 raeburn 5310: if (ref($request_domains) eq 'HASH') {
5311: push(@{$request_domains->{$type}},$env{'user.domain'});
5312: }
1.1035 raeburn 5313: if ($dom eq $env{'user.domain'}) {
5314: $can_request->{$type} = 1;
5315: }
5316: }
5317: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5318: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5319: if (@curr > 0) {
1.1036 raeburn 5320: foreach my $item (@curr) {
5321: if (ref($request_domains) eq 'HASH') {
5322: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5323: if ($otherdom ne '') {
5324: if (ref($request_domains->{$type}) eq 'ARRAY') {
5325: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5326: push(@{$request_domains->{$type}},$otherdom);
5327: }
5328: } else {
5329: push(@{$request_domains->{$type}},$otherdom);
5330: }
5331: }
5332: }
5333: }
5334: unless($dom eq $env{'user.domain'}) {
5335: $canreq ++;
1.1035 raeburn 5336: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5337: $can_request->{$type} = 1;
5338: }
5339: }
5340: }
5341: }
5342: }
5343: }
5344: return $canreq;
5345: }
5346:
1.341 www 5347: # ---------------------------------------------- Custom access rule evaluation
5348:
5349: sub customaccess {
5350: my ($priv,$uri)=@_;
1.807 albertel 5351: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5352: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5353: $udom = &LONCAPA::clean_domain($udom);
5354: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5355: my $access=0;
1.800 albertel 5356: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5357: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5358: if ($type eq 'user') {
5359: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5360: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5361: if ($tdom) {
5362: if ($tdom ne $env{'user.domain'}) { next; }
5363: }
1.896 albertel 5364: if ($tuname) {
5365: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5366: }
5367: $access=($effect eq 'allow');
5368: last;
5369: }
5370: } else {
5371: if ($role) {
5372: if ($role ne $urole) { next; }
5373: }
5374: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5375: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5376: if ($tdom) {
5377: if ($tdom ne $udom) { next; }
5378: }
5379: if ($tcrs) {
5380: if ($tcrs ne $ucrs) { next; }
5381: }
5382: if ($tsec) {
5383: if ($tsec ne $usec) { next; }
5384: }
5385: $access=($effect eq 'allow');
5386: last;
5387: }
5388: if ($realm eq '' && $role eq '') {
5389: $access=($effect eq 'allow');
5390: }
1.402 bowersj2 5391: }
1.341 www 5392: }
5393: return $access;
5394: }
5395:
1.103 harris41 5396: # ------------------------------------------------- Check for a user privilege
1.12 www 5397:
5398: sub allowed {
1.810 raeburn 5399: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5400: my $ver_orguri=$uri;
1.439 www 5401: $uri=&deversion($uri);
1.152 www 5402: my $orguri=$uri;
1.52 www 5403: $uri=&declutter($uri);
1.809 raeburn 5404:
1.810 raeburn 5405: if ($priv eq 'evb') {
5406: # Evade communication block restrictions for specified role in a course
5407: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5408: return $1;
5409: } else {
5410: return;
5411: }
5412: }
5413:
1.620 albertel 5414: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5415: # Free bre access to adm and meta resources
1.775 albertel 5416: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5417: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5418: && ($priv eq 'bre')) {
1.14 www 5419: return 'F';
1.159 www 5420: }
5421:
1.545 banghart 5422: # Free bre access to user's own portfolio contents
1.714 raeburn 5423: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5424: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5425: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5426: my %setters;
5427: my ($startblock,$endblock) =
5428: &Apache::loncommon::blockcheck(\%setters,'port');
5429: if ($startblock && $endblock) {
5430: return 'B';
5431: } else {
5432: return 'F';
5433: }
1.545 banghart 5434: }
5435:
1.762 raeburn 5436: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5437: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5438: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5439: if (exists($env{'request.course.id'})) {
5440: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5441: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5442: if (($domain eq $cdom) && ($name eq $cnum)) {
5443: my $courseprivid=$env{'request.course.id'};
5444: $courseprivid=~s/\_/\//;
5445: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5446: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5447: return $1;
1.762 raeburn 5448: } else {
5449: if ($env{'request.course.sec'}) {
5450: $courseprivid.='/'.$env{'request.course.sec'};
5451: }
5452: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5453: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5454: return $2;
5455: }
1.714 raeburn 5456: }
5457: }
5458: }
5459: }
5460:
1.159 www 5461: # Free bre to public access
5462:
5463: if ($priv eq 'bre') {
1.238 www 5464: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5465: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5466: return 'F';
5467: }
1.238 www 5468: if ($copyright eq 'priv') {
5469: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5470: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5471: return '';
5472: }
5473: }
5474: if ($copyright eq 'domain') {
5475: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5476: unless (($env{'user.domain'} eq $1) ||
5477: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5478: return '';
5479: }
1.262 matthew 5480: }
1.620 albertel 5481: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5482: # Library role, so allow browsing of resources in this domain.
5483: return 'F';
1.238 www 5484: }
1.341 www 5485: if ($copyright eq 'custom') {
5486: unless (&customaccess($priv,$uri)) { return ''; }
5487: }
1.14 www 5488: }
1.264 matthew 5489: # Domain coordinator is trying to create a course
1.620 albertel 5490: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5491: # uri is the requested domain in this case.
5492: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5493: # a role of dc for the domain in question.
1.620 albertel 5494: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5495: }
1.29 www 5496:
1.52 www 5497: my $thisallowed='';
5498: my $statecond=0;
5499: my $courseprivid='';
5500:
1.1039 raeburn 5501: my $ownaccess;
1.1043 raeburn 5502: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5503: if (($priv eq 'bro') && ($env{'user.author'})) {
5504: if ($uri eq '') {
5505: $ownaccess = 1;
5506: } else {
5507: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5508: my $udom = $env{'user.domain'};
5509: my $uname = $env{'user.name'};
5510: if ($uri =~ m{^\Q$udom\E/?$}) {
5511: $ownaccess = 1;
1.1040 raeburn 5512: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5513: unless ($uri =~ m{\.\./}) {
5514: $ownaccess = 1;
5515: }
5516: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5517: my $now = time;
5518: if ($uri =~ m{^([^/]+)/?$}) {
5519: my $adom = $1;
5520: foreach my $key (keys(%env)) {
1.1042 raeburn 5521: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5522: my ($start,$end) = split('.',$env{$key});
5523: if (($now >= $start) && (!$end || $end < $now)) {
5524: $ownaccess = 1;
5525: last;
5526: }
5527: }
5528: }
5529: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5530: my $adom = $1;
5531: my $aname = $2;
1.1042 raeburn 5532: foreach my $role ('ca','aa') {
5533: if ($env{"user.role.$role./$adom/$aname"}) {
5534: my ($start,$end) =
5535: split('.',$env{"user.role.$role./$adom/$aname"});
5536: if (($now >= $start) && (!$end || $end < $now)) {
5537: $ownaccess = 1;
5538: last;
5539: }
1.1039 raeburn 5540: }
5541: }
5542: }
5543: }
5544: }
5545: }
5546: }
5547:
1.52 www 5548: # Course
5549:
1.620 albertel 5550: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5551: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5552: $thisallowed.=$1;
5553: }
1.52 www 5554: }
1.29 www 5555:
1.52 www 5556: # Domain
5557:
1.620 albertel 5558: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5559: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5560: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5561: $thisallowed.=$1;
5562: }
1.12 www 5563: }
1.52 www 5564:
5565: # Course: uri itself is a course
1.66 www 5566: my $courseuri=$uri;
5567: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5568: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5569:
1.620 albertel 5570: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5571: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5572: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5573: $thisallowed.=$1;
5574: }
1.12 www 5575: }
1.29 www 5576:
1.665 albertel 5577: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5578: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5579: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5580: $thisallowed='';
1.671 raeburn 5581: my ($match)=&is_on_map($uri);
5582: if ($match) {
5583: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5584: =~/\Q$priv\E\&([^\:]*)/) {
5585: $thisallowed.=$1;
5586: }
5587: } else {
1.705 albertel 5588: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5589: if ($refuri) {
5590: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5591: $thisallowed='F';
1.671 raeburn 5592: } else {
5593: $refuri=&declutter($refuri);
5594: my ($match) = &is_on_map($refuri);
5595: if ($match) {
5596: $thisallowed='F';
5597: }
1.669 raeburn 5598: }
1.671 raeburn 5599: }
5600: }
1.314 www 5601: }
1.492 albertel 5602:
1.766 albertel 5603: if ($priv eq 'bre'
5604: && $thisallowed ne 'F'
5605: && $thisallowed ne '2'
5606: && &is_portfolio_url($uri)) {
5607: $thisallowed = &portfolio_access($uri);
5608: }
5609:
1.52 www 5610: # Full access at system, domain or course-wide level? Exit.
1.29 www 5611: if ($thisallowed=~/F/) {
5612: return 'F';
5613: }
5614:
1.52 www 5615: # If this is generating or modifying users, exit with special codes
1.29 www 5616:
1.643 www 5617: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5618: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5619: my ($audom,$auname)=split('/',$uri);
1.643 www 5620: # no author name given, so this just checks on the general right to make a co-author in this domain
5621: unless ($auname) { return $thisallowed; }
5622: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5623: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5624: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5625: ($audom ne $env{'request.role.domain'}))) { return ''; }
5626: }
1.52 www 5627: return $thisallowed;
5628: }
5629: #
1.103 harris41 5630: # Gathered so far: system, domain and course wide privileges
1.52 www 5631: #
5632: # Course: See if uri or referer is an individual resource that is part of
5633: # the course
5634:
1.620 albertel 5635: if ($env{'request.course.id'}) {
1.232 www 5636:
1.620 albertel 5637: $courseprivid=$env{'request.course.id'};
5638: if ($env{'request.course.sec'}) {
5639: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5640: }
5641: $courseprivid=~s/\_/\//;
5642: my $checkreferer=1;
1.232 www 5643: my ($match,$cond)=&is_on_map($uri);
5644: if ($match) {
5645: $statecond=$cond;
1.620 albertel 5646: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5647: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5648: $thisallowed.=$1;
5649: $checkreferer=0;
5650: }
1.29 www 5651: }
1.83 www 5652:
1.148 www 5653: if ($checkreferer) {
1.620 albertel 5654: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5655: unless ($refuri) {
1.800 albertel 5656: foreach my $key (keys(%env)) {
5657: if ($key=~/^httpref\..*\*/) {
5658: my $pattern=$key;
1.156 www 5659: $pattern=~s/^httpref\.\/res\///;
1.148 www 5660: $pattern=~s/\*/\[\^\/\]\+/g;
5661: $pattern=~s/\//\\\//g;
1.152 www 5662: if ($orguri=~/$pattern/) {
1.800 albertel 5663: $refuri=$env{$key};
1.148 www 5664: }
5665: }
1.191 harris41 5666: }
1.148 www 5667: }
1.232 www 5668:
1.148 www 5669: if ($refuri) {
1.152 www 5670: $refuri=&declutter($refuri);
1.232 www 5671: my ($match,$cond)=&is_on_map($refuri);
5672: if ($match) {
5673: my $refstatecond=$cond;
1.620 albertel 5674: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5675: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5676: $thisallowed.=$1;
1.53 www 5677: $uri=$refuri;
5678: $statecond=$refstatecond;
1.52 www 5679: }
5680: }
1.148 www 5681: }
1.29 www 5682: }
1.52 www 5683: }
1.29 www 5684:
1.52 www 5685: #
1.103 harris41 5686: # Gathered now: all privileges that could apply, and condition number
1.52 www 5687: #
5688: #
5689: # Full or no access?
5690: #
1.29 www 5691:
1.52 www 5692: if ($thisallowed=~/F/) {
5693: return 'F';
5694: }
1.29 www 5695:
1.52 www 5696: unless ($thisallowed) {
5697: return '';
5698: }
1.29 www 5699:
1.52 www 5700: # Restrictions exist, deal with them
5701: #
5702: # C:according to course preferences
5703: # R:according to resource settings
5704: # L:unless locked
5705: # X:according to user session state
5706: #
5707:
5708: # Possibly locked functionality, check all courses
1.54 www 5709: # Locks might take effect only after 10 minutes cache expiration for other
5710: # courses, and 2 minutes for current course
1.52 www 5711:
5712: my $envkey;
5713: if ($thisallowed=~/L/) {
1.1000 raeburn 5714: foreach $envkey (keys(%env)) {
1.54 www 5715: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5716: my $courseid=$2;
5717: my $roleid=$1.'.'.$2;
1.92 www 5718: $courseid=~s/^\///;
1.54 www 5719: my $expiretime=600;
1.620 albertel 5720: if ($env{'request.role'} eq $roleid) {
1.54 www 5721: $expiretime=120;
5722: }
5723: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5724: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5725: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5726: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5727: }
1.620 albertel 5728: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5729: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5730: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5731: &log($env{'user.domain'},$env{'user.name'},
5732: $env{'user.home'},
1.57 www 5733: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5734: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5735: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5736: return '';
5737: }
5738: }
1.620 albertel 5739: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5740: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5741: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5742: &log($env{'user.domain'},$env{'user.name'},
5743: $env{'user.home'},
1.57 www 5744: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5745: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5746: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5747: return '';
5748: }
5749: }
5750: }
1.29 www 5751: }
1.52 www 5752: }
5753:
5754: #
5755: # Rest of the restrictions depend on selected course
5756: #
5757:
1.620 albertel 5758: unless ($env{'request.course.id'}) {
1.766 albertel 5759: if ($thisallowed eq 'A') {
5760: return 'A';
1.814 raeburn 5761: } elsif ($thisallowed eq 'B') {
5762: return 'B';
1.766 albertel 5763: } else {
5764: return '1';
5765: }
1.52 www 5766: }
1.29 www 5767:
1.52 www 5768: #
5769: # Now user is definitely in a course
5770: #
1.53 www 5771:
5772:
5773: # Course preferences
5774:
5775: if ($thisallowed=~/C/) {
1.620 albertel 5776: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5777: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5778: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5779: =~/\Q$rolecode\E/) {
1.1056.4.22 raeburn 5780: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5781: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5782: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5783: $env{'request.course.id'});
5784: }
1.237 www 5785: return '';
5786: }
5787:
1.620 albertel 5788: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5789: =~/\Q$unamedom\E/) {
1.1056.4.22 raeburn 5790: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5791: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5792: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5793: $env{'request.course.id'});
5794: }
1.54 www 5795: return '';
5796: }
1.53 www 5797: }
5798:
5799: # Resource preferences
5800:
5801: if ($thisallowed=~/R/) {
1.620 albertel 5802: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5803: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1056.4.22 raeburn 5804: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5805: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5806: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5807: }
5808: return '';
1.54 www 5809: }
1.53 www 5810: }
1.30 www 5811:
1.246 www 5812: # Restricted by state or randomout?
1.30 www 5813:
1.52 www 5814: if ($thisallowed=~/X/) {
1.620 albertel 5815: if ($env{'acc.randomout'}) {
1.579 albertel 5816: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5817: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5818: return '';
5819: }
1.247 www 5820: }
5821: if (&condval($statecond)) {
1.52 www 5822: return '2';
5823: } else {
5824: return '';
5825: }
5826: }
1.30 www 5827:
1.766 albertel 5828: if ($thisallowed eq 'A') {
5829: return 'A';
1.814 raeburn 5830: } elsif ($thisallowed eq 'B') {
5831: return 'B';
1.766 albertel 5832: }
1.52 www 5833: return 'F';
1.232 www 5834: }
5835:
1.710 albertel 5836: sub split_uri_for_cond {
5837: my $uri=&deversion(&declutter(shift));
5838: my @uriparts=split(/\//,$uri);
5839: my $filename=pop(@uriparts);
5840: my $pathname=join('/',@uriparts);
5841: return ($pathname,$filename);
5842: }
1.232 www 5843: # --------------------------------------------------- Is a resource on the map?
5844:
5845: sub is_on_map {
1.710 albertel 5846: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5847: #Trying to find the conditional for the file
1.620 albertel 5848: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5849: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5850: if ($match) {
1.289 bowersj2 5851: return (1,$1);
5852: } else {
1.434 www 5853: return (0,0);
1.289 bowersj2 5854: }
1.12 www 5855: }
5856:
1.427 www 5857: # --------------------------------------------------------- Get symb from alias
5858:
5859: sub get_symb_from_alias {
5860: my $symb=shift;
5861: my ($map,$resid,$url)=&decode_symb($symb);
5862: # Already is a symb
5863: if ($url) { return $symb; }
5864: # Must be an alias
5865: my $aliassymb='';
5866: my %bighash;
1.620 albertel 5867: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5868: &GDBM_READER(),0640)) {
5869: my $rid=$bighash{'mapalias_'.$symb};
5870: if ($rid) {
5871: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5872: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5873: $resid,$bighash{'src_'.$rid});
1.427 www 5874: }
5875: untie %bighash;
5876: }
5877: return $aliassymb;
5878: }
5879:
1.12 www 5880: # ----------------------------------------------------------------- Define Role
5881:
5882: sub definerole {
5883: if (allowed('mcr','/')) {
5884: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5885: foreach my $role (split(':',$sysrole)) {
5886: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5887: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5888: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5889: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5890: return "refused:s:$crole&$cqual";
5891: }
5892: }
1.191 harris41 5893: }
1.800 albertel 5894: foreach my $role (split(':',$domrole)) {
5895: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5896: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5897: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5898: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5899: return "refused:d:$crole&$cqual";
5900: }
5901: }
1.191 harris41 5902: }
1.800 albertel 5903: foreach my $role (split(':',$courole)) {
5904: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5905: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5906: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5907: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5908: return "refused:c:$crole&$cqual";
5909: }
5910: }
1.191 harris41 5911: }
1.620 albertel 5912: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5913: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5914: "rolesdef_$rolename=".
5915: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5916: return reply($command,$env{'user.home'});
1.12 www 5917: } else {
5918: return 'refused';
5919: }
1.105 harris41 5920: }
5921:
5922: # ---------------- Make a metadata query against the network of library servers
5923:
5924: sub metadata_query {
1.244 matthew 5925: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5926: my %rhash;
1.845 albertel 5927: my %libserv = &all_library();
1.244 matthew 5928: my @server_list = (defined($server_array) ? @$server_array
5929: : keys(%libserv) );
5930: for my $server (@server_list) {
1.118 harris41 5931: unless ($custom or $customshow) {
5932: my $reply=&reply("querysend:".&escape($query),$server);
5933: $rhash{$server}=$reply;
5934: }
5935: else {
5936: my $reply=&reply("querysend:".&escape($query).':'.
5937: &escape($custom).':'.&escape($customshow),
5938: $server);
5939: $rhash{$server}=$reply;
5940: }
1.112 harris41 5941: }
1.118 harris41 5942: return \%rhash;
1.240 www 5943: }
5944:
5945: # ----------------------------------------- Send log queries and wait for reply
5946:
5947: sub log_query {
5948: my ($uname,$udom,$query,%filters)=@_;
5949: my $uhome=&homeserver($uname,$udom);
5950: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5951: my $uhost=&hostname($uhome);
1.800 albertel 5952: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5953: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5954: $uhome);
1.479 albertel 5955: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5956: return get_query_reply($queryid);
5957: }
5958:
1.818 raeburn 5959: # -------------------------- Update MySQL table for portfolio file
5960:
5961: sub update_portfolio_table {
1.821 raeburn 5962: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5963: if ($group ne '') {
5964: $file_name =~s /^\Q$group\E//;
5965: }
1.818 raeburn 5966: my $homeserver = &homeserver($uname,$udom);
5967: my $queryid=
1.821 raeburn 5968: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5969: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5970: my $reply = &get_query_reply($queryid);
5971: return $reply;
5972: }
5973:
1.899 raeburn 5974: # -------------------------- Update MySQL allusers table
5975:
5976: sub update_allusers_table {
5977: my ($uname,$udom,$names) = @_;
5978: my $homeserver = &homeserver($uname,$udom);
5979: my $queryid=
5980: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5981: 'lastname='.&escape($names->{'lastname'}).'%%'.
5982: 'firstname='.&escape($names->{'firstname'}).'%%'.
5983: 'middlename='.&escape($names->{'middlename'}).'%%'.
5984: 'generation='.&escape($names->{'generation'}).'%%'.
5985: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5986: 'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4 raeburn 5987: return;
1.899 raeburn 5988: }
5989:
1.508 raeburn 5990: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5991:
5992: sub fetch_enrollment_query {
1.511 raeburn 5993: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5994: my $homeserver;
1.547 raeburn 5995: my $maxtries = 1;
1.508 raeburn 5996: if ($context eq 'automated') {
5997: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5998: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5999: } else {
6000: $homeserver = &homeserver($cnum,$dom);
6001: }
1.838 albertel 6002: my $host=&hostname($homeserver);
1.506 raeburn 6003: my $cmd = '';
1.1000 raeburn 6004: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6005: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6006: }
6007: $cmd =~ s/%%$//;
6008: $cmd = &escape($cmd);
6009: my $query = 'fetchenrollment';
1.620 albertel 6010: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6011: unless ($queryid=~/^\Q$host\E\_/) {
6012: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6013: return 'error: '.$queryid;
6014: }
1.506 raeburn 6015: my $reply = &get_query_reply($queryid);
1.547 raeburn 6016: my $tries = 1;
6017: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6018: $reply = &get_query_reply($queryid);
6019: $tries ++;
6020: }
1.526 raeburn 6021: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6022: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6023: } else {
1.901 albertel 6024: my @responses = split(/:/,$reply);
1.515 raeburn 6025: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6026: foreach my $line (@responses) {
6027: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6028: $$replyref{$key} = $value;
6029: }
6030: } else {
1.506 raeburn 6031: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 6032: foreach my $line (@responses) {
6033: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6034: $$replyref{$key} = $value;
6035: if ($value > 0) {
1.800 albertel 6036: foreach my $item (@{$$affiliatesref{$key}}) {
6037: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6038: my $destname = $pathname.'/'.$filename;
6039: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6040: if ($xml_classlist =~ /^error/) {
6041: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6042: } else {
1.506 raeburn 6043: if ( open(FILE,">$destname") ) {
6044: print FILE &unescape($xml_classlist);
6045: close(FILE);
1.526 raeburn 6046: } else {
6047: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6048: }
6049: }
6050: }
6051: }
6052: }
6053: }
6054: return 'ok';
6055: }
6056: return 'error';
6057: }
6058:
1.242 www 6059: sub get_query_reply {
6060: my $queryid=shift;
1.240 www 6061: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
6062: my $reply='';
6063: for (1..100) {
6064: sleep 2;
6065: if (-e $replyfile.'.end') {
1.448 albertel 6066: if (open(my $fh,$replyfile)) {
1.904 albertel 6067: $reply = join('',<$fh>);
6068: close($fh);
1.240 www 6069: } else { return 'error: reply_file_error'; }
1.242 www 6070: return &unescape($reply);
6071: }
1.240 www 6072: }
1.242 www 6073: return 'timeout:'.$queryid;
1.240 www 6074: }
6075:
6076: sub courselog_query {
1.241 www 6077: #
6078: # possible filters:
6079: # url: url or symb
6080: # username
6081: # domain
6082: # action: view, submit, grade
6083: # start: timestamp
6084: # end: timestamp
6085: #
1.240 www 6086: my (%filters)=@_;
1.620 albertel 6087: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6088: if ($filters{'url'}) {
6089: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6090: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6091: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6092: }
1.620 albertel 6093: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6094: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6095: return &log_query($cname,$cdom,'courselog',%filters);
6096: }
6097:
6098: sub userlog_query {
1.858 raeburn 6099: #
6100: # possible filters:
6101: # action: log check role
6102: # start: timestamp
6103: # end: timestamp
6104: #
1.240 www 6105: my ($uname,$udom,%filters)=@_;
6106: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6107: }
6108:
1.506 raeburn 6109: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6110:
6111: sub auto_run {
1.508 raeburn 6112: my ($cnum,$cdom) = @_;
1.876 raeburn 6113: my $response = 0;
6114: my $settings;
6115: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6116: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6117: $settings = $domconfig{'autoenroll'};
6118: if ($settings->{'run'} eq '1') {
6119: $response = 1;
6120: }
6121: } else {
1.934 raeburn 6122: my $homeserver;
6123: if (&is_course($cdom,$cnum)) {
6124: $homeserver = &homeserver($cnum,$cdom);
6125: } else {
6126: $homeserver = &domain($cdom,'primary');
6127: }
6128: if ($homeserver ne 'no_host') {
6129: $response = &reply('autorun:'.$cdom,$homeserver);
6130: }
1.876 raeburn 6131: }
1.506 raeburn 6132: return $response;
6133: }
1.776 albertel 6134:
1.506 raeburn 6135: sub auto_get_sections {
1.508 raeburn 6136: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6137: my $homeserver;
6138: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6139: $homeserver = &homeserver($cnum,$cdom);
6140: }
6141: if (!defined($homeserver)) {
6142: if ($cdom =~ /^$match_domain$/) {
6143: $homeserver = &domain($cdom,'primary');
6144: }
6145: }
6146: my @secs;
6147: if (defined($homeserver)) {
6148: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6149: unless ($response eq 'refused') {
6150: @secs = split(/:/,$response);
6151: }
1.506 raeburn 6152: }
6153: return @secs;
6154: }
1.776 albertel 6155:
1.506 raeburn 6156: sub auto_new_course {
1.1056.4.19 raeburn 6157: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6158: my $homeserver = &homeserver($cnum,$cdom);
1.1056.4.19 raeburn 6159: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6160: return $response;
6161: }
1.776 albertel 6162:
1.506 raeburn 6163: sub auto_validate_courseID {
1.508 raeburn 6164: my ($cnum,$cdom,$inst_course_id) = @_;
6165: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6166: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6167: return $response;
6168: }
1.776 albertel 6169:
1.1007 raeburn 6170: sub auto_validate_instcode {
1.1020 raeburn 6171: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6172: my ($homeserver,$response);
6173: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6174: $homeserver = &homeserver($cnum,$cdom);
6175: }
6176: if (!defined($homeserver)) {
6177: if ($cdom =~ /^$match_domain$/) {
6178: $homeserver = &domain($cdom,'primary');
6179: }
6180: }
1.1056.4.2 raeburn 6181: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6182: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6183: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6184: return ($outcome,$description);
1.1007 raeburn 6185: }
6186:
1.506 raeburn 6187: sub auto_create_password {
1.873 raeburn 6188: my ($cnum,$cdom,$authparam,$udom) = @_;
6189: my ($homeserver,$response);
1.506 raeburn 6190: my $create_passwd = 0;
6191: my $authchk = '';
1.873 raeburn 6192: if ($udom =~ /^$match_domain$/) {
6193: $homeserver = &domain($udom,'primary');
6194: }
6195: if ($homeserver eq '') {
6196: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6197: $homeserver = &homeserver($cnum,$cdom);
6198: }
6199: }
6200: if ($homeserver eq '') {
6201: $authchk = 'nodomain';
1.506 raeburn 6202: } else {
1.873 raeburn 6203: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6204: if ($response eq 'refused') {
6205: $authchk = 'refused';
6206: } else {
1.901 albertel 6207: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6208: }
1.506 raeburn 6209: }
6210: return ($authparam,$create_passwd,$authchk);
6211: }
6212:
1.706 raeburn 6213: sub auto_photo_permission {
6214: my ($cnum,$cdom,$students) = @_;
6215: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6216: my ($outcome,$perm_reqd,$conditions) =
6217: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6218: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6219: return (undef,undef);
6220: }
1.706 raeburn 6221: return ($outcome,$perm_reqd,$conditions);
6222: }
6223:
6224: sub auto_checkphotos {
6225: my ($uname,$udom,$pid) = @_;
6226: my $homeserver = &homeserver($uname,$udom);
6227: my ($result,$resulttype);
6228: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6229: &escape($uname).':'.&escape($pid),
6230: $homeserver));
1.709 albertel 6231: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6232: return (undef,undef);
6233: }
1.706 raeburn 6234: if ($outcome) {
6235: ($result,$resulttype) = split(/:/,$outcome);
6236: }
6237: return ($result,$resulttype);
6238: }
6239:
6240: sub auto_photochoice {
6241: my ($cnum,$cdom) = @_;
6242: my $homeserver = &homeserver($cnum,$cdom);
6243: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6244: &escape($cdom),
6245: $homeserver)));
1.709 albertel 6246: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6247: return (undef,undef);
6248: }
1.706 raeburn 6249: return ($update,$comment);
6250: }
6251:
6252: sub auto_photoupdate {
6253: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6254: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6255: my $host=&hostname($homeserver);
1.706 raeburn 6256: my $cmd = '';
6257: my $maxtries = 1;
1.800 albertel 6258: foreach my $affiliate (keys(%{$affiliatesref})) {
6259: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6260: }
6261: $cmd =~ s/%%$//;
6262: $cmd = &escape($cmd);
6263: my $query = 'institutionalphotos';
6264: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6265: unless ($queryid=~/^\Q$host\E\_/) {
6266: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6267: return 'error: '.$queryid;
6268: }
6269: my $reply = &get_query_reply($queryid);
6270: my $tries = 1;
6271: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6272: $reply = &get_query_reply($queryid);
6273: $tries ++;
6274: }
6275: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6276: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6277: } else {
6278: my @responses = split(/:/,$reply);
6279: my $outcome = shift(@responses);
6280: foreach my $item (@responses) {
6281: my ($key,$value) = split(/=/,$item);
6282: $$photo{$key} = $value;
6283: }
6284: return $outcome;
6285: }
6286: return 'error';
6287: }
6288:
1.521 raeburn 6289: sub auto_instcode_format {
1.793 albertel 6290: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6291: $cat_order) = @_;
1.521 raeburn 6292: my $courses = '';
1.772 raeburn 6293: my @homeservers;
1.521 raeburn 6294: if ($caller eq 'global') {
1.841 albertel 6295: my %servers = &get_servers($codedom,'library');
6296: foreach my $tryserver (keys(%servers)) {
6297: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6298: push(@homeservers,$tryserver);
6299: }
1.584 raeburn 6300: }
1.1022 raeburn 6301: } elsif ($caller eq 'requests') {
6302: if ($codedom =~ /^$match_domain$/) {
6303: my $chome = &domain($codedom,'primary');
6304: unless ($chome eq 'no_host') {
6305: push(@homeservers,$chome);
6306: }
6307: }
1.521 raeburn 6308: } else {
1.772 raeburn 6309: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6310: }
1.793 albertel 6311: foreach my $code (keys(%{$instcodes})) {
6312: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6313: }
6314: chop($courses);
1.772 raeburn 6315: my $ok_response = 0;
6316: my $response;
6317: while (@homeservers > 0 && $ok_response == 0) {
6318: my $server = shift(@homeservers);
6319: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6320: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6321: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6322: split(/:/,$response);
1.772 raeburn 6323: %{$codes} = (%{$codes},&str2hash($codes_str));
6324: push(@{$codetitles},&str2array($codetitles_str));
6325: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6326: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6327: $ok_response = 1;
6328: }
6329: }
6330: if ($ok_response) {
1.521 raeburn 6331: return 'ok';
1.772 raeburn 6332: } else {
6333: return $response;
1.521 raeburn 6334: }
6335: }
6336:
1.792 raeburn 6337: sub auto_instcode_defaults {
6338: my ($domain,$returnhash,$code_order) = @_;
6339: my @homeservers;
1.841 albertel 6340:
6341: my %servers = &get_servers($domain,'library');
6342: foreach my $tryserver (keys(%servers)) {
6343: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6344: push(@homeservers,$tryserver);
6345: }
1.792 raeburn 6346: }
1.841 albertel 6347:
1.792 raeburn 6348: my $response;
1.841 albertel 6349: foreach my $server (@homeservers) {
1.792 raeburn 6350: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6351: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6352:
6353: foreach my $pair (split(/\&/,$response)) {
6354: my ($name,$value)=split(/\=/,$pair);
6355: if ($name eq 'code_order') {
6356: @{$code_order} = split(/\&/,&unescape($value));
6357: } else {
6358: $returnhash->{&unescape($name)}=&unescape($value);
6359: }
6360: }
6361: return 'ok';
1.792 raeburn 6362: }
1.841 albertel 6363:
6364: return $response;
1.1003 raeburn 6365: }
6366:
6367: sub auto_possible_instcodes {
1.1007 raeburn 6368: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6369: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6370: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6371: return;
6372: }
1.1003 raeburn 6373: my (@homeservers,$uhome);
6374: if (defined(&domain($domain,'primary'))) {
6375: $uhome=&domain($domain,'primary');
6376: push(@homeservers,&domain($domain,'primary'));
6377: } else {
6378: my %servers = &get_servers($domain,'library');
6379: foreach my $tryserver (keys(%servers)) {
6380: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6381: push(@homeservers,$tryserver);
6382: }
6383: }
6384: }
6385: my $response;
6386: foreach my $server (@homeservers) {
6387: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6388: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6389: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6390: split(':',$response);
6391: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6392: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6393: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6394: my ($name,$value)=split('=',$item);
6395: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6396: }
6397: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6398: my ($name,$value)=split('=',$item);
6399: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6400: }
6401: return 'ok';
6402: }
6403: return $response;
6404: }
1.792 raeburn 6405:
1.1010 raeburn 6406: sub auto_courserequest_checks {
6407: my ($dom) = @_;
1.1020 raeburn 6408: my ($homeserver,%validations);
6409: if ($dom =~ /^$match_domain$/) {
6410: $homeserver = &domain($dom,'primary');
6411: }
6412: unless ($homeserver eq 'no_host') {
6413: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6414: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6415: my @items = split(/&/,$response);
6416: foreach my $item (@items) {
6417: my ($key,$value) = split('=',$item);
6418: $validations{&unescape($key)} = &thaw_unescape($value);
6419: }
6420: }
6421: }
1.1010 raeburn 6422: return %validations;
6423: }
6424:
1.1020 raeburn 6425: sub auto_courserequest_validation {
6426: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6427: my ($homeserver,$response);
6428: if ($dom =~ /^$match_domain$/) {
6429: $homeserver = &domain($dom,'primary');
6430: }
6431: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6432:
1.1020 raeburn 6433: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6434: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6435: ':'.&escape($instcode).':'.&escape($instseclist),
6436: $homeserver));
6437: }
6438: return $response;
6439: }
6440:
1.777 albertel 6441: sub auto_validate_class_sec {
1.918 raeburn 6442: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6443: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6444: my $ownerlist;
6445: if (ref($owners) eq 'ARRAY') {
6446: $ownerlist = join(',',@{$owners});
6447: } else {
6448: $ownerlist = $owners;
6449: }
1.773 raeburn 6450: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6451: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6452: return $response;
6453: }
6454:
1.679 raeburn 6455: # ------------------------------------------------------- Course Group routines
6456:
6457: sub get_coursegroups {
1.809 raeburn 6458: my ($cdom,$cnum,$group,$namespace) = @_;
6459: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6460: }
6461:
1.679 raeburn 6462: sub modify_coursegroup {
6463: my ($cdom,$cnum,$groupsettings) = @_;
6464: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6465: }
6466:
1.809 raeburn 6467: sub toggle_coursegroup_status {
6468: my ($cdom,$cnum,$group,$action) = @_;
6469: my ($from_namespace,$to_namespace);
6470: if ($action eq 'delete') {
6471: $from_namespace = 'coursegroups';
6472: $to_namespace = 'deleted_groups';
6473: } else {
6474: $from_namespace = 'deleted_groups';
6475: $to_namespace = 'coursegroups';
6476: }
6477: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6478: if (my $tmp = &error(%curr_group)) {
6479: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6480: return ('read error',$tmp);
6481: } else {
6482: my %savedsettings = %curr_group;
1.809 raeburn 6483: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6484: my $deloutcome;
6485: if ($result eq 'ok') {
1.809 raeburn 6486: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6487: } else {
6488: return ('write error',$result);
6489: }
6490: if ($deloutcome eq 'ok') {
6491: return 'ok';
6492: } else {
6493: return ('delete error',$deloutcome);
6494: }
6495: }
6496: }
6497:
1.679 raeburn 6498: sub modify_group_roles {
1.957 raeburn 6499: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6500: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6501: my $role = 'gr/'.&escape($userprivs);
6502: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6503: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6504: if ($result eq 'ok') {
6505: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6506: }
1.679 raeburn 6507: return $result;
6508: }
6509:
6510: sub modify_coursegroup_membership {
6511: my ($cdom,$cnum,$membership) = @_;
6512: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6513: return $result;
6514: }
6515:
1.682 raeburn 6516: sub get_active_groups {
6517: my ($udom,$uname,$cdom,$cnum) = @_;
6518: my $now = time;
6519: my %groups = ();
6520: foreach my $key (keys(%env)) {
1.811 albertel 6521: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6522: my ($start,$end) = split(/\./,$env{$key});
6523: if (($end!=0) && ($end<$now)) { next; }
6524: if (($start!=0) && ($start>$now)) { next; }
6525: if ($1 eq $cdom && $2 eq $cnum) {
6526: $groups{$3} = $env{$key} ;
6527: }
6528: }
6529: }
6530: return %groups;
6531: }
6532:
1.683 raeburn 6533: sub get_group_membership {
6534: my ($cdom,$cnum,$group) = @_;
6535: return(&dump('groupmembership',$cdom,$cnum,$group));
6536: }
6537:
6538: sub get_users_groups {
6539: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6540: my @usersgroups;
1.683 raeburn 6541: my $cachetime=1800;
6542:
6543: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6544: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6545: if (defined($cached)) {
1.734 albertel 6546: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6547: } else {
6548: $grouplist = '';
1.816 raeburn 6549: my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 6550: my $extra = &freeze_escape({'skipcheck' => 1});
6551: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6552: my $access_end = $env{'course.'.$courseid.
6553: '.default_enrollment_end_date'};
6554: my $now = time;
6555: foreach my $key (keys(%roleshash)) {
6556: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6557: my $group = $1;
6558: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6559: my $start = $2;
6560: my $end = $1;
6561: if ($start == -1) { next; } # deleted from group
6562: if (($start!=0) && ($start>$now)) { next; }
6563: if (($end!=0) && ($end<$now)) {
6564: if ($access_end && $access_end < $now) {
6565: if ($access_end - $end < 86400) {
6566: push(@usersgroups,$group);
1.733 raeburn 6567: }
6568: }
1.817 raeburn 6569: next;
1.733 raeburn 6570: }
1.817 raeburn 6571: push(@usersgroups,$group);
1.683 raeburn 6572: }
6573: }
6574: }
1.817 raeburn 6575: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6576: $grouplist = join(':',@usersgroups);
6577: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6578: }
1.733 raeburn 6579: return @usersgroups;
1.683 raeburn 6580: }
6581:
6582: sub devalidate_getgroups_cache {
6583: my ($udom,$uname,$cdom,$cnum)=@_;
6584: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6585:
1.683 raeburn 6586: my $hashid="$udom:$uname:$courseid";
6587: &devalidate_cache_new('getgroups',$hashid);
6588: }
6589:
1.12 www 6590: # ------------------------------------------------------------------ Plain Text
6591:
6592: sub plaintext {
1.988 raeburn 6593: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6594: if ($short =~ m{^cr/}) {
1.758 albertel 6595: return (split('/',$short))[-1];
6596: }
1.742 raeburn 6597: if (!defined($cid)) {
6598: $cid = $env{'request.course.id'};
6599: }
6600: my %rolenames = (
1.1008 raeburn 6601: Course => 'std',
6602: Community => 'alt1',
1.742 raeburn 6603: );
1.1037 raeburn 6604: if ($cid ne '') {
6605: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6606: unless ($forcedefault) {
6607: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6608: &Apache::lonlocal::mt_escape(\$roletext);
6609: return &Apache::lonlocal::mt($roletext);
6610: }
6611: }
6612: }
6613: if ((defined($type)) && (defined($rolenames{$type})) &&
6614: (defined($rolenames{$type})) &&
6615: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6616: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6617: } elsif ($cid ne '') {
6618: my $crstype = $env{'course.'.$cid.'.type'};
6619: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6620: (defined($prp{$short}{$rolenames{$crstype}}))) {
6621: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6622: }
1.742 raeburn 6623: }
1.1037 raeburn 6624: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6625: }
6626:
6627: # ----------------------------------------------------------------- Assign Role
6628:
6629: sub assignrole {
1.957 raeburn 6630: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6631: $context)=@_;
1.21 www 6632: my $mrole;
6633: if ($role =~ /^cr\//) {
1.393 www 6634: my $cwosec=$url;
1.811 albertel 6635: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6636: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6637: my $refused = 1;
6638: if ($context eq 'requestcourses') {
6639: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6640: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6641: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6642: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6643: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6644: if ($crsenv{'internal.courseowner'} eq
6645: $env{'user.name'}.':'.$env{'user.domain'}) {
6646: $refused = '';
6647: }
6648: }
6649: }
6650: }
6651: }
6652: if ($refused) {
6653: &logthis('Refused custom assignrole: '.
6654: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6655: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6656: return 'refused';
6657: }
1.104 www 6658: }
1.21 www 6659: $mrole='cr';
1.678 raeburn 6660: } elsif ($role =~ /^gr\//) {
6661: my $cwogrp=$url;
1.811 albertel 6662: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6663: unless (&allowed('mdg',$cwogrp)) {
6664: &logthis('Refused group assignrole: '.
6665: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6666: $env{'user.name'}.' at '.$env{'user.domain'});
6667: return 'refused';
6668: }
6669: $mrole='gr';
1.21 www 6670: } else {
1.82 www 6671: my $cwosec=$url;
1.811 albertel 6672: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6673: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6674: my $refused;
6675: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6676: if (!(&allowed('c'.$role,$url))) {
6677: $refused = 1;
6678: }
6679: } else {
6680: $refused = 1;
6681: }
1.947 raeburn 6682: if ($refused) {
1.1045 raeburn 6683: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6684: if (!$selfenroll && $context eq 'course') {
6685: my %crsenv;
6686: if ($role eq 'cc' || $role eq 'co') {
6687: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6688: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6689: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6690: if ($crsenv{'internal.courseowner'} eq
6691: $env{'user.name'}.':'.$env{'user.domain'}) {
6692: $refused = '';
6693: }
6694: }
6695: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6696: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6697: if ($crsenv{'internal.courseowner'} eq
6698: $env{'user.name'}.':'.$env{'user.domain'}) {
6699: $refused = '';
6700: }
6701: }
6702: }
6703: }
6704: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6705: $refused = '';
1.1017 raeburn 6706: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6707: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6708: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6709: my $wrongcc;
6710: if ($cnum =~ /^$match_community$/) {
6711: $wrongcc = 1 if ($role eq 'cc');
6712: } else {
6713: $wrongcc = 1 if ($role eq 'co');
6714: }
6715: unless ($wrongcc) {
6716: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6717: if ($crsenv{'internal.courseowner'} eq
6718: $env{'user.name'}.':'.$env{'user.domain'}) {
6719: $refused = '';
6720: }
1.1017 raeburn 6721: }
6722: }
6723: }
6724: if ($refused) {
1.947 raeburn 6725: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6726: ' '.$role.' '.$end.' '.$start.' by '.
6727: $env{'user.name'}.' at '.$env{'user.domain'});
6728: return 'refused';
6729: }
1.932 raeburn 6730: }
1.104 www 6731: }
1.21 www 6732: $mrole=$role;
6733: }
1.620 albertel 6734: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6735: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6736: if ($end) { $command.='_'.$end; }
1.21 www 6737: if ($start) {
6738: if ($end) {
1.81 www 6739: $command.='_'.$start;
1.21 www 6740: } else {
1.81 www 6741: $command.='_0_'.$start;
1.21 www 6742: }
6743: }
1.739 raeburn 6744: my $origstart = $start;
6745: my $origend = $end;
1.957 raeburn 6746: my $delflag;
1.357 www 6747: # actually delete
6748: if ($deleteflag) {
1.373 www 6749: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6750: # modify command to delete the role
1.620 albertel 6751: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6752: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6753: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6754: # set start and finish to negative values for userrolelog
6755: $start=-1;
6756: $end=-1;
1.957 raeburn 6757: $delflag = 1;
1.357 www 6758: }
6759: }
6760: # send command
1.349 www 6761: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6762: # log new user role if status is ok
1.349 www 6763: if ($answer eq 'ok') {
1.663 raeburn 6764: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6765: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6766: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6767: unless ($role =~ /^gr/) {
6768: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6769: $origstart,$selfenroll,$context);
1.739 raeburn 6770: }
1.1053 raeburn 6771: if ($role eq 'cc') {
6772: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6773: }
1.349 www 6774: }
6775: return $answer;
1.169 harris41 6776: }
6777:
1.1053 raeburn 6778: sub autoupdate_coowners {
6779: my ($url,$end,$start,$uname,$udom) = @_;
6780: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6781: if (($cdom ne '') && ($cnum ne '')) {
6782: my $now = time;
6783: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6784: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6785: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6786: my $instcode = $coursehash{'internal.coursecode'};
6787: if ($instcode ne '') {
1.1056 raeburn 6788: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6789: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6790: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6791: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6792: if ($result eq 'valid') {
6793: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6794: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6795: push(@newcoowners,$coowner);
6796: }
6797: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6798: push(@newcoowners,$uname.':'.$udom);
6799: }
6800: @newcoowners = sort(@newcoowners);
6801: } else {
6802: push(@newcoowners,$uname.':'.$udom);
6803: }
6804: } else {
6805: if ($coursehash{'internal.co-owners'}) {
6806: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6807: unless ($coowner eq $uname.':'.$udom) {
6808: push(@newcoowners,$coowner);
6809: }
6810: }
6811: unless (@newcoowners > 0) {
6812: $delcoowners = 1;
6813: $coowners = '';
6814: }
6815: }
6816: }
6817: if (@newcoowners || $delcoowners) {
6818: &store_coowners($cdom,$cnum,$coursehash{'home'},
6819: $delcoowners,@newcoowners);
6820: }
6821: }
6822: }
6823: }
6824: }
6825: }
6826: }
6827:
6828: sub store_coowners {
6829: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6830: my $cid = $cdom.'_'.$cnum;
6831: my ($coowners,$delresult,$putresult);
6832: if (@newcoowners) {
6833: $coowners = join(',',@newcoowners);
6834: my %coownershash = (
6835: 'internal.co-owners' => $coowners,
6836: );
6837: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6838: if ($putresult eq 'ok') {
6839: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6840: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6841: }
6842: }
6843: }
6844: if ($delcoowners) {
6845: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6846: if ($delresult eq 'ok') {
6847: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6848: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6849: }
6850: }
6851: }
6852: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6853: my %crsinfo =
6854: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6855: if (ref($crsinfo{$cid}) eq 'HASH') {
6856: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6857: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6858: }
6859: }
6860: }
6861:
1.169 harris41 6862: # -------------------------------------------------- Modify user authentication
1.197 www 6863: # Overrides without validation
6864:
1.169 harris41 6865: sub modifyuserauth {
6866: my ($udom,$uname,$umode,$upass)=@_;
6867: my $uhome=&homeserver($uname,$udom);
1.197 www 6868: unless (&allowed('mau',$udom)) { return 'refused'; }
6869: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6870: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6871: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6872: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6873: &escape($upass),$uhome);
1.620 albertel 6874: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6875: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6876: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6877: &log($udom,,$uname,$uhome,
1.620 albertel 6878: 'Authentication changed by '.$env{'user.domain'}.', '.
6879: $env{'user.name'}.', '.$umode.
1.197 www 6880: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6881: unless ($reply eq 'ok') {
1.197 www 6882: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6883: return 'error: '.$reply;
6884: }
1.170 harris41 6885: return 'ok';
1.80 www 6886: }
6887:
1.81 www 6888: # --------------------------------------------------------------- Modify a user
1.80 www 6889:
1.81 www 6890: sub modifyuser {
1.206 matthew 6891: my ($udom, $uname, $uid,
6892: $umode, $upass, $first,
6893: $middle, $last, $gene,
1.1056.4.1 raeburn 6894: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6895: $udom= &LONCAPA::clean_domain($udom);
6896: $uname=&LONCAPA::clean_username($uname);
1.1056.4.1 raeburn 6897: my $showcandelete = 'none';
6898: if (ref($candelete) eq 'ARRAY') {
6899: if (@{$candelete} > 0) {
6900: $showcandelete = join(', ',@{$candelete});
6901: }
6902: }
1.81 www 6903: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6904: $umode.', '.$first.', '.$middle.', '.
1.1056.4.1 raeburn 6905: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6906: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6907: ' desiredhome not specified').
1.620 albertel 6908: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6909: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6910: my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4 raeburn 6911: my $newuser;
6912: if ($uhome eq 'no_host') {
6913: $newuser = 1;
6914: }
1.80 www 6915: # ----------------------------------------------------------------- Create User
1.406 albertel 6916: if (($uhome eq 'no_host') &&
6917: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6918: my $unhome='';
1.844 albertel 6919: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6920: $unhome = $desiredhome;
1.620 albertel 6921: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6922: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6923: } else { # load balancing routine for determining $unhome
1.81 www 6924: my $loadm=10000000;
1.841 albertel 6925: my %servers = &get_servers($udom,'library');
6926: foreach my $tryserver (keys(%servers)) {
6927: my $answer=reply('load',$tryserver);
6928: if (($answer=~/\d+/) && ($answer<$loadm)) {
6929: $loadm=$answer;
6930: $unhome=$tryserver;
6931: }
1.80 www 6932: }
6933: }
6934: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6935: return 'error: unable to find a home server for '.$uname.
6936: ' in domain '.$udom;
1.80 www 6937: }
6938: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6939: &escape($upass),$unhome);
6940: unless ($reply eq 'ok') {
6941: return 'error: '.$reply;
6942: }
1.230 stredwic 6943: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6944: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6945: return 'error: unable verify users home machine.';
1.80 www 6946: }
1.209 matthew 6947: } # End of creation of new user
1.80 www 6948: # ---------------------------------------------------------------------- Add ID
6949: if ($uid) {
6950: $uid=~tr/A-Z/a-z/;
6951: my %uidhash=&idrget($udom,$uname);
1.196 www 6952: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6953: && (!$forceid)) {
1.80 www 6954: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6955: return 'error: user id "'.$uid.'" does not match '.
6956: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6957: }
6958: } else {
6959: &idput($udom,($uname => $uid));
6960: }
6961: }
6962: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6963: my @tmp=&get('environment',
1.899 raeburn 6964: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6965: 'permanentemail','inststatus'],
1.134 albertel 6966: $udom,$uname);
1.1056.4.4 raeburn 6967: my (%names,%oldnames);
1.313 matthew 6968: if ($tmp[0] =~ m/^error:.*/) {
6969: %names=();
6970: } else {
6971: %names = @tmp;
1.1056.4.4 raeburn 6972: %oldnames = %names;
1.313 matthew 6973: }
1.1056.4.6 raeburn 6974: #
1.1056.4.1 raeburn 6975: # If name, email and/or uid are blank (e.g., because an uploaded file
6976: # of users did not contain them), do not overwrite existing values
6977: # unless field is in $candelete array ref.
6978: #
6979:
6980: my @fields = ('firstname','middlename','lastname','generation',
6981: 'permanentemail','id');
6982: my %newvalues;
6983: if (ref($candelete) eq 'ARRAY') {
6984: foreach my $field (@fields) {
6985: if (grep(/^\Q$field\E$/,@{$candelete})) {
6986: if ($field eq 'firstname') {
6987: $names{$field} = $first;
6988: } elsif ($field eq 'middlename') {
6989: $names{$field} = $middle;
6990: } elsif ($field eq 'lastname') {
6991: $names{$field} = $last;
6992: } elsif ($field eq 'generation') {
6993: $names{$field} = $gene;
6994: } elsif ($field eq 'permanentemail') {
6995: $names{$field} = $email;
6996: } elsif ($field eq 'id') {
6997: $names{$field} = $uid;
6998: }
6999: }
7000: }
7001: }
1.388 www 7002: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7003: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7004: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7005: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7006: if ($email) {
7007: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7008: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7009: }
1.899 raeburn 7010: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7011: if (defined($inststatus)) {
7012: $names{'inststatus'} = '';
7013: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7014: if (ref($usertypes) eq 'HASH') {
7015: my @okstatuses;
7016: foreach my $item (split(/:/,$inststatus)) {
7017: if (defined($usertypes->{$item})) {
7018: push(@okstatuses,$item);
7019: }
7020: }
7021: if (@okstatuses) {
7022: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7023: }
7024: }
7025: }
1.1056.4.4 raeburn 7026: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7027: $umode.', '.$first.', '.$middle.', '.
1.1056.4.4 raeburn 7028: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7029: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7030: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7031: } else {
7032: $logmsg .= ' during self creation';
7033: }
1.1056.4.4 raeburn 7034: my $changed;
7035: if ($newuser) {
7036: $changed = 1;
7037: } else {
7038: foreach my $field (@fields) {
7039: if ($names{$field} ne $oldnames{$field}) {
7040: $changed = 1;
7041: last;
7042: }
7043: }
7044: }
7045: unless ($changed) {
7046: $logmsg = 'No changes in user information needed for: '.$logmsg;
7047: &logthis($logmsg);
7048: return 'ok';
7049: }
7050: my $reply = &put('environment', \%names, $udom,$uname);
7051: if ($reply ne 'ok') {
7052: return 'error: '.$reply;
7053: }
1.1056.4.11 raeburn 7054: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7055: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7056: }
1.1056.4.4 raeburn 7057: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7058: &devalidate_cache_new('namescache',$uname.':'.$udom);
7059: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7060: &logthis($logmsg);
1.134 albertel 7061: return 'ok';
1.80 www 7062: }
7063:
1.81 www 7064: # -------------------------------------------------------------- Modify student
1.80 www 7065:
1.81 www 7066: sub modifystudent {
7067: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7068: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7069: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7070: if (!$cid) {
1.620 albertel 7071: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7072: return 'not_in_class';
7073: }
1.80 www 7074: }
7075: # --------------------------------------------------------------- Make the user
1.81 www 7076: my $reply=&modifyuser
1.209 matthew 7077: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7078: $desiredhome,$email,$inststatus);
1.80 www 7079: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7080: # This will cause &modify_student_enrollment to get the uid from the
7081: # students environment
7082: $uid = undef if (!$forceid);
1.455 albertel 7083: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7084: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7085: return $reply;
7086: }
7087:
7088: sub modify_student_enrollment {
1.957 raeburn 7089: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7090: my ($cdom,$cnum,$chome);
7091: if (!$cid) {
1.620 albertel 7092: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7093: return 'not_in_class';
7094: }
1.620 albertel 7095: $cdom=$env{'course.'.$cid.'.domain'};
7096: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7097: } else {
7098: ($cdom,$cnum)=split(/_/,$cid);
7099: }
1.620 albertel 7100: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7101: if (!$chome) {
1.457 raeburn 7102: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7103: }
1.455 albertel 7104: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7105: # Make sure the user exists
1.81 www 7106: my $uhome=&homeserver($uname,$udom);
7107: if (($uhome eq '') || ($uhome eq 'no_host')) {
7108: return 'error: no such user';
7109: }
1.297 matthew 7110: # Get student data if we were not given enough information
7111: if (!defined($first) || $first eq '' ||
7112: !defined($last) || $last eq '' ||
7113: !defined($uid) || $uid eq '' ||
7114: !defined($middle) || $middle eq '' ||
7115: !defined($gene) || $gene eq '') {
1.294 matthew 7116: # They did not supply us with enough data to enroll the student, so
7117: # we need to pick up more information.
1.297 matthew 7118: my %tmp = &get('environment',
1.294 matthew 7119: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7120: ,$udom,$uname);
7121:
1.800 albertel 7122: #foreach my $key (keys(%tmp)) {
7123: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7124: #}
1.294 matthew 7125: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7126: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7127: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7128: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7129: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7130: }
1.556 albertel 7131: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7132: my $reply=cput('classlist',
7133: {"$uname:$udom" =>
1.515 raeburn 7134: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7135: $cdom,$cnum);
1.81 www 7136: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7137: return 'error: '.$reply;
1.652 albertel 7138: } else {
7139: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7140: }
1.297 matthew 7141: # Add student role to user
1.83 www 7142: my $uurl='/'.$cid;
1.81 www 7143: $uurl=~s/\_/\//g;
7144: if ($usec) {
7145: $uurl.='/'.$usec;
7146: }
1.957 raeburn 7147: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7148: }
7149:
1.556 albertel 7150: sub format_name {
7151: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7152: my $name;
7153: if ($first ne 'lastname') {
7154: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7155: } else {
7156: if ($lastname=~/\S/) {
7157: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7158: $name=~s/\s+,/,/;
7159: } else {
7160: $name.= $firstname.' '.$middlename.' '.$generation;
7161: }
7162: }
7163: $name=~s/^\s+//;
7164: $name=~s/\s+$//;
7165: $name=~s/\s+/ /g;
7166: return $name;
7167: }
7168:
1.84 www 7169: # ------------------------------------------------- Write to course preferences
7170:
7171: sub writecoursepref {
7172: my ($courseid,%prefs)=@_;
7173: $courseid=~s/^\///;
7174: $courseid=~s/\_/\//g;
7175: my ($cdomain,$cnum)=split(/\//,$courseid);
7176: my $chome=homeserver($cnum,$cdomain);
7177: if (($chome eq '') || ($chome eq 'no_host')) {
7178: return 'error: no such course';
7179: }
7180: my $cstring='';
1.800 albertel 7181: foreach my $pref (keys(%prefs)) {
7182: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7183: }
1.84 www 7184: $cstring=~s/\&$//;
7185: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7186: }
7187:
7188: # ---------------------------------------------------------- Make/modify course
7189:
7190: sub createcourse {
1.741 raeburn 7191: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7192: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7193: $url=&declutter($url);
7194: my $cid='';
1.1028 raeburn 7195: if ($context eq 'requestcourses') {
7196: my $can_create = 0;
7197: my ($ownername,$ownerdom) = split(':',$course_owner);
7198: if ($udom eq $ownerdom) {
7199: if (&usertools_access($ownername,$ownerdom,$category,undef,
7200: $context)) {
7201: $can_create = 1;
7202: }
7203: } else {
7204: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7205: $category);
7206: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7207: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7208: if (@curr > 0) {
7209: my @options = qw(approval validate autolimit);
7210: my $optregex = join('|',@options);
7211: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7212: $can_create = 1;
7213: }
7214: }
7215: }
7216: }
7217: if ($can_create) {
7218: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7219: unless (&allowed('ccc',$udom)) {
7220: return 'refused';
7221: }
1.1017 raeburn 7222: }
7223: } else {
7224: return 'refused';
7225: }
1.1028 raeburn 7226: } elsif (!&allowed('ccc',$udom)) {
7227: return 'refused';
1.84 www 7228: }
1.1011 raeburn 7229: # --------------------------------------------------------------- Get Unique ID
7230: my $uname;
7231: if ($cnum =~ /^$match_courseid$/) {
7232: my $chome=&homeserver($cnum,$udom,'true');
7233: if (($chome eq '') || ($chome eq 'no_host')) {
7234: $uname = $cnum;
7235: } else {
1.1038 raeburn 7236: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7237: }
7238: } else {
1.1038 raeburn 7239: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7240: }
7241: return $uname if ($uname =~ /^error/);
7242: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7243: if (!defined($course_server)) {
7244: if (defined(&domain($udom,'primary'))) {
7245: $course_server = &domain($udom,'primary');
7246: } else {
7247: $course_server = $env{'user.home'};
7248: }
7249: }
7250: my %host_servers =
7251: &Apache::lonnet::get_servers($udom,'library');
7252: unless ($host_servers{$course_server}) {
7253: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7254: }
1.84 www 7255: # ------------------------------------------------------------- Make the course
7256: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7257: $course_server);
1.84 www 7258: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7259: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7260: if (($uhome eq '') || ($uhome eq 'no_host')) {
7261: return 'error: no such course';
7262: }
1.271 www 7263: # ----------------------------------------------------------------- Course made
1.516 raeburn 7264: # log existence
1.1029 raeburn 7265: my $now = time;
1.918 raeburn 7266: my $newcourse = {
7267: $udom.'_'.$uname => {
1.921 raeburn 7268: description => $description,
7269: inst_code => $inst_code,
7270: owner => $course_owner,
7271: type => $crstype,
1.1029 raeburn 7272: creator => $env{'user.name'}.':'.
7273: $env{'user.domain'},
7274: created => $now,
7275: context => $context,
1.918 raeburn 7276: },
7277: };
1.921 raeburn 7278: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7279: # set toplevel url
1.271 www 7280: my $topurl=$url;
7281: unless ($nonstandard) {
7282: # ------------------------------------------ For standard courses, make top url
7283: my $mapurl=&clutter($url);
1.278 www 7284: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7285: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7286: <map>
7287: <resource id="1" type="start"></resource>
7288: <resource id="2" src="$mapurl"></resource>
7289: <resource id="3" type="finish"></resource>
7290: <link index="1" from="1" to="2"></link>
7291: <link index="2" from="2" to="3"></link>
7292: </map>
7293: ENDINITMAP
7294: $topurl=&declutter(
1.638 albertel 7295: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7296: );
7297: }
7298: # ----------------------------------------------------------- Write preferences
1.84 www 7299: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7300: ('description' => $description,
7301: 'url' => $topurl,
7302: 'internal.creator' => $env{'user.name'}.':'.
7303: $env{'user.domain'},
7304: 'internal.created' => $now,
7305: 'internal.creationcontext' => $context)
7306: );
1.84 www 7307: return '/'.$udom.'/'.$uname;
7308: }
7309:
1.1011 raeburn 7310: # ------------------------------------------------------------------- Create ID
7311: sub generate_coursenum {
1.1038 raeburn 7312: my ($udom,$crstype) = @_;
1.1011 raeburn 7313: my $domdesc = &domain($udom);
7314: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7315: my $first;
7316: if ($crstype eq 'Community') {
7317: $first = '0';
7318: } else {
7319: $first = int(1+rand(9));
7320: }
7321: my $uname=$first.
1.1011 raeburn 7322: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7323: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7324: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7325: # ----------------------------------------------- Make sure that does not exist
7326: my $uhome=&homeserver($uname,$udom,'true');
7327: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7328: if ($crstype eq 'Community') {
7329: $first = '0';
7330: } else {
7331: $first = int(1+rand(9));
7332: }
7333: $uname=$first.
1.1011 raeburn 7334: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7335: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7336: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7337: $uhome=&homeserver($uname,$udom,'true');
7338: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7339: return 'error: unable to generate unique course-ID';
7340: }
7341: }
7342: return $uname;
7343: }
7344:
1.813 albertel 7345: sub is_course {
7346: my ($cdom,$cnum) = @_;
7347: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7348: undef,'.');
1.813 albertel 7349: if (exists($courses{$cdom.'_'.$cnum})) {
7350: return 1;
7351: }
7352: return 0;
7353: }
7354:
1.1015 raeburn 7355: sub store_userdata {
7356: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7357: my $result;
1.1016 raeburn 7358: if ($datakey ne '') {
1.1013 raeburn 7359: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7360: if ($udom eq '' || $uname eq '') {
7361: $udom = $env{'user.domain'};
7362: $uname = $env{'user.name'};
7363: }
7364: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7365: if (($uhome eq '') || ($uhome eq 'no_host')) {
7366: $result = 'error: no_host';
7367: } else {
7368: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7369: $storehash->{'host'} = $perlvar{'lonHostID'};
7370:
7371: my $namevalue='';
7372: foreach my $key (keys(%{$storehash})) {
7373: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7374: }
7375: $namevalue=~s/\&$//;
1.1056.4.24 raeburn 7376: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7377: $namevalue,$uhome);
1.1013 raeburn 7378: }
7379: } else {
7380: $result = 'error: data to store was not a hash reference';
7381: }
7382: } else {
7383: $result= 'error: invalid requestkey';
7384: }
7385: return $result;
7386: }
7387:
1.21 www 7388: # ---------------------------------------------------------- Assign Custom Role
7389:
7390: sub assigncustomrole {
1.957 raeburn 7391: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7392: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7393: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7394: }
7395:
7396: # ----------------------------------------------------------------- Revoke Role
7397:
7398: sub revokerole {
1.957 raeburn 7399: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7400: my $now=time;
1.965 raeburn 7401: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7402: }
7403:
7404: # ---------------------------------------------------------- Revoke Custom Role
7405:
7406: sub revokecustomrole {
1.957 raeburn 7407: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7408: my $now=time;
1.357 www 7409: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7410: $deleteflag,$selfenroll,$context);
1.17 www 7411: }
7412:
1.533 banghart 7413: # ------------------------------------------------------------ Disk usage
1.535 albertel 7414: sub diskusage {
1.955 raeburn 7415: my ($udom,$uname,$directorypath,$getpropath)=@_;
7416: $directorypath =~ s/\/$//;
7417: my $listing=&reply('du2:'.&escape($directorypath).':'
7418: .&escape($getpropath).':'.&escape($uname).':'
7419: .&escape($udom),homeserver($uname,$udom));
7420: if ($listing eq 'unknown_cmd') {
7421: if ($getpropath) {
7422: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7423: }
7424: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7425: }
1.514 albertel 7426: return $listing;
1.512 banghart 7427: }
7428:
1.566 banghart 7429: sub is_locked {
1.1056.4.17 raeburn 7430: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7431: my @check;
7432: my $is_locked;
1.1056.4.14 raeburn 7433: push(@check,$file_name);
1.613 albertel 7434: my %locked = &get('file_permissions',\@check,
1.620 albertel 7435: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7436: my ($tmp)=keys(%locked);
7437: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7438:
1.566 banghart 7439: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7440: $is_locked = 'false';
7441: foreach my $entry (@{$locked{$file_name}}) {
1.1056.4.17 raeburn 7442: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7443: $is_locked = 'true';
1.1056.4.17 raeburn 7444: if (ref($which) eq 'ARRAY') {
7445: push(@{$which},$entry);
7446: } else {
7447: last;
7448: }
1.745 raeburn 7449: }
7450: }
1.566 banghart 7451: } else {
7452: $is_locked = 'false';
7453: }
1.1056.4.14 raeburn 7454: return $is_locked;
1.566 banghart 7455: }
7456:
1.759 albertel 7457: sub declutter_portfile {
7458: my ($file) = @_;
1.833 albertel 7459: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7460: return $file;
7461: }
7462:
1.559 banghart 7463: # ------------------------------------------------------------- Mark as Read Only
7464:
7465: sub mark_as_readonly {
7466: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7467: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7468: my ($tmp)=keys(%current_permissions);
7469: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7470: foreach my $file (@{$files}) {
1.759 albertel 7471: $file = &declutter_portfile($file);
1.561 banghart 7472: push(@{$current_permissions{$file}},$what);
1.559 banghart 7473: }
1.613 albertel 7474: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7475: return;
7476: }
7477:
1.572 banghart 7478: # ------------------------------------------------------------Save Selected Files
7479:
7480: sub save_selected_files {
7481: my ($user, $path, @files) = @_;
7482: my $filename = $user."savedfiles";
1.573 banghart 7483: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7484: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7485: foreach my $file (@files) {
1.620 albertel 7486: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7487: }
7488: foreach my $file (@other_files) {
1.574 banghart 7489: print (OUT $file."\n");
1.572 banghart 7490: }
1.574 banghart 7491: close (OUT);
1.572 banghart 7492: return 'ok';
7493: }
7494:
1.574 banghart 7495: sub clear_selected_files {
7496: my ($user) = @_;
7497: my $filename = $user."savedfiles";
7498: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7499: print (OUT undef);
7500: close (OUT);
7501: return ("ok");
7502: }
7503:
1.572 banghart 7504: sub files_in_path {
7505: my ($user, $path) = @_;
7506: my $filename = $user."savedfiles";
7507: my %return_files;
1.574 banghart 7508: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7509: while (my $line_in = <IN>) {
1.574 banghart 7510: chomp ($line_in);
7511: my @paths_and_file = split (m!/!, $line_in);
7512: my $file_part = pop (@paths_and_file);
7513: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7514: $path_part.='/';
7515: my $path_and_file = $path_part.$file_part;
7516: if ($path_part eq $path) {
7517: $return_files{$file_part}= 'selected';
7518: }
7519: }
1.574 banghart 7520: close (IN);
7521: return (\%return_files);
1.572 banghart 7522: }
7523:
7524: # called in portfolio select mode, to show files selected NOT in current directory
7525: sub files_not_in_path {
7526: my ($user, $path) = @_;
7527: my $filename = $user."savedfiles";
7528: my @return_files;
7529: my $path_part;
1.800 albertel 7530: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7531: while (my $line = <IN>) {
1.572 banghart 7532: #ok, I know it's clunky, but I want it to work
1.800 albertel 7533: my @paths_and_file = split(m|/|, $line);
7534: my $file_part = pop(@paths_and_file);
7535: chomp($file_part);
7536: my $path_part = join('/', @paths_and_file);
1.572 banghart 7537: $path_part .= '/';
7538: my $path_and_file = $path_part.$file_part;
7539: if ($path_part ne $path) {
1.800 albertel 7540: push(@return_files, ($path_and_file));
1.572 banghart 7541: }
7542: }
1.800 albertel 7543: close(OUT);
1.574 banghart 7544: return (@return_files);
1.572 banghart 7545: }
7546:
1.745 raeburn 7547: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7548:
1.745 raeburn 7549: sub get_portfile_permissions {
7550: my ($domain,$user) = @_;
1.613 albertel 7551: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7552: my ($tmp)=keys(%current_permissions);
7553: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7554: return \%current_permissions;
7555: }
7556:
7557: #---------------------------------------------Get portfolio file access controls
7558:
1.749 raeburn 7559: sub get_access_controls {
1.745 raeburn 7560: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7561: my %access;
7562: my $real_file = $file;
7563: $file =~ s/\.meta$//;
1.745 raeburn 7564: if (defined($file)) {
1.749 raeburn 7565: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7566: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7567: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7568: }
7569: }
1.745 raeburn 7570: } else {
1.749 raeburn 7571: foreach my $key (keys(%{$current_permissions})) {
7572: if ($key =~ /\0accesscontrol$/) {
7573: if (defined($group)) {
7574: if ($key !~ m-^\Q$group\E/-) {
7575: next;
7576: }
7577: }
7578: my ($fullpath) = split(/\0/,$key);
7579: if (ref($$current_permissions{$key}) eq 'HASH') {
7580: foreach my $control (keys(%{$$current_permissions{$key}})) {
7581: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7582: }
7583: }
7584: }
7585: }
7586: }
7587: return %access;
7588: }
7589:
7590: sub modify_access_controls {
7591: my ($file_name,$changes,$domain,$user)=@_;
7592: my ($outcome,$deloutcome);
7593: my %store_permissions;
7594: my %new_values;
7595: my %new_control;
7596: my %translation;
7597: my @deletions = ();
7598: my $now = time;
7599: if (exists($$changes{'activate'})) {
7600: if (ref($$changes{'activate'}) eq 'HASH') {
7601: my @newitems = sort(keys(%{$$changes{'activate'}}));
7602: my $numnew = scalar(@newitems);
7603: for (my $i=0; $i<$numnew; $i++) {
7604: my $newkey = $newitems[$i];
7605: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7606: if ($newkey =~ /^\d+:/) {
7607: $newkey =~ s/^(\d+)/$newid/;
7608: $translation{$1} = $newid;
7609: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7610: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7611: $translation{$1} = $newid;
7612: }
1.749 raeburn 7613: $new_values{$file_name."\0".$newkey} =
7614: $$changes{'activate'}{$newitems[$i]};
7615: $new_control{$newkey} = $now;
7616: }
7617: }
7618: }
7619: my %todelete;
7620: my %changed_items;
7621: foreach my $action ('delete','update') {
7622: if (exists($$changes{$action})) {
7623: if (ref($$changes{$action}) eq 'HASH') {
7624: foreach my $key (keys(%{$$changes{$action}})) {
7625: my ($itemnum) = ($key =~ /^([^:]+):/);
7626: if ($action eq 'delete') {
7627: $todelete{$itemnum} = 1;
7628: } else {
7629: $changed_items{$itemnum} = $key;
7630: }
7631: }
1.745 raeburn 7632: }
7633: }
1.749 raeburn 7634: }
7635: # get lock on access controls for file.
7636: my $lockhash = {
7637: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7638: ':'.$env{'user.domain'},
7639: };
7640: my $tries = 0;
7641: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7642:
7643: while (($gotlock ne 'ok') && $tries <3) {
7644: $tries ++;
7645: sleep 1;
7646: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7647: }
7648: if ($gotlock eq 'ok') {
7649: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7650: my ($tmp)=keys(%curr_permissions);
7651: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7652: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7653: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7654: if (ref($curr_controls) eq 'HASH') {
7655: foreach my $control_item (keys(%{$curr_controls})) {
7656: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7657: if (defined($todelete{$itemnum})) {
7658: push(@deletions,$file_name."\0".$control_item);
7659: } else {
7660: if (defined($changed_items{$itemnum})) {
7661: $new_control{$changed_items{$itemnum}} = $now;
7662: push(@deletions,$file_name."\0".$control_item);
7663: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7664: } else {
7665: $new_control{$control_item} = $$curr_controls{$control_item};
7666: }
7667: }
1.745 raeburn 7668: }
7669: }
7670: }
1.970 raeburn 7671: my ($group);
7672: if (&is_course($domain,$user)) {
7673: ($group,my $file) = split(/\//,$file_name,2);
7674: }
1.749 raeburn 7675: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7676: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7677: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7678: # remove lock
7679: my @del_lock = ($file_name."\0".'locked_access_records');
7680: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7681: my $sqlresult =
1.970 raeburn 7682: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7683: $group);
1.749 raeburn 7684: } else {
7685: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7686: }
1.749 raeburn 7687: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7688: }
7689:
1.827 raeburn 7690: sub make_public_indefinitely {
7691: my ($requrl) = @_;
7692: my $now = time;
7693: my $action = 'activate';
7694: my $aclnum = 0;
7695: if (&is_portfolio_url($requrl)) {
7696: my (undef,$udom,$unum,$file_name,$group) =
7697: &parse_portfolio_url($requrl);
7698: my $current_perms = &get_portfile_permissions($udom,$unum);
7699: my %access_controls = &get_access_controls($current_perms,
7700: $group,$file_name);
7701: foreach my $key (keys(%{$access_controls{$file_name}})) {
7702: my ($num,$scope,$end,$start) =
7703: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7704: if ($scope eq 'public') {
7705: if ($start <= $now && $end == 0) {
7706: $action = 'none';
7707: } else {
7708: $action = 'update';
7709: $aclnum = $num;
7710: }
7711: last;
7712: }
7713: }
7714: if ($action eq 'none') {
7715: return 'ok';
7716: } else {
7717: my %changes;
7718: my $newend = 0;
7719: my $newstart = $now;
7720: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7721: $changes{$action}{$newkey} = {
7722: type => 'public',
7723: time => {
7724: start => $newstart,
7725: end => $newend,
7726: },
7727: };
7728: my ($outcome,$deloutcome,$new_values,$translation) =
7729: &modify_access_controls($file_name,\%changes,$udom,$unum);
7730: return $outcome;
7731: }
7732: } else {
7733: return 'invalid';
7734: }
7735: }
7736:
1.745 raeburn 7737: #------------------------------------------------------Get Marked as Read Only
7738:
7739: sub get_marked_as_readonly {
7740: my ($domain,$user,$what,$group) = @_;
7741: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7742: my @readonly_files;
1.629 banghart 7743: my $cmp1=$what;
7744: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7745: while (my ($file_name,$value) = each(%{$current_permissions})) {
7746: if (defined($group)) {
7747: if ($file_name !~ m-^\Q$group\E/-) {
7748: next;
7749: }
7750: }
1.561 banghart 7751: if (ref($value) eq "ARRAY"){
7752: foreach my $stored_what (@{$value}) {
1.629 banghart 7753: my $cmp2=$stored_what;
1.759 albertel 7754: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7755: $cmp2=join('',@{$stored_what});
1.745 raeburn 7756: }
1.629 banghart 7757: if ($cmp1 eq $cmp2) {
1.561 banghart 7758: push(@readonly_files, $file_name);
1.745 raeburn 7759: last;
1.563 banghart 7760: } elsif (!defined($what)) {
7761: push(@readonly_files, $file_name);
1.745 raeburn 7762: last;
1.561 banghart 7763: }
7764: }
1.745 raeburn 7765: }
1.561 banghart 7766: }
7767: return @readonly_files;
7768: }
1.577 banghart 7769: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7770:
1.577 banghart 7771: sub get_marked_as_readonly_hash {
1.745 raeburn 7772: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7773: my %readonly_files;
1.745 raeburn 7774: while (my ($file_name,$value) = each(%{$current_permissions})) {
7775: if (defined($group)) {
7776: if ($file_name !~ m-^\Q$group\E/-) {
7777: next;
7778: }
7779: }
1.577 banghart 7780: if (ref($value) eq "ARRAY"){
7781: foreach my $stored_what (@{$value}) {
1.745 raeburn 7782: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7783: foreach my $lock_descriptor(@{$stored_what}) {
7784: if ($lock_descriptor eq 'graded') {
7785: $readonly_files{$file_name} = 'graded';
7786: } elsif ($lock_descriptor eq 'handback') {
7787: $readonly_files{$file_name} = 'handback';
7788: } else {
7789: if (!exists($readonly_files{$file_name})) {
7790: $readonly_files{$file_name} = 'locked';
7791: }
7792: }
1.745 raeburn 7793: }
1.750 banghart 7794: }
1.577 banghart 7795: }
7796: }
7797: }
7798: return %readonly_files;
7799: }
1.559 banghart 7800: # ------------------------------------------------------------ Unmark as Read Only
7801:
7802: sub unmark_as_readonly {
1.629 banghart 7803: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7804: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7805: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7806: $file_name = &declutter_portfile($file_name);
1.634 albertel 7807: my $symb_crs = $what;
7808: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7809: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7810: my ($tmp)=keys(%current_permissions);
7811: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7812: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7813: foreach my $file (@readonly_files) {
1.759 albertel 7814: my $clean_file = &declutter_portfile($file);
7815: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7816: my $current_locks = $current_permissions{$file};
1.563 banghart 7817: my @new_locks;
7818: my @del_keys;
7819: if (ref($current_locks) eq "ARRAY"){
7820: foreach my $locker (@{$current_locks}) {
1.632 albertel 7821: my $compare=$locker;
1.749 raeburn 7822: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7823: $compare=join('',@{$locker});
1.746 raeburn 7824: if ($compare ne $symb_crs) {
7825: push(@new_locks, $locker);
7826: }
1.563 banghart 7827: }
7828: }
1.650 albertel 7829: if (scalar(@new_locks) > 0) {
1.563 banghart 7830: $current_permissions{$file} = \@new_locks;
7831: } else {
7832: push(@del_keys, $file);
1.613 albertel 7833: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7834: delete($current_permissions{$file});
1.563 banghart 7835: }
7836: }
1.561 banghart 7837: }
1.613 albertel 7838: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7839: return;
7840: }
1.512 banghart 7841:
1.17 www 7842: # ------------------------------------------------------------ Directory lister
7843:
7844: sub dirlist {
1.955 raeburn 7845: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7846: $uri=~s/^\///;
7847: $uri=~s/\/$//;
1.253 stredwic 7848: my ($udom, $uname);
1.955 raeburn 7849: if ($getuserdir) {
1.253 stredwic 7850: $udom = $userdomain;
7851: $uname = $username;
1.955 raeburn 7852: } else {
7853: (undef,$udom,$uname)=split(/\//,$uri);
7854: if(defined($userdomain)) {
7855: $udom = $userdomain;
7856: }
7857: if(defined($username)) {
7858: $uname = $username;
7859: }
1.253 stredwic 7860: }
1.955 raeburn 7861: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7862:
1.955 raeburn 7863: $dirRoot = $perlvar{'lonDocRoot'};
7864: if (defined($getpropath)) {
7865: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7866: $dirRoot =~ s/\/$//;
1.955 raeburn 7867: } elsif (defined($getuserdir)) {
7868: my $subdir=$uname.'__';
7869: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7870: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7871: ."/$udom/$subdir/$uname";
7872: } elsif (defined($alternateRoot)) {
7873: $dirRoot = $alternateRoot;
1.751 banghart 7874: }
1.253 stredwic 7875:
7876: if($udom) {
7877: if($uname) {
1.955 raeburn 7878: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7879: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7880: .':'.&escape($uname).':'.&escape($udom),
7881: &homeserver($uname,$udom));
7882: if ($listing eq 'unknown_cmd') {
7883: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7884: &homeserver($uname,$udom));
7885: } else {
7886: @listing_results = map { &unescape($_); } split(/:/,$listing);
7887: }
1.605 matthew 7888: if ($listing eq 'unknown_cmd') {
1.800 albertel 7889: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7890: &homeserver($uname,$udom));
1.605 matthew 7891: @listing_results = split(/:/,$listing);
7892: } else {
7893: @listing_results = map { &unescape($_); } split(/:/,$listing);
7894: }
7895: return @listing_results;
1.955 raeburn 7896: } elsif(!$alternateRoot) {
1.800 albertel 7897: my %allusers;
1.841 albertel 7898: my %servers = &get_servers($udom,'library');
1.955 raeburn 7899: foreach my $tryserver (keys(%servers)) {
7900: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7901: &escape($udom),$tryserver);
7902: if ($listing eq 'unknown_cmd') {
7903: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7904: $udom, $tryserver);
7905: } else {
7906: @listing_results = map { &unescape($_); } split(/:/,$listing);
7907: }
1.841 albertel 7908: if ($listing eq 'unknown_cmd') {
7909: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7910: $udom, $tryserver);
7911: @listing_results = split(/:/,$listing);
7912: } else {
7913: @listing_results =
7914: map { &unescape($_); } split(/:/,$listing);
7915: }
7916: if ($listing_results[0] ne 'no_such_dir' &&
7917: $listing_results[0] ne 'empty' &&
7918: $listing_results[0] ne 'con_lost') {
7919: foreach my $line (@listing_results) {
7920: my ($entry) = split(/&/,$line,2);
7921: $allusers{$entry} = 1;
7922: }
7923: }
1.253 stredwic 7924: }
7925: my $alluserstr='';
1.800 albertel 7926: foreach my $user (sort(keys(%allusers))) {
7927: $alluserstr.=$user.'&user:';
1.253 stredwic 7928: }
7929: $alluserstr=~s/:$//;
7930: return split(/:/,$alluserstr);
7931: } else {
1.800 albertel 7932: return ('missing user name');
1.253 stredwic 7933: }
1.955 raeburn 7934: } elsif(!defined($getpropath)) {
1.841 albertel 7935: my @all_domains = sort(&all_domains());
1.955 raeburn 7936: foreach my $domain (@all_domains) {
7937: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7938: }
7939: return @all_domains;
7940: } else {
1.800 albertel 7941: return ('missing domain');
1.275 stredwic 7942: }
7943: }
7944:
7945: # --------------------------------------------- GetFileTimestamp
7946: # This function utilizes dirlist and returns the date stamp for
7947: # when it was last modified. It will also return an error of -1
7948: # if an error occurs
7949:
7950: sub GetFileTimestamp {
1.955 raeburn 7951: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7952: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7953: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7954: my ($fileStat) =
7955: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7956: undef,$getuserdir);
1.275 stredwic 7957: my @stats = split('&', $fileStat);
7958: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7959: # @stats contains first the filename, then the stat output
7960: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7961: } else {
7962: return -1;
1.253 stredwic 7963: }
1.26 www 7964: }
7965:
1.712 albertel 7966: sub stat_file {
7967: my ($uri) = @_;
1.787 albertel 7968: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7969:
1.955 raeburn 7970: my ($udom,$uname,$file);
1.712 albertel 7971: if ($uri =~ m-^/(uploaded|editupload)/-) {
7972: ($udom,$uname,$file) =
1.811 albertel 7973: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7974: $file = 'userfiles/'.$file;
7975: }
7976: if ($uri =~ m-^/res/-) {
7977: ($udom,$uname) =
1.807 albertel 7978: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7979: $file = $uri;
7980: }
7981:
7982: if (!$udom || !$uname || !$file) {
7983: # unable to handle the uri
7984: return ();
7985: }
1.956 raeburn 7986: my $getpropath;
7987: if ($file =~ /^userfiles\//) {
7988: $getpropath = 1;
7989: }
1.955 raeburn 7990: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7991: my @stats = split('&', $result);
1.721 banghart 7992:
1.712 albertel 7993: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7994: shift(@stats); #filename is first
7995: return @stats;
7996: }
7997: return ();
7998: }
7999:
1.26 www 8000: # -------------------------------------------------------- Value of a Condition
8001:
1.713 albertel 8002: # gets the value of a specific preevaluated condition
8003: # stored in the string $env{user.state.<cid>}
8004: # or looks up a condition reference in the bighash and if if hasn't
8005: # already been evaluated recurses into docondval to get the value of
8006: # the condition, then memoizing it to
8007: # $env{user.state.<cid>.<condition>}
1.40 www 8008: sub directcondval {
8009: my $number=shift;
1.620 albertel 8010: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8011: &Apache::lonuserstate::evalstate();
8012: }
1.713 albertel 8013: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8014: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8015: } elsif ($number =~ /^_/) {
8016: my $sub_condition;
8017: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8018: &GDBM_READER(),0640)) {
8019: $sub_condition=$bighash{'conditions'.$number};
8020: untie(%bighash);
8021: }
8022: my $value = &docondval($sub_condition);
1.949 raeburn 8023: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8024: return $value;
8025: }
1.620 albertel 8026: if ($env{'user.state.'.$env{'request.course.id'}}) {
8027: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8028: } else {
8029: return 2;
8030: }
8031: }
8032:
1.713 albertel 8033: # get the collection of conditions for this resource
1.26 www 8034: sub condval {
8035: my $condidx=shift;
1.54 www 8036: my $allpathcond='';
1.713 albertel 8037: foreach my $cond (split(/\|/,$condidx)) {
8038: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8039: $allpathcond.=
8040: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8041: }
1.191 harris41 8042: }
1.54 www 8043: $allpathcond=~s/\|$//;
1.713 albertel 8044: return &docondval($allpathcond);
8045: }
8046:
8047: #evaluates an expression of conditions
8048: sub docondval {
8049: my ($allpathcond) = @_;
8050: my $result=0;
8051: if ($env{'request.course.id'}
8052: && defined($allpathcond)) {
8053: my $operand='|';
8054: my @stack;
8055: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8056: if ($chunk eq '(') {
8057: push @stack,($operand,$result);
8058: } elsif ($chunk eq ')') {
8059: my $before=pop @stack;
8060: if (pop @stack eq '&') {
8061: $result=$result>$before?$before:$result;
8062: } else {
8063: $result=$result>$before?$result:$before;
8064: }
8065: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8066: $operand=$chunk;
8067: } else {
8068: my $new=directcondval($chunk);
8069: if ($operand eq '&') {
8070: $result=$result>$new?$new:$result;
8071: } else {
8072: $result=$result>$new?$result:$new;
8073: }
8074: }
8075: }
1.26 www 8076: }
8077: return $result;
1.421 albertel 8078: }
8079:
8080: # ---------------------------------------------------- Devalidate courseresdata
8081:
8082: sub devalidatecourseresdata {
8083: my ($coursenum,$coursedomain)=@_;
8084: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8085: &devalidate_cache_new('courseres',$hashid);
1.28 www 8086: }
8087:
1.763 www 8088:
1.200 www 8089: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8090: #
8091: # Parameters:
8092: # $coursenum - Number of the course.
8093: # $coursedomain - Domain at which the course was created.
8094: # Returns:
8095: # A hash of the course parameters along (I think) with timestamps
8096: # and version info.
1.877 foxr 8097:
1.624 albertel 8098: sub get_courseresdata {
8099: my ($coursenum,$coursedomain)=@_;
1.200 www 8100: my $coursehom=&homeserver($coursenum,$coursedomain);
8101: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8102: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8103: my %dumpreply;
1.417 albertel 8104: unless (defined($cached)) {
1.624 albertel 8105: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8106: $result=\%dumpreply;
1.251 albertel 8107: my ($tmp) = keys(%dumpreply);
8108: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8109: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8110: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8111: return $tmp;
1.416 albertel 8112: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8113: $result=undef;
1.599 albertel 8114: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8115: }
8116: }
1.624 albertel 8117: return $result;
8118: }
8119:
1.633 albertel 8120: sub devalidateuserresdata {
8121: my ($uname,$udom)=@_;
8122: my $hashid="$udom:$uname";
8123: &devalidate_cache_new('userres',$hashid);
8124: }
8125:
1.624 albertel 8126: sub get_userresdata {
8127: my ($uname,$udom)=@_;
8128: #most student don\'t have any data set, check if there is some data
8129: if (&EXT_cache_status($udom,$uname)) { return undef; }
8130:
8131: my $hashid="$udom:$uname";
8132: my ($result,$cached)=&is_cached_new('userres',$hashid);
8133: if (!defined($cached)) {
8134: my %resourcedata=&dump('resourcedata',$udom,$uname);
8135: $result=\%resourcedata;
8136: &do_cache_new('userres',$hashid,$result,600);
8137: }
8138: my ($tmp)=keys(%$result);
8139: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8140: return $result;
8141: }
8142: #error 2 occurs when the .db doesn't exist
8143: if ($tmp!~/error: 2 /) {
1.672 albertel 8144: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8145: " Trying to get resource data for ".
8146: $uname." at ".$udom.": ".
8147: $tmp."</font>");
8148: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8149: #&EXT_cache_set($udom,$uname);
8150: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8151: undef($tmp); # not really an error so don't send it back
1.624 albertel 8152: }
8153: return $tmp;
8154: }
1.879 foxr 8155: #----------------------------------------------- resdata - return resource data
8156: # Purpose:
8157: # Return resource data for either users or for a course.
8158: # Parameters:
8159: # $name - Course/user name.
8160: # $domain - Name of the domain the user/course is registered on.
8161: # $type - Type of thing $name is (must be 'course' or 'user'
8162: # @which - Array of names of resources desired.
8163: # Returns:
8164: # The value of the first reasource in @which that is found in the
8165: # resource hash.
8166: # Exceptional Conditions:
8167: # If the $type passed in is not valid (not the string 'course' or
8168: # 'user', an undefined reference is returned.
8169: # If none of the resources are found, an undef is returned
1.624 albertel 8170: sub resdata {
8171: my ($name,$domain,$type,@which)=@_;
8172: my $result;
8173: if ($type eq 'course') {
8174: $result=&get_courseresdata($name,$domain);
8175: } elsif ($type eq 'user') {
8176: $result=&get_userresdata($name,$domain);
8177: }
8178: if (!ref($result)) { return $result; }
1.251 albertel 8179: foreach my $item (@which) {
1.927 albertel 8180: if (defined($result->{$item->[0]})) {
8181: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8182: }
1.250 albertel 8183: }
1.291 albertel 8184: return undef;
1.200 www 8185: }
8186:
1.379 matthew 8187: #
8188: # EXT resource caching routines
8189: #
8190:
8191: sub clear_EXT_cache_status {
1.383 albertel 8192: &delenv('cache.EXT.');
1.379 matthew 8193: }
8194:
8195: sub EXT_cache_status {
8196: my ($target_domain,$target_user) = @_;
1.383 albertel 8197: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8198: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8199: # We know already the user has no data
8200: return 1;
8201: } else {
8202: return 0;
8203: }
8204: }
8205:
8206: sub EXT_cache_set {
8207: my ($target_domain,$target_user) = @_;
1.383 albertel 8208: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8209: #&appenv({$cachename => time});
1.379 matthew 8210: }
8211:
1.28 www 8212: # --------------------------------------------------------- Value of a Variable
1.58 www 8213: sub EXT {
1.715 albertel 8214:
1.395 albertel 8215: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8216: unless ($varname) { return ''; }
1.218 albertel 8217: #get real user name/domain, courseid and symb
8218: my $courseid;
1.359 albertel 8219: my $publicuser;
1.427 www 8220: if ($symbparm) {
8221: $symbparm=&get_symb_from_alias($symbparm);
8222: }
1.218 albertel 8223: if (!($uname && $udom)) {
1.790 albertel 8224: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8225: if (!$symbparm) { $symbparm=$cursymb; }
8226: } else {
1.620 albertel 8227: $courseid=$env{'request.course.id'};
1.218 albertel 8228: }
1.48 www 8229: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8230: my $rest;
1.320 albertel 8231: if (defined($therest[0])) {
1.48 www 8232: $rest=join('.',@therest);
8233: } else {
8234: $rest='';
8235: }
1.320 albertel 8236:
1.57 www 8237: my $qualifierrest=$qualifier;
8238: if ($rest) { $qualifierrest.='.'.$rest; }
8239: my $spacequalifierrest=$space;
8240: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8241: if ($realm eq 'user') {
1.48 www 8242: # --------------------------------------------------------------- user.resource
8243: if ($space eq 'resource') {
1.651 albertel 8244: if ( (defined($Apache::lonhomework::parsing_a_problem)
8245: || defined($Apache::lonhomework::parsing_a_task))
8246: &&
1.744 albertel 8247: ($symbparm eq &symbread()) ) {
8248: # if we are in the middle of processing the resource the
8249: # get the value we are planning on committing
8250: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8251: return $Apache::lonhomework::results{$qualifierrest};
8252: } else {
8253: return $Apache::lonhomework::history{$qualifierrest};
8254: }
1.335 albertel 8255: } else {
1.359 albertel 8256: my %restored;
1.620 albertel 8257: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8258: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8259: } else {
8260: %restored=&restore($symbparm,$courseid,$udom,$uname);
8261: }
1.335 albertel 8262: return $restored{$qualifierrest};
8263: }
1.48 www 8264: # ----------------------------------------------------------------- user.access
8265: } elsif ($space eq 'access') {
1.218 albertel 8266: # FIXME - not supporting calls for a specific user
1.48 www 8267: return &allowed($qualifier,$rest);
8268: # ------------------------------------------ user.preferences, user.environment
8269: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8270: if (($uname eq $env{'user.name'}) &&
8271: ($udom eq $env{'user.domain'})) {
8272: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8273: } else {
1.359 albertel 8274: my %returnhash;
8275: if (!$publicuser) {
8276: %returnhash=&userenvironment($udom,$uname,
8277: $qualifierrest);
8278: }
1.218 albertel 8279: return $returnhash{$qualifierrest};
8280: }
1.48 www 8281: # ----------------------------------------------------------------- user.course
8282: } elsif ($space eq 'course') {
1.218 albertel 8283: # FIXME - not supporting calls for a specific user
1.620 albertel 8284: return $env{join('.',('request.course',$qualifier))};
1.48 www 8285: # ------------------------------------------------------------------- user.role
8286: } elsif ($space eq 'role') {
1.218 albertel 8287: # FIXME - not supporting calls for a specific user
1.620 albertel 8288: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8289: if ($qualifier eq 'value') {
8290: return $role;
8291: } elsif ($qualifier eq 'extent') {
8292: return $where;
8293: }
8294: # ----------------------------------------------------------------- user.domain
8295: } elsif ($space eq 'domain') {
1.218 albertel 8296: return $udom;
1.48 www 8297: # ------------------------------------------------------------------- user.name
8298: } elsif ($space eq 'name') {
1.218 albertel 8299: return $uname;
1.48 www 8300: # ---------------------------------------------------- Any other user namespace
1.29 www 8301: } else {
1.359 albertel 8302: my %reply;
8303: if (!$publicuser) {
8304: %reply=&get($space,[$qualifierrest],$udom,$uname);
8305: }
8306: return $reply{$qualifierrest};
1.48 www 8307: }
1.236 www 8308: } elsif ($realm eq 'query') {
8309: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8310: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8311: [$spacequalifierrest]);
1.620 albertel 8312: return $env{'form.'.$spacequalifierrest};
1.236 www 8313: } elsif ($realm eq 'request') {
1.48 www 8314: # ------------------------------------------------------------- request.browser
8315: if ($space eq 'browser') {
1.430 www 8316: if ($qualifier eq 'textremote') {
1.676 albertel 8317: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8318: return 1;
8319: } else {
8320: return 0;
8321: }
8322: } else {
1.620 albertel 8323: return $env{'browser.'.$qualifier};
1.430 www 8324: }
1.57 www 8325: # ------------------------------------------------------------ request.filename
8326: } else {
1.620 albertel 8327: return $env{'request.'.$spacequalifierrest};
1.29 www 8328: }
1.28 www 8329: } elsif ($realm eq 'course') {
1.48 www 8330: # ---------------------------------------------------------- course.description
1.620 albertel 8331: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8332: } elsif ($realm eq 'resource') {
1.165 www 8333:
1.620 albertel 8334: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8335: if (!$symbparm) { $symbparm=&symbread(); }
8336: }
1.693 albertel 8337:
8338: if ($space eq 'title') {
8339: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8340: return &gettitle($symbparm);
8341: }
8342:
8343: if ($space eq 'map') {
8344: my ($map) = &decode_symb($symbparm);
8345: return &symbread($map);
8346: }
1.905 albertel 8347: if ($space eq 'filename') {
8348: if ($symbparm) {
8349: return &clutter((&decode_symb($symbparm))[2]);
8350: }
8351: return &hreflocation('',$env{'request.filename'});
8352: }
1.693 albertel 8353:
8354: my ($section, $group, @groups);
1.593 albertel 8355: my ($courselevelm,$courselevel);
1.539 albertel 8356: if ($symbparm && defined($courseid) &&
1.620 albertel 8357: $courseid eq $env{'request.course.id'}) {
1.165 www 8358:
1.218 albertel 8359: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8360:
1.60 www 8361: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8362: my $symbp=$symbparm;
1.735 albertel 8363: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8364:
8365: my $symbparm=$symbp.'.'.$spacequalifierrest;
8366: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8367:
1.620 albertel 8368: if (($env{'user.name'} eq $uname) &&
8369: ($env{'user.domain'} eq $udom)) {
8370: $section=$env{'request.course.sec'};
1.733 raeburn 8371: @groups = split(/:/,$env{'request.course.groups'});
8372: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8373: } else {
1.539 albertel 8374: if (! defined($usection)) {
1.551 albertel 8375: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8376: } else {
8377: $section = $usection;
8378: }
1.733 raeburn 8379: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8380: }
8381:
8382: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8383: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8384: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8385:
1.593 albertel 8386: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8387: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8388: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8389:
1.60 www 8390: # ----------------------------------------------------------- first, check user
1.624 albertel 8391:
8392: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8393: ([$courselevelr,'resource'],
8394: [$courselevelm,'map' ],
8395: [$courselevel, 'course' ]));
1.931 albertel 8396: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8397:
1.594 albertel 8398: # ------------------------------------------------ second, check some of course
1.684 raeburn 8399: my $coursereply;
1.691 raeburn 8400: if (@groups > 0) {
8401: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8402: $mapparm,$spacequalifierrest);
1.927 albertel 8403: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8404: }
1.96 www 8405:
1.684 raeburn 8406: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8407: $env{'course.'.$courseid.'.domain'},
8408: 'course',
8409: ([$seclevelr, 'resource'],
8410: [$seclevelm, 'map' ],
8411: [$seclevel, 'course' ],
8412: [$courselevelr,'resource']));
8413: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8414:
1.60 www 8415: # ------------------------------------------------------ third, check map parms
1.218 albertel 8416: my %parmhash=();
8417: my $thisparm='';
8418: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8419: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8420: &GDBM_READER(),0640)) {
1.218 albertel 8421: $thisparm=$parmhash{$symbparm};
8422: untie(%parmhash);
8423: }
1.927 albertel 8424: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8425: }
1.594 albertel 8426: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8427:
1.218 albertel 8428: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8429: my $filename;
8430: if (!$symbparm) { $symbparm=&symbread(); }
8431: if ($symbparm) {
1.409 www 8432: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8433: } else {
1.620 albertel 8434: $filename=$env{'request.filename'};
1.282 albertel 8435: }
8436: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8437: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8438: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8439: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8440:
1.927 albertel 8441: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8442: if ($symbparm && defined($courseid) &&
1.620 albertel 8443: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8444: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8445: $env{'course.'.$courseid.'.domain'},
8446: 'course',
1.927 albertel 8447: ([$courselevelm,'map' ],
8448: [$courselevel, 'course']));
8449: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8450: }
1.145 www 8451: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8452: unless ($space eq '0') {
1.336 albertel 8453: my @parts=split(/_/,$space);
8454: my $id=pop(@parts);
8455: my $part=join('_',@parts);
8456: if ($part eq '') { $part='0'; }
1.927 albertel 8457: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8458: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8459: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8460: }
1.395 albertel 8461: if ($recurse) { return undef; }
8462: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8463: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8464: # ---------------------------------------------------- Any other user namespace
8465: } elsif ($realm eq 'environment') {
8466: # ----------------------------------------------------------------- environment
1.620 albertel 8467: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8468: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8469: } else {
1.770 albertel 8470: if ($uname eq 'anonymous' && $udom eq '') {
8471: return '';
8472: }
1.219 albertel 8473: my %returnhash=&userenvironment($udom,$uname,
8474: $spacequalifierrest);
8475: return $returnhash{$spacequalifierrest};
8476: }
1.28 www 8477: } elsif ($realm eq 'system') {
1.48 www 8478: # ----------------------------------------------------------------- system.time
8479: if ($space eq 'time') {
8480: return time;
8481: }
1.696 albertel 8482: } elsif ($realm eq 'server') {
8483: # ----------------------------------------------------------------- system.time
8484: if ($space eq 'name') {
8485: return $ENV{'SERVER_NAME'};
8486: }
1.28 www 8487: }
1.48 www 8488: return '';
1.61 www 8489: }
8490:
1.927 albertel 8491: sub get_reply {
8492: my ($reply_value) = @_;
1.940 raeburn 8493: if (ref($reply_value) eq 'ARRAY') {
8494: if (wantarray) {
8495: return @$reply_value;
8496: }
8497: return $reply_value->[0];
8498: } else {
8499: return $reply_value;
1.927 albertel 8500: }
8501: }
8502:
1.691 raeburn 8503: sub check_group_parms {
8504: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8505: my @groupitems = ();
8506: my $resultitem;
1.927 albertel 8507: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8508: foreach my $group (@{$groups}) {
8509: foreach my $level (@levels) {
1.927 albertel 8510: my $item = $courseid.'.['.$group.'].'.$level->[0];
8511: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8512: }
8513: }
8514: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8515: $env{'course.'.$courseid.'.domain'},
8516: 'course',@groupitems);
8517: return $coursereply;
8518: }
8519:
8520: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8521: my ($courseid,@groups) = @_;
8522: @groups = sort(@groups);
1.691 raeburn 8523: return @groups;
8524: }
8525:
1.395 albertel 8526: sub packages_tab_default {
8527: my ($uri,$varname)=@_;
8528: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8529:
8530: my (@extension,@specifics,$do_default);
8531: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8532: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8533: if ($pack_type eq 'default') {
8534: $do_default=1;
8535: } elsif ($pack_type eq 'extension') {
8536: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8537: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8538: # only look at packages defaults for packages that this id is
1.738 albertel 8539: push(@specifics,[$package,$pack_type,$pack_part]);
8540: }
8541: }
8542: # first look for a package that matches the requested part id
8543: foreach my $package (@specifics) {
8544: my (undef,$pack_type,$pack_part)=@{$package};
8545: next if ($pack_part ne $part);
8546: if (defined($packagetab{"$pack_type&$name&default"})) {
8547: return $packagetab{"$pack_type&$name&default"};
8548: }
8549: }
8550: # look for any possible matching non extension_ package
8551: foreach my $package (@specifics) {
8552: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8553: if (defined($packagetab{"$pack_type&$name&default"})) {
8554: return $packagetab{"$pack_type&$name&default"};
8555: }
1.585 albertel 8556: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8557: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8558: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8559: }
8560: }
1.738 albertel 8561: # look for any posible extension_ match
8562: foreach my $package (@extension) {
8563: my ($package,$pack_type)=@{$package};
8564: if (defined($packagetab{"$pack_type&$name&default"})) {
8565: return $packagetab{"$pack_type&$name&default"};
8566: }
8567: if (defined($packagetab{$package."&$name&default"})) {
8568: return $packagetab{$package."&$name&default"};
8569: }
8570: }
8571: # look for a global default setting
8572: if ($do_default && defined($packagetab{"default&$name&default"})) {
8573: return $packagetab{"default&$name&default"};
8574: }
1.395 albertel 8575: return undef;
8576: }
8577:
1.334 albertel 8578: sub add_prefix_and_part {
8579: my ($prefix,$part)=@_;
8580: my $keyroot;
8581: if (defined($prefix) && $prefix !~ /^__/) {
8582: # prefix that has a part already
8583: $keyroot=$prefix;
8584: } elsif (defined($prefix)) {
8585: # prefix that is missing a part
8586: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8587: } else {
8588: # no prefix at all
8589: if (defined($part)) { $keyroot='_'.$part; }
8590: }
8591: return $keyroot;
8592: }
8593:
1.71 www 8594: # ---------------------------------------------------------------- Get metadata
8595:
1.599 albertel 8596: my %metaentry;
1.71 www 8597: sub metadata {
1.176 www 8598: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8599: $uri=&declutter($uri);
1.288 albertel 8600: # if it is a non metadata possible uri return quickly
1.529 albertel 8601: if (($uri eq '') ||
8602: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8603: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.20 raeburn 8604: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$}) || ($uri =~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.924 albertel 8605: return undef;
8606: }
8607: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8608: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8609: return undef;
1.288 albertel 8610: }
1.73 www 8611: my $filename=$uri;
8612: $uri=~s/\.meta$//;
1.172 www 8613: #
8614: # Is the metadata already cached?
1.177 www 8615: # Look at timestamp of caching
1.172 www 8616: # Everything is cached by the main uri, libraries are never directly cached
8617: #
1.428 albertel 8618: if (!defined($liburi)) {
1.599 albertel 8619: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8620: if (defined($cached)) { return $result->{':'.$what}; }
8621: }
8622: {
1.172 www 8623: #
8624: # Is this a recursive call for a library?
8625: #
1.599 albertel 8626: # if (! exists($metacache{$uri})) {
8627: # $metacache{$uri}={};
8628: # }
1.924 albertel 8629: my $cachetime = 60*60;
1.171 www 8630: if ($liburi) {
8631: $liburi=&declutter($liburi);
8632: $filename=$liburi;
1.401 bowersj2 8633: } else {
1.599 albertel 8634: &devalidate_cache_new('meta',$uri);
8635: undef(%metaentry);
1.401 bowersj2 8636: }
1.140 www 8637: my %metathesekeys=();
1.73 www 8638: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8639: my $metastring;
1.924 albertel 8640: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8641: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8642: $metastring =
1.929 albertel 8643: &Apache::lonnet::ssi_body($which,
1.924 albertel 8644: ('grade_target' => 'meta'));
8645: $cachetime = 1; # only want this cached in the child not long term
8646: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8647: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8648: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8649: $metastring=&getfile($file);
1.489 albertel 8650: }
1.208 albertel 8651: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8652: my $token;
1.140 www 8653: undef %metathesekeys;
1.71 www 8654: while ($token=$parser->get_token) {
1.339 albertel 8655: if ($token->[0] eq 'S') {
8656: if (defined($token->[2]->{'package'})) {
1.172 www 8657: #
8658: # This is a package - get package info
8659: #
1.339 albertel 8660: my $package=$token->[2]->{'package'};
8661: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8662: if (defined($token->[2]->{'id'})) {
8663: $keyroot.='_'.$token->[2]->{'id'};
8664: }
1.599 albertel 8665: if ($metaentry{':packages'}) {
8666: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8667: } else {
1.599 albertel 8668: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8669: }
1.736 albertel 8670: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8671: my $part=$keyroot;
8672: $part=~s/^\_//;
1.736 albertel 8673: if ($pack_entry=~/^\Q$package\E\&/ ||
8674: $pack_entry=~/^\Q$package\E_0\&/) {
8675: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8676: # ignore package.tab specified default values
8677: # here &package_tab_default() will fetch those
8678: if ($subp eq 'default') { next; }
1.736 albertel 8679: my $value=$packagetab{$pack_entry};
1.432 albertel 8680: my $unikey;
8681: if ($pack =~ /_0$/) {
8682: $unikey='parameter_0_'.$name;
8683: $part=0;
8684: } else {
8685: $unikey='parameter'.$keyroot.'_'.$name;
8686: }
1.339 albertel 8687: if ($subp eq 'display') {
8688: $value.=' [Part: '.$part.']';
8689: }
1.599 albertel 8690: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8691: $metathesekeys{$unikey}=1;
1.599 albertel 8692: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8693: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8694: }
1.599 albertel 8695: if (defined($metaentry{':'.$unikey.'.default'})) {
8696: $metaentry{':'.$unikey}=
8697: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8698: }
1.339 albertel 8699: }
8700: }
8701: } else {
1.172 www 8702: #
8703: # This is not a package - some other kind of start tag
1.339 albertel 8704: #
8705: my $entry=$token->[1];
8706: my $unikey;
8707: if ($entry eq 'import') {
8708: $unikey='';
8709: } else {
8710: $unikey=$entry;
8711: }
8712: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8713:
8714: if (defined($token->[2]->{'id'})) {
8715: $unikey.='_'.$token->[2]->{'id'};
8716: }
1.175 www 8717:
1.339 albertel 8718: if ($entry eq 'import') {
1.175 www 8719: #
8720: # Importing a library here
1.339 albertel 8721: #
8722: if ($depthcount<20) {
8723: my $location=$parser->get_text('/import');
8724: my $dir=$filename;
8725: $dir=~s|[^/]*$||;
8726: $location=&filelocation($dir,$location);
1.736 albertel 8727: my $metadata =
8728: &metadata($uri,'keys', $location,$unikey,
8729: $depthcount+1);
8730: foreach my $meta (split(',',$metadata)) {
8731: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8732: $metathesekeys{$meta}=1;
1.339 albertel 8733: }
8734: }
8735: } else {
8736: if (defined($token->[2]->{'name'})) {
8737: $unikey.='_'.$token->[2]->{'name'};
8738: }
8739: $metathesekeys{$unikey}=1;
1.736 albertel 8740: foreach my $param (@{$token->[3]}) {
8741: $metaentry{':'.$unikey.'.'.$param} =
8742: $token->[2]->{$param};
1.339 albertel 8743: }
8744: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8745: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8746: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8747: # only ws inside the tag, and not in default, so use default
8748: # as value
1.599 albertel 8749: $metaentry{':'.$unikey}=$default;
1.908 albertel 8750: } elsif ( $internaltext =~ /\S/ ) {
8751: # something interesting inside the tag
8752: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8753: } else {
1.908 albertel 8754: # no interesting values, don't set a default
1.339 albertel 8755: }
1.172 www 8756: # end of not-a-package not-a-library import
1.339 albertel 8757: }
1.172 www 8758: # end of not-a-package start tag
1.339 albertel 8759: }
1.172 www 8760: # the next is the end of "start tag"
1.339 albertel 8761: }
8762: }
1.483 albertel 8763: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8764: $extension = lc($extension);
8765: if ($extension eq 'htm') { $extension='html'; }
8766:
1.737 albertel 8767: foreach my $key (keys(%packagetab)) {
1.483 albertel 8768: #no specific packages #how's our extension
8769: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8770: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8771: \%metathesekeys);
8772: }
1.883 albertel 8773:
8774: if (!exists($metaentry{':packages'})
8775: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8776: foreach my $key (keys(%packagetab)) {
1.483 albertel 8777: #no specific packages well let's get default then
8778: if ($key!~/^default&/) { next; }
1.488 albertel 8779: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8780: \%metathesekeys);
8781: }
8782: }
1.338 www 8783: # are there custom rights to evaluate
1.599 albertel 8784: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8785:
1.338 www 8786: #
8787: # Importing a rights file here
1.339 albertel 8788: #
8789: unless ($depthcount) {
1.599 albertel 8790: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8791: my $dir=$filename;
8792: $dir=~s|[^/]*$||;
8793: $location=&filelocation($dir,$location);
1.736 albertel 8794: my $rights_metadata =
8795: &metadata($uri,'keys',$location,'_rights',
8796: $depthcount+1);
8797: foreach my $rights (split(',',$rights_metadata)) {
8798: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8799: $metathesekeys{$rights}=1;
1.339 albertel 8800: }
8801: }
8802: }
1.737 albertel 8803: # uniqifiy package listing
8804: my %seen;
8805: my @uniq_packages =
8806: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8807: $metaentry{':packages'} = join(',',@uniq_packages);
8808:
8809: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8810: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8811: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8812: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8813: # this is the end of "was not already recently cached
1.71 www 8814: }
1.599 albertel 8815: return $metaentry{':'.$what};
1.261 albertel 8816: }
8817:
1.488 albertel 8818: sub metadata_create_package_def {
1.483 albertel 8819: my ($uri,$key,$package,$metathesekeys)=@_;
8820: my ($pack,$name,$subp)=split(/\&/,$key);
8821: if ($subp eq 'default') { next; }
8822:
1.599 albertel 8823: if (defined($metaentry{':packages'})) {
8824: $metaentry{':packages'}.=','.$package;
1.483 albertel 8825: } else {
1.599 albertel 8826: $metaentry{':packages'}=$package;
1.483 albertel 8827: }
8828: my $value=$packagetab{$key};
8829: my $unikey;
8830: $unikey='parameter_0_'.$name;
1.599 albertel 8831: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8832: $$metathesekeys{$unikey}=1;
1.599 albertel 8833: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8834: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8835: }
1.599 albertel 8836: if (defined($metaentry{':'.$unikey.'.default'})) {
8837: $metaentry{':'.$unikey}=
8838: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8839: }
8840: }
8841:
1.261 albertel 8842: sub metadata_generate_part0 {
8843: my ($metadata,$metacache,$uri) = @_;
8844: my %allnames;
1.737 albertel 8845: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8846: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8847: my $part=$$metacache{':'.$metakey.'.part'};
8848: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8849: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8850: $allnames{$name}=$part;
8851: }
8852: }
8853: }
8854: foreach my $name (keys(%allnames)) {
8855: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8856: my $key=":parameter_0_$name";
1.261 albertel 8857: $$metacache{"$key.part"}='0';
8858: $$metacache{"$key.name"}=$name;
1.428 albertel 8859: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8860: $allnames{$name}.'_'.$name.
8861: '.type'};
1.428 albertel 8862: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8863: '.display'};
1.644 www 8864: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8865: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8866: $$metacache{"$key.display"}=$olddis;
8867: }
1.71 www 8868: }
8869:
1.764 albertel 8870: # ------------------------------------------------------ Devalidate title cache
8871:
8872: sub devalidate_title_cache {
8873: my ($url)=@_;
8874: if (!$env{'request.course.id'}) { return; }
8875: my $symb=&symbread($url);
8876: if (!$symb) { return; }
8877: my $key=$env{'request.course.id'}."\0".$symb;
8878: &devalidate_cache_new('title',$key);
8879: }
8880:
1.1014 droeschl 8881: # ------------------------------------------------- Get the title of a course
8882:
8883: sub current_course_title {
8884: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8885: }
1.301 www 8886: # ------------------------------------------------- Get the title of a resource
8887:
8888: sub gettitle {
8889: my $urlsymb=shift;
8890: my $symb=&symbread($urlsymb);
1.534 albertel 8891: if ($symb) {
1.620 albertel 8892: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8893: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8894: if (defined($cached)) {
8895: return $result;
8896: }
1.534 albertel 8897: my ($map,$resid,$url)=&decode_symb($symb);
8898: my $title='';
1.907 albertel 8899: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8900: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8901: } else {
8902: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8903: &GDBM_READER(),0640)) {
8904: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8905: $title=$bighash{'title_'.$mapid.'.'.$resid};
8906: untie(%bighash);
8907: }
1.534 albertel 8908: }
8909: $title=~s/\&colon\;/\:/gs;
8910: if ($title) {
1.599 albertel 8911: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8912: }
8913: $urlsymb=$url;
8914: }
8915: my $title=&metadata($urlsymb,'title');
8916: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8917: return $title;
1.301 www 8918: }
1.613 albertel 8919:
1.614 albertel 8920: sub get_slot {
8921: my ($which,$cnum,$cdom)=@_;
8922: if (!$cnum || !$cdom) {
1.790 albertel 8923: (undef,my $courseid)=&whichuser();
1.620 albertel 8924: $cdom=$env{'course.'.$courseid.'.domain'};
8925: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8926: }
1.703 albertel 8927: my $key=join("\0",'slots',$cdom,$cnum,$which);
8928: my %slotinfo;
8929: if (exists($remembered{$key})) {
8930: $slotinfo{$which} = $remembered{$key};
8931: } else {
8932: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8933: &Apache::lonhomework::showhash(%slotinfo);
8934: my ($tmp)=keys(%slotinfo);
8935: if ($tmp=~/^error:/) { return (); }
8936: $remembered{$key} = $slotinfo{$which};
8937: }
1.616 albertel 8938: if (ref($slotinfo{$which}) eq 'HASH') {
8939: return %{$slotinfo{$which}};
8940: }
8941: return $slotinfo{$which};
1.614 albertel 8942: }
1.31 www 8943: # ------------------------------------------------- Update symbolic store links
8944:
8945: sub symblist {
8946: my ($mapname,%newhash)=@_;
1.438 www 8947: $mapname=&deversion(&declutter($mapname));
1.31 www 8948: my %hash;
1.620 albertel 8949: if (($env{'request.course.fn'}) && (%newhash)) {
8950: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8951: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8952: foreach my $url (keys(%newhash)) {
1.711 albertel 8953: next if ($url eq 'last_known'
8954: && $env{'form.no_update_last_known'});
8955: $hash{declutter($url)}=&encode_symb($mapname,
8956: $newhash{$url}->[1],
8957: $newhash{$url}->[0]);
1.191 harris41 8958: }
1.31 www 8959: if (untie(%hash)) {
8960: return 'ok';
8961: }
8962: }
8963: }
8964: return 'error';
1.212 www 8965: }
8966:
8967: # --------------------------------------------------------------- Verify a symb
8968:
8969: sub symbverify {
1.510 www 8970: my ($symb,$thisurl)=@_;
8971: my $thisfn=$thisurl;
1.439 www 8972: $thisfn=&declutter($thisfn);
1.215 www 8973: # direct jump to resource in page or to a sequence - will construct own symbs
8974: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8975: # check URL part
1.409 www 8976: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8977:
1.431 www 8978: unless ($url eq $thisfn) { return 0; }
1.213 www 8979:
1.216 www 8980: $symb=&symbclean($symb);
1.510 www 8981: $thisurl=&deversion($thisurl);
1.439 www 8982: $thisfn=&deversion($thisfn);
1.213 www 8983:
8984: my %bighash;
8985: my $okay=0;
1.431 www 8986:
1.620 albertel 8987: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8988: &GDBM_READER(),0640)) {
1.1032 raeburn 8989: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8990: $thisurl =~ s/\?.+$//;
8991: }
1.510 www 8992: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8993: unless ($ids) {
1.1056.4.21 raeburn 8994: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
8995: $ids=$bighash{$idkey};
1.216 www 8996: }
8997: if ($ids) {
8998: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8999: foreach my $id (split(/\,/,$ids)) {
9000: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9001: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9002: $symb =~ s/\?.+$//;
9003: }
1.216 www 9004: if (
9005: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9006: eq $symb) {
1.620 albertel 9007: if (($env{'request.role.adv'}) ||
1.1056.4.20 raeburn 9008: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9009: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9010: $okay=1;
9011: }
9012: }
1.216 www 9013: }
9014: }
1.213 www 9015: untie(%bighash);
9016: }
9017: return $okay;
1.31 www 9018: }
9019:
1.210 www 9020: # --------------------------------------------------------------- Clean-up symb
9021:
9022: sub symbclean {
9023: my $symb=shift;
1.568 albertel 9024: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9025: # remove version from map
9026: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9027:
1.210 www 9028: # remove version from URL
9029: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9030:
1.507 www 9031: # remove wrapper
9032:
1.510 www 9033: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9034: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9035: return $symb;
1.409 www 9036: }
9037:
9038: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9039:
9040: sub encode_symb {
9041: my ($map,$resid,$url)=@_;
9042: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9043: }
1.409 www 9044:
9045: sub decode_symb {
1.568 albertel 9046: my $symb=shift;
9047: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9048: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9049: return (&fixversion($map),$resid,&fixversion($url));
9050: }
9051:
9052: sub fixversion {
9053: my $fn=shift;
1.609 banghart 9054: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9055: my %bighash;
9056: my $uri=&clutter($fn);
1.620 albertel 9057: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9058: # is this cached?
1.599 albertel 9059: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9060: if (defined($cached)) { return $result; }
9061: # unfortunately not cached, or expired
1.620 albertel 9062: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9063: &GDBM_READER(),0640)) {
9064: if ($bighash{'version_'.$uri}) {
9065: my $version=$bighash{'version_'.$uri};
1.444 www 9066: unless (($version eq 'mostrecent') ||
9067: ($version==&getversion($uri))) {
1.440 www 9068: $uri=~s/\.(\w+)$/\.$version\.$1/;
9069: }
9070: }
9071: untie %bighash;
1.413 www 9072: }
1.599 albertel 9073: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9074: }
9075:
9076: sub deversion {
9077: my $url=shift;
9078: $url=~s/\.\d+\.(\w+)$/\.$1/;
9079: return $url;
1.210 www 9080: }
9081:
1.31 www 9082: # ------------------------------------------------------ Return symb list entry
9083:
9084: sub symbread {
1.249 www 9085: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9086: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9087: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9088: # no filename provided? try from environment
1.44 www 9089: unless ($thisfn) {
1.620 albertel 9090: if ($env{'request.symb'}) {
9091: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9092: }
1.620 albertel 9093: $thisfn=$env{'request.filename'};
1.44 www 9094: }
1.569 albertel 9095: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9096: # is that filename actually a symb? Verify, clean, and return
9097: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9098: if (&symbverify($thisfn,$1)) {
1.620 albertel 9099: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9100: }
1.242 www 9101: }
1.44 www 9102: $thisfn=declutter($thisfn);
1.31 www 9103: my %hash;
1.37 www 9104: my %bighash;
9105: my $syval='';
1.620 albertel 9106: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9107: my $targetfn = $thisfn;
1.609 banghart 9108: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9109: $targetfn = 'adm/wrapper/'.$thisfn;
9110: }
1.687 albertel 9111: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9112: $targetfn=$1;
9113: }
1.620 albertel 9114: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9115: &GDBM_READER(),0640)) {
1.481 raeburn 9116: $syval=$hash{$targetfn};
1.37 www 9117: untie(%hash);
9118: }
9119: # ---------------------------------------------------------- There was an entry
9120: if ($syval) {
1.601 albertel 9121: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9122: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9123: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9124: #return $env{$cache_str}='';
1.601 albertel 9125: #}
9126: #$syval.=$1;
9127: #}
1.37 www 9128: } else {
9129: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9130: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9131: &GDBM_READER(),0640)) {
1.37 www 9132: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9133: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9134: unless ($ids) {
9135: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9136: }
9137: unless ($ids) {
9138: # alias?
9139: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9140: }
1.37 www 9141: if ($ids) {
9142: # ------------------------------------------------------------------- Has ID(s)
9143: my @possibilities=split(/\,/,$ids);
1.39 www 9144: if ($#possibilities==0) {
9145: # ----------------------------------------------- There is only one possibility
1.37 www 9146: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9147: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9148: $resid,$thisfn);
1.249 www 9149: } elsif (!$donotrecurse) {
1.39 www 9150: # ------------------------------------------ There is more than one possibility
9151: my $realpossible=0;
1.800 albertel 9152: foreach my $id (@possibilities) {
9153: my $file=$bighash{'src_'.$id};
1.39 www 9154: if (&allowed('bre',$file)) {
1.800 albertel 9155: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9156: if ($bighash{'map_type_'.$mapid} ne 'page') {
9157: $realpossible++;
1.626 albertel 9158: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9159: $resid,$thisfn);
1.39 www 9160: }
9161: }
1.191 harris41 9162: }
1.39 www 9163: if ($realpossible!=1) { $syval=''; }
1.249 www 9164: } else {
9165: $syval='';
1.37 www 9166: }
9167: }
9168: untie(%bighash)
1.481 raeburn 9169: }
1.31 www 9170: }
1.62 www 9171: if ($syval) {
1.620 albertel 9172: return $env{$cache_str}=$syval;
1.62 www 9173: }
1.31 www 9174: }
1.949 raeburn 9175: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9176: return $env{$cache_str}='';
1.31 www 9177: }
9178:
9179: # ---------------------------------------------------------- Return random seed
9180:
1.32 www 9181: sub numval {
9182: my $txt=shift;
9183: $txt=~tr/A-J/0-9/;
9184: $txt=~tr/a-j/0-9/;
9185: $txt=~tr/K-T/0-9/;
9186: $txt=~tr/k-t/0-9/;
9187: $txt=~tr/U-Z/0-5/;
9188: $txt=~tr/u-z/0-5/;
9189: $txt=~s/\D//g;
1.564 albertel 9190: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9191: return int($txt);
1.368 albertel 9192: }
9193:
1.484 albertel 9194: sub numval2 {
9195: my $txt=shift;
9196: $txt=~tr/A-J/0-9/;
9197: $txt=~tr/a-j/0-9/;
9198: $txt=~tr/K-T/0-9/;
9199: $txt=~tr/k-t/0-9/;
9200: $txt=~tr/U-Z/0-5/;
9201: $txt=~tr/u-z/0-5/;
9202: $txt=~s/\D//g;
9203: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9204: my $total;
9205: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9206: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9207: return int($total);
9208: }
9209:
1.575 albertel 9210: sub numval3 {
9211: use integer;
9212: my $txt=shift;
9213: $txt=~tr/A-J/0-9/;
9214: $txt=~tr/a-j/0-9/;
9215: $txt=~tr/K-T/0-9/;
9216: $txt=~tr/k-t/0-9/;
9217: $txt=~tr/U-Z/0-5/;
9218: $txt=~tr/u-z/0-5/;
9219: $txt=~s/\D//g;
9220: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9221: my $total;
9222: foreach my $val (@txts) { $total+=$val; }
9223: if ($_64bit) { $total=(($total<<32)>>32); }
9224: return $total;
9225: }
9226:
1.675 albertel 9227: sub digest {
9228: my ($data)=@_;
9229: my $digest=&Digest::MD5::md5($data);
9230: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9231: my ($e,$f);
9232: {
9233: use integer;
9234: $e=($a+$b);
9235: $f=($c+$d);
9236: if ($_64bit) {
9237: $e=(($e<<32)>>32);
9238: $f=(($f<<32)>>32);
9239: }
9240: }
9241: if (wantarray) {
9242: return ($e,$f);
9243: } else {
9244: my $g;
9245: {
9246: use integer;
9247: $g=($e+$f);
9248: if ($_64bit) {
9249: $g=(($g<<32)>>32);
9250: }
9251: }
9252: return $g;
9253: }
9254: }
9255:
1.368 albertel 9256: sub latest_rnd_algorithm_id {
1.675 albertel 9257: return '64bit5';
1.366 albertel 9258: }
1.32 www 9259:
1.503 albertel 9260: sub get_rand_alg {
9261: my ($courseid)=@_;
1.790 albertel 9262: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9263: if ($courseid) {
1.620 albertel 9264: return $env{"course.$courseid.rndseed"};
1.503 albertel 9265: }
9266: return &latest_rnd_algorithm_id();
9267: }
9268:
1.562 albertel 9269: sub validCODE {
9270: my ($CODE)=@_;
9271: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9272: return 0;
9273: }
9274:
1.491 albertel 9275: sub getCODE {
1.620 albertel 9276: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9277: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9278: defined($Apache::lonhomework::parsing_a_task) ) &&
9279: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9280: return $Apache::lonhomework::history{'resource.CODE'};
9281: }
9282: return undef;
9283: }
9284:
1.31 www 9285: sub rndseed {
1.155 albertel 9286: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9287: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9288: if (!defined($symb)) {
1.366 albertel 9289: unless ($symb=$wsymb) { return time; }
9290: }
9291: if (!$courseid) { $courseid=$wcourseid; }
9292: if (!$domain) { $domain=$wdomain; }
9293: if (!$username) { $username=$wusername }
1.503 albertel 9294: my $which=&get_rand_alg();
1.803 albertel 9295:
1.491 albertel 9296: if (defined(&getCODE())) {
1.675 albertel 9297: if ($which eq '64bit5') {
9298: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9299: } elsif ($which eq '64bit4') {
1.575 albertel 9300: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9301: } else {
9302: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9303: }
1.675 albertel 9304: } elsif ($which eq '64bit5') {
9305: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9306: } elsif ($which eq '64bit4') {
9307: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9308: } elsif ($which eq '64bit3') {
9309: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9310: } elsif ($which eq '64bit2') {
9311: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9312: } elsif ($which eq '64bit') {
9313: return &rndseed_64bit($symb,$courseid,$domain,$username);
9314: }
9315: return &rndseed_32bit($symb,$courseid,$domain,$username);
9316: }
9317:
9318: sub rndseed_32bit {
9319: my ($symb,$courseid,$domain,$username)=@_;
9320: {
9321: use integer;
9322: my $symbchck=unpack("%32C*",$symb) << 27;
9323: my $symbseed=numval($symb) << 22;
9324: my $namechck=unpack("%32C*",$username) << 17;
9325: my $nameseed=numval($username) << 12;
9326: my $domainseed=unpack("%32C*",$domain) << 7;
9327: my $courseseed=unpack("%32C*",$courseid);
9328: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9329: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9330: #&logthis("rndseed :$num:$symb");
1.564 albertel 9331: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9332: return $num;
9333: }
9334: }
9335:
9336: sub rndseed_64bit {
9337: my ($symb,$courseid,$domain,$username)=@_;
9338: {
9339: use integer;
9340: my $symbchck=unpack("%32S*",$symb) << 21;
9341: my $symbseed=numval($symb) << 10;
9342: my $namechck=unpack("%32S*",$username);
9343:
9344: my $nameseed=numval($username) << 21;
9345: my $domainseed=unpack("%32S*",$domain) << 10;
9346: my $courseseed=unpack("%32S*",$courseid);
9347:
9348: my $num1=$symbchck+$symbseed+$namechck;
9349: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9350: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9351: #&logthis("rndseed :$num:$symb");
1.564 albertel 9352: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9353: return "$num1,$num2";
1.155 albertel 9354: }
1.366 albertel 9355: }
9356:
1.443 albertel 9357: sub rndseed_64bit2 {
9358: my ($symb,$courseid,$domain,$username)=@_;
9359: {
9360: use integer;
9361: # strings need to be an even # of cahracters long, it it is odd the
9362: # last characters gets thrown away
9363: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9364: my $symbseed=numval($symb) << 10;
9365: my $namechck=unpack("%32S*",$username.' ');
9366:
9367: my $nameseed=numval($username) << 21;
1.501 albertel 9368: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9369: my $courseseed=unpack("%32S*",$courseid.' ');
9370:
9371: my $num1=$symbchck+$symbseed+$namechck;
9372: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9373: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9374: #&logthis("rndseed :$num:$symb");
1.803 albertel 9375: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9376: return "$num1,$num2";
9377: }
9378: }
9379:
9380: sub rndseed_64bit3 {
9381: my ($symb,$courseid,$domain,$username)=@_;
9382: {
9383: use integer;
9384: # strings need to be an even # of cahracters long, it it is odd the
9385: # last characters gets thrown away
9386: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9387: my $symbseed=numval2($symb) << 10;
9388: my $namechck=unpack("%32S*",$username.' ');
9389:
9390: my $nameseed=numval2($username) << 21;
1.443 albertel 9391: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9392: my $courseseed=unpack("%32S*",$courseid.' ');
9393:
9394: my $num1=$symbchck+$symbseed+$namechck;
9395: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9396: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9397: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9398: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9399:
1.503 albertel 9400: return "$num1:$num2";
1.443 albertel 9401: }
9402: }
9403:
1.575 albertel 9404: sub rndseed_64bit4 {
9405: my ($symb,$courseid,$domain,$username)=@_;
9406: {
9407: use integer;
9408: # strings need to be an even # of cahracters long, it it is odd the
9409: # last characters gets thrown away
9410: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9411: my $symbseed=numval3($symb) << 10;
9412: my $namechck=unpack("%32S*",$username.' ');
9413:
9414: my $nameseed=numval3($username) << 21;
9415: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9416: my $courseseed=unpack("%32S*",$courseid.' ');
9417:
9418: my $num1=$symbchck+$symbseed+$namechck;
9419: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9420: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9421: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9422: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9423:
9424: return "$num1:$num2";
9425: }
9426: }
9427:
1.675 albertel 9428: sub rndseed_64bit5 {
9429: my ($symb,$courseid,$domain,$username)=@_;
9430: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9431: return "$num1:$num2";
9432: }
9433:
1.366 albertel 9434: sub rndseed_CODE_64bit {
9435: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9436: {
1.366 albertel 9437: use integer;
1.443 albertel 9438: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9439: my $symbseed=numval2($symb);
1.491 albertel 9440: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9441: my $CODEseed=numval(&getCODE());
1.443 albertel 9442: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9443: my $num1=$symbseed+$CODEchck;
9444: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9445: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9446: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9447: if ($_64bit) { $num1=(($num1<<32)>>32); }
9448: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9449: return "$num1:$num2";
1.366 albertel 9450: }
9451: }
9452:
1.575 albertel 9453: sub rndseed_CODE_64bit4 {
9454: my ($symb,$courseid,$domain,$username)=@_;
9455: {
9456: use integer;
9457: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9458: my $symbseed=numval3($symb);
9459: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9460: my $CODEseed=numval3(&getCODE());
9461: my $courseseed=unpack("%32S*",$courseid.' ');
9462: my $num1=$symbseed+$CODEchck;
9463: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9464: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9465: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9466: if ($_64bit) { $num1=(($num1<<32)>>32); }
9467: if ($_64bit) { $num2=(($num2<<32)>>32); }
9468: return "$num1:$num2";
9469: }
9470: }
9471:
1.675 albertel 9472: sub rndseed_CODE_64bit5 {
9473: my ($symb,$courseid,$domain,$username)=@_;
9474: my $code = &getCODE();
9475: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9476: return "$num1:$num2";
9477: }
9478:
1.366 albertel 9479: sub setup_random_from_rndseed {
9480: my ($rndseed)=@_;
1.503 albertel 9481: if ($rndseed =~/([,:])/) {
9482: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9483: &Math::Random::random_set_seed(abs($num1),abs($num2));
9484: } else {
9485: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9486: }
1.36 albertel 9487: }
9488:
1.474 albertel 9489: sub latest_receipt_algorithm_id {
1.835 albertel 9490: return 'receipt3';
1.474 albertel 9491: }
9492:
1.480 www 9493: sub recunique {
9494: my $fucourseid=shift;
9495: my $unique;
1.835 albertel 9496: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9497: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9498: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9499: } else {
9500: $unique=$perlvar{'lonReceipt'};
9501: }
9502: return unpack("%32C*",$unique);
9503: }
9504:
9505: sub recprefix {
9506: my $fucourseid=shift;
9507: my $prefix;
1.835 albertel 9508: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9509: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9510: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9511: } else {
9512: $prefix=$perlvar{'lonHostID'};
9513: }
9514: return unpack("%32C*",$prefix);
9515: }
9516:
1.76 www 9517: sub ireceipt {
1.474 albertel 9518: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9519:
9520: my $return =&recprefix($fucourseid).'-';
9521:
9522: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9523: $env{'request.state'} eq 'construct') {
9524: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9525: return $return;
9526: }
9527:
1.76 www 9528: my $cuname=unpack("%32C*",$funame);
9529: my $cudom=unpack("%32C*",$fudom);
9530: my $cucourseid=unpack("%32C*",$fucourseid);
9531: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9532: my $cunique=&recunique($fucourseid);
1.474 albertel 9533: my $cpart=unpack("%32S*",$part);
1.835 albertel 9534: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9535:
1.790 albertel 9536: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9537:
9538: $return.= ($cunique%$cuname+
9539: $cunique%$cudom+
9540: $cusymb%$cuname+
9541: $cusymb%$cudom+
9542: $cucourseid%$cuname+
9543: $cucourseid%$cudom+
9544: $cpart%$cuname+
9545: $cpart%$cudom);
9546: } else {
9547: $return.= ($cunique%$cuname+
9548: $cunique%$cudom+
9549: $cusymb%$cuname+
9550: $cusymb%$cudom+
9551: $cucourseid%$cuname+
9552: $cucourseid%$cudom);
9553: }
9554: return $return;
1.76 www 9555: }
9556:
9557: sub receipt {
1.474 albertel 9558: my ($part)=@_;
1.790 albertel 9559: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9560: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9561: }
1.260 ng 9562:
1.790 albertel 9563: sub whichuser {
9564: my ($passedsymb)=@_;
9565: my ($symb,$courseid,$domain,$name,$publicuser);
9566: if (defined($env{'form.grade_symb'})) {
9567: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9568: my $allowed=&allowed('vgr',$tmp_courseid);
9569: if (!$allowed &&
9570: exists($env{'request.course.sec'}) &&
9571: $env{'request.course.sec'} !~ /^\s*$/) {
9572: $allowed=&allowed('vgr',$tmp_courseid.
9573: '/'.$env{'request.course.sec'});
9574: }
9575: if ($allowed) {
9576: ($symb)=&get_env_multiple('form.grade_symb');
9577: $courseid=$tmp_courseid;
9578: ($domain)=&get_env_multiple('form.grade_domain');
9579: ($name)=&get_env_multiple('form.grade_username');
9580: return ($symb,$courseid,$domain,$name,$publicuser);
9581: }
9582: }
9583: if (!$passedsymb) {
9584: $symb=&symbread();
9585: } else {
9586: $symb=$passedsymb;
9587: }
9588: $courseid=$env{'request.course.id'};
9589: $domain=$env{'user.domain'};
9590: $name=$env{'user.name'};
9591: if ($name eq 'public' && $domain eq 'public') {
9592: if (!defined($env{'form.username'})) {
9593: $env{'form.username'}.=time.rand(10000000);
9594: }
9595: $name.=$env{'form.username'};
9596: }
9597: return ($symb,$courseid,$domain,$name,$publicuser);
9598:
9599: }
9600:
1.36 albertel 9601: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9602: # returns either the contents of the file or
9603: # -1 if the file doesn't exist
1.481 raeburn 9604: #
9605: # if the target is a file that was uploaded via DOCS,
9606: # a check will be made to see if a current copy exists on the local server,
9607: # if it does this will be served, otherwise a copy will be retrieved from
9608: # the home server for the course and stored in /home/httpd/html/userfiles on
9609: # the local server.
1.472 albertel 9610:
1.36 albertel 9611: sub getfile {
1.538 albertel 9612: my ($file) = @_;
1.609 banghart 9613: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9614: &repcopy($file);
9615: return &readfile($file);
9616: }
9617:
9618: sub repcopy_userfile {
9619: my ($file)=@_;
1.609 banghart 9620: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9621: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9622: my ($cdom,$cnum,$filename) =
1.811 albertel 9623: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9624: my $uri="/uploaded/$cdom/$cnum/$filename";
9625: if (-e "$file") {
1.828 www 9626: # we already have a local copy, check it out
1.538 albertel 9627: my @fileinfo = stat($file);
1.828 www 9628: my $rtncode;
9629: my $info;
1.538 albertel 9630: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9631: if ($lwpresp ne 'ok') {
1.828 www 9632: # there is no such file anymore, even though we had a local copy
1.482 albertel 9633: if ($rtncode eq '404') {
1.538 albertel 9634: unlink($file);
1.482 albertel 9635: }
9636: return -1;
9637: }
9638: if ($info < $fileinfo[9]) {
1.828 www 9639: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9640: return 'ok';
1.828 www 9641: } else {
9642: # the file is outdated, get rid of it
9643: unlink($file);
1.482 albertel 9644: }
1.828 www 9645: }
9646: # one way or the other, at this point, we don't have the file
9647: # construct the correct path for the file
9648: my @parts = ($cdom,$cnum);
9649: if ($filename =~ m|^(.+)/[^/]+$|) {
9650: push @parts, split(/\//,$1);
9651: }
9652: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9653: foreach my $part (@parts) {
9654: $path .= '/'.$part;
9655: if (!-e $path) {
9656: mkdir($path,0770);
1.482 albertel 9657: }
9658: }
1.828 www 9659: # now the path exists for sure
9660: # get a user agent
9661: my $ua=new LWP::UserAgent;
9662: my $transferfile=$file.'.in.transfer';
9663: # FIXME: this should flock
9664: if (-e $transferfile) { return 'ok'; }
9665: my $request;
9666: $uri=~s/^\///;
1.980 raeburn 9667: my $homeserver = &homeserver($cnum,$cdom);
9668: my $protocol = $protocol{$homeserver};
9669: $protocol = 'http' if ($protocol ne 'https');
9670: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9671: my $response=$ua->request($request,$transferfile);
9672: # did it work?
9673: if ($response->is_error()) {
9674: unlink($transferfile);
9675: &logthis("Userfile repcopy failed for $uri");
9676: return -1;
9677: }
9678: # worked, rename the transfer file
9679: rename($transferfile,$file);
1.607 raeburn 9680: return 'ok';
1.481 raeburn 9681: }
9682:
1.517 albertel 9683: sub tokenwrapper {
9684: my $uri=shift;
1.980 raeburn 9685: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9686: $uri=~s|^/||;
1.620 albertel 9687: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9688: my $token=$1;
1.552 albertel 9689: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9690: if ($udom && $uname && $file) {
9691: $file=~s|(\?\.*)*$||;
1.949 raeburn 9692: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9693: my $homeserver = &homeserver($uname,$udom);
9694: my $protocol = $protocol{$homeserver};
9695: $protocol = 'http' if ($protocol ne 'https');
9696: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9697: (($uri=~/\?/)?'&':'?').'token='.$token.
9698: '&tokenissued='.$perlvar{'lonHostID'};
9699: } else {
9700: return '/adm/notfound.html';
9701: }
9702: }
9703:
1.828 www 9704: # call with reqtype HEAD: get last modification time
9705: # call with reqtype GET: get the file contents
9706: # Do not call this with reqtype GET for large files! It loads everything into memory
9707: #
1.481 raeburn 9708: sub getuploaded {
9709: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9710: $uri=~s/^\///;
1.980 raeburn 9711: my $homeserver = &homeserver($cnum,$cdom);
9712: my $protocol = $protocol{$homeserver};
9713: $protocol = 'http' if ($protocol ne 'https');
9714: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9715: my $ua=new LWP::UserAgent;
9716: my $request=new HTTP::Request($reqtype,$uri);
9717: my $response=$ua->request($request);
9718: $$rtncode = $response->code;
1.482 albertel 9719: if (! $response->is_success()) {
9720: return 'failed';
9721: }
9722: if ($reqtype eq 'HEAD') {
1.486 www 9723: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9724: } elsif ($reqtype eq 'GET') {
9725: $$info = $response->content;
1.472 albertel 9726: }
1.482 albertel 9727: return 'ok';
1.36 albertel 9728: }
9729:
1.481 raeburn 9730: sub readfile {
9731: my $file = shift;
9732: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9733: my $fh;
9734: open($fh,"<$file");
9735: my $a='';
1.800 albertel 9736: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9737: return $a;
9738: }
9739:
1.36 albertel 9740: sub filelocation {
1.590 banghart 9741: my ($dir,$file) = @_;
9742: my $location;
9743: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9744:
9745: if ($file =~ m-^/adm/-) {
9746: $file=~s-^/adm/wrapper/-/-;
9747: $file=~s-^/adm/coursedocs/showdoc/-/-;
9748: }
1.882 albertel 9749:
1.590 banghart 9750: if ($file=~m:^/~:) { # is a contruction space reference
9751: $location = $file;
9752: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9753: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9754: # is a correct contruction space reference
9755: $location = $file;
1.956 raeburn 9756: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9757: $location = $file;
1.609 banghart 9758: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9759: my ($udom,$uname,$filename)=
1.811 albertel 9760: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9761: my $home=&homeserver($uname,$udom);
9762: my $is_me=0;
9763: my @ids=¤t_machine_ids();
9764: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9765: if ($is_me) {
1.955 raeburn 9766: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9767: } else {
9768: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9769: $udom.'/'.$uname.'/'.$filename;
9770: }
1.882 albertel 9771: } elsif ($file =~ m-^/adm/-) {
9772: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9773: } else {
9774: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9775: $file=~s:^/res/:/:;
9776: if ( !( $file =~ m:^/:) ) {
9777: $location = $dir. '/'.$file;
9778: } else {
9779: $location = '/home/httpd/html/res'.$file;
9780: }
1.59 albertel 9781: }
1.590 banghart 9782: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9783: while ($location=~m{/\.\./}) {
9784: if ($location =~ m{/[^/]+/\.\./}) {
9785: $location=~ s{/[^/]+/\.\./}{/}g;
9786: } else {
9787: $location=~ s{/\.\./}{/}g;
9788: }
9789: } #remove dir/..
1.590 banghart 9790: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9791: return $location;
1.46 www 9792: }
1.36 albertel 9793:
1.46 www 9794: sub hreflocation {
9795: my ($dir,$file)=@_;
1.980 raeburn 9796: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9797: $file=filelocation($dir,$file);
1.700 albertel 9798: } elsif ($file=~m-^/adm/-) {
9799: $file=~s-^/adm/wrapper/-/-;
9800: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9801: }
9802: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9803: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9804: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9805: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9806: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9807: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9808: -/uploaded/$1/$2/-x;
1.46 www 9809: }
1.913 albertel 9810: if ($file=~ m{^/userfiles/}) {
9811: $file =~ s{^/userfiles/}{/uploaded/};
9812: }
1.462 albertel 9813: return $file;
1.465 albertel 9814: }
9815:
9816: sub current_machine_domains {
1.853 albertel 9817: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9818: }
9819:
9820: sub machine_domains {
9821: my ($hostname) = @_;
1.465 albertel 9822: my @domains;
1.838 albertel 9823: my %hostname = &all_hostnames();
1.465 albertel 9824: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9825: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9826: if ($hostname eq $name) {
1.844 albertel 9827: push(@domains,&host_domain($id));
1.465 albertel 9828: }
9829: }
9830: return @domains;
9831: }
9832:
9833: sub current_machine_ids {
1.853 albertel 9834: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9835: }
9836:
9837: sub machine_ids {
9838: my ($hostname) = @_;
9839: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9840: my @ids;
1.888 albertel 9841: my %name_to_host = &all_names();
1.889 albertel 9842: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9843: return @{ $name_to_host{$hostname} };
9844: }
9845: return;
1.31 www 9846: }
9847:
1.824 raeburn 9848: sub additional_machine_domains {
9849: my @domains;
9850: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9851: while( my $line = <$fh>) {
9852: $line =~ s/\s//g;
9853: push(@domains,$line);
9854: }
9855: return @domains;
9856: }
9857:
9858: sub default_login_domain {
9859: my $domain = $perlvar{'lonDefDomain'};
9860: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9861: foreach my $posdom (¤t_machine_domains(),
9862: &additional_machine_domains()) {
9863: if (lc($posdom) eq lc($testdomain)) {
9864: $domain=$posdom;
9865: last;
9866: }
9867: }
9868: return $domain;
9869: }
9870:
1.31 www 9871: # ------------------------------------------------------------- Declutters URLs
9872:
9873: sub declutter {
9874: my $thisfn=shift;
1.569 albertel 9875: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9876: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9877: $thisfn=~s/^\///;
1.697 albertel 9878: $thisfn=~s|^adm/wrapper/||;
9879: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9880: $thisfn=~s/^res\///;
1.1032 raeburn 9881: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9882: $thisfn=~s/\?.+$//;
9883: }
1.268 www 9884: return $thisfn;
9885: }
9886:
9887: # ------------------------------------------------------------- Clutter up URLs
9888:
9889: sub clutter {
9890: my $thisfn='/'.&declutter(shift);
1.887 albertel 9891: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9892: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9893: $thisfn='/res'.$thisfn;
9894: }
1.1031 raeburn 9895: if ($thisfn !~m|^/adm|) {
9896: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9897: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9898: } else {
9899: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9900: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9901: if ($embstyle eq 'ssi'
9902: || ($embstyle eq 'hdn')
9903: || ($embstyle eq 'rat')
9904: || ($embstyle eq 'prv')
9905: || ($embstyle eq 'ign')) {
9906: #do nothing with these
9907: } elsif (($embstyle eq 'img')
1.695 albertel 9908: || ($embstyle eq 'emb')
9909: || ($embstyle eq 'wrp')) {
9910: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9911: } elsif ($embstyle eq 'unk'
9912: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9913: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9914: } else {
1.718 www 9915: # &logthis("Got a blank emb style");
1.695 albertel 9916: }
1.694 albertel 9917: }
9918: }
1.31 www 9919: return $thisfn;
1.12 www 9920: }
9921:
1.787 albertel 9922: sub clutter_with_no_wrapper {
9923: my $uri = &clutter(shift);
9924: if ($uri =~ m-^/adm/-) {
9925: $uri =~ s-^/adm/wrapper/-/-;
9926: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9927: }
9928: return $uri;
9929: }
9930:
1.557 albertel 9931: sub freeze_escape {
9932: my ($value)=@_;
9933: if (ref($value)) {
9934: $value=&nfreeze($value);
9935: return '__FROZEN__'.&escape($value);
9936: }
9937: return &escape($value);
9938: }
9939:
1.11 www 9940:
1.557 albertel 9941: sub thaw_unescape {
9942: my ($value)=@_;
9943: if ($value =~ /^__FROZEN__/) {
9944: substr($value,0,10,undef);
9945: $value=&unescape($value);
9946: return &thaw($value);
9947: }
9948: return &unescape($value);
9949: }
9950:
1.436 albertel 9951: sub correct_line_ends {
9952: my ($result)=@_;
9953: $$result =~s/\r\n/\n/mg;
9954: $$result =~s/\r/\n/mg;
1.415 albertel 9955: }
1.1 albertel 9956: # ================================================================ Main Program
9957:
1.184 www 9958: sub goodbye {
1.204 albertel 9959: &logthis("Starting Shut down");
1.443 albertel 9960: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9961: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9962: #converted
1.599 albertel 9963: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9964: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9965: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9966: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9967: #1.1 only
1.870 albertel 9968: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9969: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9970: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9971: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9972: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9973: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9974: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9975: &flushcourselogs();
9976: &logthis("Shutting down");
9977: }
9978:
1.852 albertel 9979: sub get_dns {
1.869 albertel 9980: my ($url,$func,$ignore_cache) = @_;
9981: if (!$ignore_cache) {
9982: my ($content,$cached)=
9983: &Apache::lonnet::is_cached_new('dns',$url);
9984: if ($cached) {
9985: &$func($content);
9986: return;
9987: }
9988: }
9989:
9990: my %alldns;
1.852 albertel 9991: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9992: foreach my $dns (<$config>) {
9993: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9994: my $line = $1;
9995: my ($host,$protocol) = split(/:/,$line);
9996: if ($protocol ne 'https') {
9997: $protocol = 'http';
9998: }
9999: $alldns{$host} = $protocol;
1.869 albertel 10000: }
10001: while (%alldns) {
10002: my ($dns) = keys(%alldns);
1.852 albertel 10003: my $ua=new LWP::UserAgent;
1.979 raeburn 10004: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10005: my $response=$ua->request($request);
1.979 raeburn 10006: delete($alldns{$dns});
1.852 albertel 10007: next if ($response->is_error());
10008: my @content = split("\n",$response->content);
1.869 albertel 10009: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10010: &$func(\@content);
1.869 albertel 10011: return;
1.852 albertel 10012: }
10013: close($config);
1.871 albertel 10014: my $which = (split('/',$url))[3];
10015: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10016: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10017: my @content = <$config>;
10018: &$func(\@content);
10019: return;
1.852 albertel 10020: }
1.327 albertel 10021: # ------------------------------------------------------------ Read domain file
10022: {
1.852 albertel 10023: my $loaded;
1.846 albertel 10024: my %domain;
10025:
1.852 albertel 10026: sub parse_domain_tab {
10027: my ($lines) = @_;
10028: foreach my $line (@$lines) {
10029: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10030:
1.846 albertel 10031: chomp($line);
1.852 albertel 10032: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10033: my %this_domain;
10034: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10035: 'lang_def', 'city', 'longi', 'lati',
10036: 'primary') {
10037: $this_domain{$field} = shift(@elements);
10038: }
10039: $domain{$name} = \%this_domain;
1.852 albertel 10040: }
10041: }
1.864 albertel 10042:
10043: sub reset_domain_info {
10044: undef($loaded);
10045: undef(%domain);
10046: }
10047:
1.852 albertel 10048: sub load_domain_tab {
1.869 albertel 10049: my ($ignore_cache) = @_;
10050: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10051: my $fh;
10052: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10053: my @lines = <$fh>;
10054: &parse_domain_tab(\@lines);
1.448 albertel 10055: }
1.852 albertel 10056: close($fh);
10057: $loaded = 1;
1.327 albertel 10058: }
1.846 albertel 10059:
10060: sub domain {
1.852 albertel 10061: &load_domain_tab() if (!$loaded);
10062:
1.846 albertel 10063: my ($name,$what) = @_;
10064: return if ( !exists($domain{$name}) );
10065:
10066: if (!$what) {
10067: return $domain{$name}{'description'};
10068: }
10069: return $domain{$name}{$what};
10070: }
1.974 raeburn 10071:
10072: sub domain_info {
10073: &load_domain_tab() if (!$loaded);
10074: return %domain;
10075: }
10076:
1.327 albertel 10077: }
10078:
10079:
1.1 albertel 10080: # ------------------------------------------------------------- Read hosts file
10081: {
1.838 albertel 10082: my %hostname;
1.844 albertel 10083: my %hostdom;
1.845 albertel 10084: my %libserv;
1.852 albertel 10085: my $loaded;
1.888 albertel 10086: my %name_to_host;
1.1056.4.6 raeburn 10087: my %internetdom;
1.1056.4.25! raeburn 10088: my %LC_dns_serv;
1.852 albertel 10089:
10090: sub parse_hosts_tab {
10091: my ($file) = @_;
10092: foreach my $configline (@$file) {
10093: next if ($configline =~ /^(\#|\s*$ )/x);
1.1056.4.25! raeburn 10094: chomp($configline);
! 10095: if ($configline =~ /^\^/) {
! 10096: if ($configline =~ /^\^([\w.\-]+)/) {
! 10097: $LC_dns_serv{$1} = 1;
! 10098: }
! 10099: next;
! 10100: }
1.1056.4.6 raeburn 10101: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10102: $name=~s/\s//g;
10103: if ($id && $domain && $role && $name) {
10104: $hostname{$id}=$name;
1.888 albertel 10105: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10106: $hostdom{$id}=$domain;
10107: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10108: if (defined($protocol)) {
10109: if ($protocol eq 'https') {
10110: $protocol{$id} = $protocol;
10111: } else {
10112: $protocol{$id} = 'http';
10113: }
1.968 raeburn 10114: } else {
1.969 raeburn 10115: $protocol{$id} = 'http';
1.968 raeburn 10116: }
1.1056.4.6 raeburn 10117: if (defined($intdom)) {
10118: $internetdom{$id} = $intdom;
10119: }
1.852 albertel 10120: }
10121: }
10122: }
1.864 albertel 10123:
10124: sub reset_hosts_info {
1.897 albertel 10125: &purge_remembered();
1.864 albertel 10126: &reset_domain_info();
10127: &reset_hosts_ip_info();
1.892 albertel 10128: undef(%name_to_host);
1.864 albertel 10129: undef(%hostname);
10130: undef(%hostdom);
10131: undef(%libserv);
10132: undef($loaded);
10133: }
1.1 albertel 10134:
1.852 albertel 10135: sub load_hosts_tab {
1.869 albertel 10136: my ($ignore_cache) = @_;
10137: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10138: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10139: my @config = <$config>;
10140: &parse_hosts_tab(\@config);
10141: close($config);
10142: $loaded=1;
1.1 albertel 10143: }
1.852 albertel 10144:
1.838 albertel 10145: sub hostname {
1.852 albertel 10146: &load_hosts_tab() if (!$loaded);
10147:
1.838 albertel 10148: my ($lonid) = @_;
10149: return $hostname{$lonid};
10150: }
1.845 albertel 10151:
1.838 albertel 10152: sub all_hostnames {
1.852 albertel 10153: &load_hosts_tab() if (!$loaded);
10154:
1.838 albertel 10155: return %hostname;
10156: }
1.845 albertel 10157:
1.888 albertel 10158: sub all_names {
10159: &load_hosts_tab() if (!$loaded);
10160:
10161: return %name_to_host;
10162: }
10163:
1.974 raeburn 10164: sub all_host_domain {
10165: &load_hosts_tab() if (!$loaded);
10166: return %hostdom;
10167: }
10168:
1.845 albertel 10169: sub is_library {
1.852 albertel 10170: &load_hosts_tab() if (!$loaded);
10171:
1.845 albertel 10172: return exists($libserv{$_[0]});
10173: }
10174:
10175: sub all_library {
1.852 albertel 10176: &load_hosts_tab() if (!$loaded);
10177:
1.845 albertel 10178: return %libserv;
10179: }
10180:
1.1056.4.2 raeburn 10181: sub unique_library {
10182: #2x reverse removes all hostnames that appear more than once
10183: my %unique = reverse &all_library();
10184: return reverse %unique;
10185: }
10186:
1.841 albertel 10187: sub get_servers {
1.852 albertel 10188: &load_hosts_tab() if (!$loaded);
10189:
1.841 albertel 10190: my ($domain,$type) = @_;
10191: my %possible_hosts = ($type eq 'library') ? %libserv
10192: : %hostname;
10193: my %result;
1.842 albertel 10194: if (ref($domain) eq 'ARRAY') {
10195: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10196: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10197: $result{$host} = $hostname;
10198: }
10199: }
10200: } else {
10201: while ( my ($host,$hostname) = each(%possible_hosts)) {
10202: if ($hostdom{$host} eq $domain) {
10203: $result{$host} = $hostname;
10204: }
1.841 albertel 10205: }
10206: }
10207: return %result;
10208: }
1.845 albertel 10209:
1.1056.4.2 raeburn 10210: sub get_unique_servers {
10211: my %unique = reverse &get_servers(@_);
10212: return reverse %unique;
10213: }
10214:
1.844 albertel 10215: sub host_domain {
1.852 albertel 10216: &load_hosts_tab() if (!$loaded);
10217:
1.844 albertel 10218: my ($lonid) = @_;
10219: return $hostdom{$lonid};
10220: }
10221:
1.841 albertel 10222: sub all_domains {
1.852 albertel 10223: &load_hosts_tab() if (!$loaded);
10224:
1.841 albertel 10225: my %seen;
10226: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10227: return @uniq;
10228: }
1.1056.4.3 raeburn 10229:
10230: sub internet_dom {
10231: &load_hosts_tab() if (!$loaded);
10232:
10233: my ($lonid) = @_;
10234: return $internetdom{$lonid};
10235: }
1.1 albertel 10236: }
10237:
1.847 albertel 10238: {
10239: my %iphost;
1.856 albertel 10240: my %name_to_ip;
10241: my %lonid_to_ip;
1.869 albertel 10242:
1.847 albertel 10243: sub get_hosts_from_ip {
10244: my ($ip) = @_;
10245: my %iphosts = &get_iphost();
10246: if (ref($iphosts{$ip})) {
10247: return @{$iphosts{$ip}};
10248: }
10249: return;
1.839 albertel 10250: }
1.864 albertel 10251:
10252: sub reset_hosts_ip_info {
10253: undef(%iphost);
10254: undef(%name_to_ip);
10255: undef(%lonid_to_ip);
10256: }
1.856 albertel 10257:
10258: sub get_host_ip {
10259: my ($lonid) = @_;
10260: if (exists($lonid_to_ip{$lonid})) {
10261: return $lonid_to_ip{$lonid};
10262: }
10263: my $name=&hostname($lonid);
10264: my $ip = gethostbyname($name);
10265: return if (!$ip || length($ip) ne 4);
10266: $ip=inet_ntoa($ip);
10267: $name_to_ip{$name} = $ip;
10268: $lonid_to_ip{$lonid} = $ip;
10269: return $ip;
10270: }
1.847 albertel 10271:
10272: sub get_iphost {
1.869 albertel 10273: my ($ignore_cache) = @_;
1.894 albertel 10274:
1.869 albertel 10275: if (!$ignore_cache) {
10276: if (%iphost) {
10277: return %iphost;
10278: }
10279: my ($ip_info,$cached)=
10280: &Apache::lonnet::is_cached_new('iphost','iphost');
10281: if ($cached) {
10282: %iphost = %{$ip_info->[0]};
10283: %name_to_ip = %{$ip_info->[1]};
10284: %lonid_to_ip = %{$ip_info->[2]};
10285: return %iphost;
10286: }
10287: }
1.894 albertel 10288:
10289: # get yesterday's info for fallback
10290: my %old_name_to_ip;
10291: my ($ip_info,$cached)=
10292: &Apache::lonnet::is_cached_new('iphost','iphost');
10293: if ($cached) {
10294: %old_name_to_ip = %{$ip_info->[1]};
10295: }
10296:
1.888 albertel 10297: my %name_to_host = &all_names();
10298: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10299: my $ip;
10300: if (!exists($name_to_ip{$name})) {
10301: $ip = gethostbyname($name);
10302: if (!$ip || length($ip) ne 4) {
1.894 albertel 10303: if (defined($old_name_to_ip{$name})) {
10304: $ip = $old_name_to_ip{$name};
10305: &logthis("Can't find $name defaulting to old $ip");
10306: } else {
10307: &logthis("Name $name no IP found");
10308: next;
10309: }
10310: } else {
10311: $ip=inet_ntoa($ip);
1.847 albertel 10312: }
10313: $name_to_ip{$name} = $ip;
10314: } else {
10315: $ip = $name_to_ip{$name};
1.653 albertel 10316: }
1.888 albertel 10317: foreach my $id (@{ $name_to_host{$name} }) {
10318: $lonid_to_ip{$id} = $ip;
10319: }
10320: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10321: }
1.869 albertel 10322: &Apache::lonnet::do_cache_new('iphost','iphost',
10323: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10324: 48*60*60);
1.869 albertel 10325:
1.847 albertel 10326: return %iphost;
1.598 albertel 10327: }
10328:
1.992 raeburn 10329: #
10330: # Given a DNS returns the loncapa host name for that DNS
10331: #
10332: sub host_from_dns {
10333: my ($dns) = @_;
10334: my @hosts;
10335: my $ip;
10336:
1.993 raeburn 10337: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10338: $ip = $name_to_ip{$dns};
10339: }
10340: if (!$ip) {
10341: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10342: if (length($ip) == 4) {
10343: $ip = &IO::Socket::inet_ntoa($ip);
10344: }
10345: }
10346: if ($ip) {
10347: @hosts = get_hosts_from_ip($ip);
10348: return $hosts[0];
10349: }
10350: return undef;
1.986 foxr 10351: }
1.992 raeburn 10352:
1.1056.4.3 raeburn 10353: sub get_internet_names {
10354: my ($lonid) = @_;
10355: return if ($lonid eq '');
10356: my ($idnref,$cached)=
10357: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10358: if ($cached) {
10359: return $idnref;
10360: }
10361: my $ip = &get_host_ip($lonid);
10362: my @hosts = &get_hosts_from_ip($ip);
10363: my %iphost = &get_iphost();
10364: my (@idns,%seen);
10365: foreach my $id (@hosts) {
10366: my $dom = &host_domain($id);
10367: my $prim_id = &domain($dom,'primary');
10368: my $prim_ip = &get_host_ip($prim_id);
10369: next if ($seen{$prim_ip});
10370: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10371: foreach my $id (@{$iphost{$prim_ip}}) {
10372: my $intdom = &internet_dom($id);
10373: unless (grep(/^\Q$intdom\E$/,@idns)) {
10374: push(@idns,$intdom);
10375: }
10376: }
10377: }
10378: $seen{$prim_ip} = 1;
10379: }
10380: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10381: }
10382:
10383: }
10384:
10385: sub all_loncaparevs {
10386: 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 10387: }
10388:
1.862 albertel 10389: BEGIN {
10390:
10391: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10392: unless ($readit) {
10393: {
10394: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10395: %perlvar = (%perlvar,%{$configvars});
10396: }
10397:
10398:
1.1 albertel 10399: # ------------------------------------------------------ Read spare server file
10400: {
1.448 albertel 10401: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10402:
10403: while (my $configline=<$config>) {
10404: chomp($configline);
1.284 matthew 10405: if ($configline) {
1.784 albertel 10406: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10407: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10408: push(@{ $spareid{$type} }, $host);
1.1 albertel 10409: }
10410: }
1.448 albertel 10411: close($config);
1.1 albertel 10412: }
1.11 www 10413: # ------------------------------------------------------------ Read permissions
10414: {
1.448 albertel 10415: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10416:
10417: while (my $configline=<$config>) {
1.448 albertel 10418: chomp($configline);
10419: if ($configline) {
10420: my ($role,$perm)=split(/ /,$configline);
10421: if ($perm ne '') { $pr{$role}=$perm; }
10422: }
1.11 www 10423: }
1.448 albertel 10424: close($config);
1.11 www 10425: }
10426:
10427: # -------------------------------------------- Read plain texts for permissions
10428: {
1.448 albertel 10429: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10430:
10431: while (my $configline=<$config>) {
1.448 albertel 10432: chomp($configline);
10433: if ($configline) {
1.742 raeburn 10434: my ($short,@plain)=split(/:/,$configline);
10435: %{$prp{$short}} = ();
10436: if (@plain > 0) {
10437: $prp{$short}{'std'} = $plain[0];
10438: for (my $i=1; $i<@plain; $i++) {
10439: $prp{$short}{'alt'.$i} = $plain[$i];
10440: }
10441: }
1.448 albertel 10442: }
1.135 www 10443: }
1.448 albertel 10444: close($config);
1.135 www 10445: }
10446:
10447: # ---------------------------------------------------------- Read package table
10448: {
1.448 albertel 10449: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10450:
10451: while (my $configline=<$config>) {
1.483 albertel 10452: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10453: chomp($configline);
10454: my ($short,$plain)=split(/:/,$configline);
10455: my ($pack,$name)=split(/\&/,$short);
10456: if ($plain ne '') {
10457: $packagetab{$pack.'&'.$name.'&name'}=$name;
10458: $packagetab{$short}=$plain;
10459: }
1.11 www 10460: }
1.448 albertel 10461: close($config);
1.329 matthew 10462: }
10463:
1.1056.4.3 raeburn 10464: # ---------------------------------------------------------- Read loncaparev table
10465: {
10466: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10467: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10468: while (my $configline=<$config>) {
10469: chomp($configline);
10470: my ($hostid,$loncaparev)=split(/:/,$configline);
10471: $loncaparevs{$hostid}=$loncaparev;
10472: }
10473: close($config);
10474: }
10475: }
10476: }
10477:
10478: # ---------------------------------------------------------- Read serverhostID table
10479: {
10480: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10481: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10482: while (my $configline=<$config>) {
10483: chomp($configline);
10484: my ($name,$id)=split(/:/,$configline);
10485: $serverhomeIDs{$name}=$id;
10486: }
10487: close($config);
10488: }
10489: }
10490: }
10491:
1.1056.4.5 raeburn 10492: {
10493: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10494: if (-e $file) {
10495: my $parser = HTML::LCParser->new($file);
10496: while (my $token = $parser->get_token()) {
10497: if ($token->[0] eq 'S') {
10498: my $item = $token->[1];
10499: my $name = $token->[2]{'name'};
10500: my $value = $token->[2]{'value'};
10501: if ($item ne '' && $name ne '' && $value ne '') {
10502: my $release = $parser->get_text();
10503: $release =~ s/(^\s*|\s*$ )//gx;
10504: $needsrelease{$item.':'.$name.':'.$value} = $release;
10505: }
10506: }
10507: }
10508: }
10509: }
10510:
1.329 matthew 10511: # ------------- set up temporary directory
10512: {
10513: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10514:
1.11 www 10515: }
10516:
1.794 albertel 10517: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10518: 'compress_threshold'=> 20_000,
10519: });
1.185 www 10520:
1.281 www 10521: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10522: $dumpcount=0;
1.958 www 10523: $locknum=0;
1.22 www 10524:
1.163 harris41 10525: &logtouch();
1.672 albertel 10526: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10527: $readit=1;
1.564 albertel 10528: {
10529: use integer;
10530: my $test=(2**32)+1;
1.568 albertel 10531: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10532: &logthis(" Detected 64bit platform ($_64bit)");
10533: }
1.195 www 10534: }
1.1 albertel 10535: }
1.179 www 10536:
1.1 albertel 10537: 1;
1.191 harris41 10538: __END__
10539:
1.243 albertel 10540: =pod
10541:
1.191 harris41 10542: =head1 NAME
10543:
1.243 albertel 10544: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10545:
10546: =head1 SYNOPSIS
10547:
1.243 albertel 10548: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10549:
10550: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10551:
1.243 albertel 10552: Common parameters:
10553:
10554: =over 4
10555:
10556: =item *
10557:
10558: $uname : an internal username (if $cname expecting a course Id specifically)
10559:
10560: =item *
10561:
10562: $udom : a domain (if $cdom expecting a course's domain specifically)
10563:
10564: =item *
10565:
10566: $symb : a resource instance identifier
10567:
10568: =item *
10569:
10570: $namespace : the name of a .db file that contains the data needed or
10571: being set.
10572:
10573: =back
10574:
1.394 bowersj2 10575: =head1 OVERVIEW
1.191 harris41 10576:
1.394 bowersj2 10577: lonnet provides subroutines which interact with the
10578: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10579: about classes, users, and resources.
1.243 albertel 10580:
10581: For many of these objects you can also use this to store data about
10582: them or modify them in various ways.
1.191 harris41 10583:
1.394 bowersj2 10584: =head2 Symbs
1.191 harris41 10585:
1.394 bowersj2 10586: To identify a specific instance of a resource, LON-CAPA uses symbols
10587: or "symbs"X<symb>. These identifiers are built from the URL of the
10588: map, the resource number of the resource in the map, and the URL of
10589: the resource itself. The latter is somewhat redundant, but might help
10590: if maps change.
10591:
10592: An example is
10593:
10594: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10595:
10596: The respective map entry is
10597:
10598: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10599: title="Problem 2">
10600: </resource>
10601:
10602: Symbs are used by the random number generator, as well as to store and
10603: restore data specific to a certain instance of for example a problem.
10604:
10605: =head2 Storing And Retrieving Data
10606:
10607: X<store()>X<cstore()>X<restore()>Three of the most important functions
10608: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10609: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10610: is is the non-critical message twin of cstore. These functions are for
10611: handlers to store a perl hash to a user's permanent data space in an
10612: easy manner, and to retrieve it again on another call. It is expected
10613: that a handler would use this once at the beginning to retrieve data,
10614: and then again once at the end to send only the new data back.
10615:
10616: The data is stored in the user's data directory on the user's
10617: homeserver under the ID of the course.
10618:
10619: The hash that is returned by restore will have all of the previous
10620: value for all of the elements of the hash.
10621:
10622: Example:
10623:
10624: #creating a hash
10625: my %hash;
10626: $hash{'foo'}='bar';
10627:
10628: #storing it
10629: &Apache::lonnet::cstore(\%hash);
10630:
10631: #changing a value
10632: $hash{'foo'}='notbar';
10633:
10634: #adding a new value
10635: $hash{'bar'}='foo';
10636: &Apache::lonnet::cstore(\%hash);
10637:
10638: #retrieving the hash
10639: my %history=&Apache::lonnet::restore();
10640:
10641: #print the hash
10642: foreach my $key (sort(keys(%history))) {
10643: print("\%history{$key} = $history{$key}");
10644: }
10645:
10646: Will print out:
1.191 harris41 10647:
1.394 bowersj2 10648: %history{1:foo} = bar
10649: %history{1:keys} = foo:timestamp
10650: %history{1:timestamp} = 990455579
10651: %history{2:bar} = foo
10652: %history{2:foo} = notbar
10653: %history{2:keys} = foo:bar:timestamp
10654: %history{2:timestamp} = 990455580
10655: %history{bar} = foo
10656: %history{foo} = notbar
10657: %history{timestamp} = 990455580
10658: %history{version} = 2
10659:
10660: Note that the special hash entries C<keys>, C<version> and
10661: C<timestamp> were added to the hash. C<version> will be equal to the
10662: total number of versions of the data that have been stored. The
10663: C<timestamp> attribute will be the UNIX time the hash was
10664: stored. C<keys> is available in every historical section to list which
10665: keys were added or changed at a specific historical revision of a
10666: hash.
10667:
10668: B<Warning>: do not store the hash that restore returns directly. This
10669: will cause a mess since it will restore the historical keys as if the
10670: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10671:
1.394 bowersj2 10672: Calling convention:
1.191 harris41 10673:
1.394 bowersj2 10674: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10675: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10676:
1.394 bowersj2 10677: For more detailed information, see lonnet specific documentation.
1.191 harris41 10678:
1.394 bowersj2 10679: =head1 RETURN MESSAGES
1.191 harris41 10680:
1.394 bowersj2 10681: =over 4
1.191 harris41 10682:
1.394 bowersj2 10683: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10684:
1.394 bowersj2 10685: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10686: when the connection is brought back up
1.191 harris41 10687:
1.394 bowersj2 10688: =item * B<con_failed>: unable to contact remote host and unable to save message
10689: for later delivery
1.191 harris41 10690:
1.967 bisitz 10691: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10692:
1.394 bowersj2 10693: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10694: that was requested
1.191 harris41 10695:
1.243 albertel 10696: =back
1.191 harris41 10697:
1.243 albertel 10698: =head1 PUBLIC SUBROUTINES
1.191 harris41 10699:
1.243 albertel 10700: =head2 Session Environment Functions
1.191 harris41 10701:
1.243 albertel 10702: =over 4
1.191 harris41 10703:
1.394 bowersj2 10704: =item *
10705: X<appenv()>
1.949 raeburn 10706: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10707: the user envirnoment file, and will be restored for each access this
1.620 albertel 10708: user makes during this session, also modifies the %env for the current
1.949 raeburn 10709: process. Optional rolesarrayref - if defined contains a reference to an array
10710: of roles which are exempt from the restriction on modifying user.role entries
10711: in the user's environment.db and in %env.
1.191 harris41 10712:
10713: =item *
1.394 bowersj2 10714: X<delenv()>
1.987 raeburn 10715: B<delenv($delthis,$regexp)>: removes all items from the session
10716: environment file that begin with $delthis. If the
10717: optional second arg - $regexp - is true, $delthis is treated as a
10718: regular expression, otherwise \Q$delthis\E is used.
10719: The values are also deleted from the current processes %env.
1.191 harris41 10720:
1.795 albertel 10721: =item * get_env_multiple($name)
10722:
10723: gets $name from the %env hash, it seemlessly handles the cases where multiple
10724: values may be defined and end up as an array ref.
10725:
10726: returns an array of values
10727:
1.243 albertel 10728: =back
10729:
10730: =head2 User Information
1.191 harris41 10731:
1.243 albertel 10732: =over 4
1.191 harris41 10733:
10734: =item *
1.394 bowersj2 10735: X<queryauthenticate()>
10736: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10737: authentication scheme
10738:
10739: =item *
1.394 bowersj2 10740: X<authenticate()>
1.1056.4.3 raeburn 10741: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10742: authenticate user from domain's lib servers (first use the current
10743: one). C<$upass> should be the users password.
1.1056.4.3 raeburn 10744: $checkdefauth is optional (value is 1 if a check should be made to
10745: authenticate user using default authentication method, and allow
10746: account creation if username does not have account in the domain).
10747: $clientcancheckhost is optional (value is 1 if checking whether the
10748: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10749:
10750: =item *
1.394 bowersj2 10751: X<homeserver()>
10752: B<homeserver($uname,$udom)>: find the server which has
10753: the user's directory and files (there must be only one), this caches
10754: the answer, and also caches if there is a borken connection.
1.191 harris41 10755:
10756: =item *
1.394 bowersj2 10757: X<idget()>
10758: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10759: (IDs are a unique resource in a domain, there must be only 1 ID per
10760: username, and only 1 username per ID in a specific domain) (returns
10761: hash: id=>name,id=>name)
1.191 harris41 10762:
10763: =item *
1.394 bowersj2 10764: X<idrget()>
10765: B<idrget($udom,@unames)>: find the IDs behind a list of
10766: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10767:
10768: =item *
1.394 bowersj2 10769: X<idput()>
10770: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10771:
10772: =item *
1.394 bowersj2 10773: X<rolesinit()>
10774: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10775:
10776: =item *
1.551 albertel 10777: X<getsection()>
10778: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10779: course $cname, return section name/number or '' for "not in course"
10780: and '-1' for "no section"
10781:
10782: =item *
1.394 bowersj2 10783: X<userenvironment()>
10784: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10785: passed in @what from the requested user's environment, returns a hash
10786:
1.858 raeburn 10787: =item *
10788: X<userlog_query()>
1.859 albertel 10789: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10790: activity.log file. %filters defines filters applied when parsing the
10791: log file. These can be start or end timestamps, or the type of action
10792: - log to look for Login or Logout events, check for Checkin or
10793: Checkout, role for role selection. The response is in the form
10794: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10795: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10796:
1.243 albertel 10797: =back
10798:
10799: =head2 User Roles
10800:
10801: =over 4
10802:
10803: =item *
10804:
1.810 raeburn 10805: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10806: F: full access
10807: U,I,K: authentication modes (cxx only)
10808: '': forbidden
10809: 1: user needs to choose course
10810: 2: browse allowed
1.766 albertel 10811: A: passphrase authentication needed
1.243 albertel 10812:
10813: =item *
10814:
10815: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10816: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10817: and course level
10818:
10819: =item *
10820:
1.988 raeburn 10821: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10822: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10823: $type is Course (default) or Community.
1.988 raeburn 10824: If $forcedefault evaluates to true, text returned will be default
10825: text for $type. Otherwise, if this is a course, the text returned
10826: will be a custom name for the role (if defined in the course's
10827: environment). If no custom name is defined the default is returned.
10828:
1.832 raeburn 10829: =item *
10830:
1.935 raeburn 10831: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10832: All arguments are optional. Returns a hash of a roles, either for
10833: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10834: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10835: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10836: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10837: For each key, value is set to colon-separated start and end times for
10838: the role. If no username and domain are specified, will default to
1.934 raeburn 10839: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10840: of role statuses (active, future or previous), roles
10841: (e.g., cc,in, st etc.) and domains of the roles which can be used
10842: to restrict the list of roles reported. If no array ref is
10843: provided for types, will default to return only active roles.
1.834 albertel 10844:
1.243 albertel 10845: =back
10846:
10847: =head2 User Modification
10848:
10849: =over 4
10850:
10851: =item *
10852:
1.957 raeburn 10853: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10854: user for the level given by URL. Optional start and end dates (leave empty
10855: string or zero for "no date")
1.191 harris41 10856:
10857: =item *
10858:
1.243 albertel 10859: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10860: change a users, password, possible return values are: ok,
10861: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10862: refused
1.191 harris41 10863:
10864: =item *
10865:
1.243 albertel 10866: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10867:
10868: =item *
10869:
1.1056.4.1 raeburn 10870: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10871: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10872:
10873: will update user information (firstname,middlename,lastname,generation,
10874: permanentemail), and if forceid is true, student/employee ID also.
10875: A user's institutional affiliation(s) can also be updated.
10876: User information fields will not be overwritten with empty entries
10877: unless the field is included in the $candelete array reference.
10878: This array is included when a single user is modified via "Manage Users",
10879: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10880:
10881: =item *
10882:
1.286 matthew 10883: modifystudent
10884:
1.957 raeburn 10885: modify a student's enrollment and identification information.
1.286 matthew 10886: The course id is resolved based on the current users environment.
10887: This means the envoking user must be a course coordinator or otherwise
10888: associated with a course.
10889:
1.297 matthew 10890: This call is essentially a wrapper for lonnet::modifyuser and
10891: lonnet::modify_student_enrollment
1.286 matthew 10892:
10893: Inputs:
10894:
10895: =over 4
10896:
1.957 raeburn 10897: =item B<$udom> Student's loncapa domain
1.286 matthew 10898:
1.957 raeburn 10899: =item B<$uname> Student's loncapa login name
1.286 matthew 10900:
1.964 bisitz 10901: =item B<$uid> Student/Employee ID
1.286 matthew 10902:
1.957 raeburn 10903: =item B<$umode> Student's authentication mode
1.286 matthew 10904:
1.957 raeburn 10905: =item B<$upass> Student's password
1.286 matthew 10906:
1.957 raeburn 10907: =item B<$first> Student's first name
1.286 matthew 10908:
1.957 raeburn 10909: =item B<$middle> Student's middle name
1.286 matthew 10910:
1.957 raeburn 10911: =item B<$last> Student's last name
1.286 matthew 10912:
1.957 raeburn 10913: =item B<$gene> Student's generation
1.286 matthew 10914:
1.957 raeburn 10915: =item B<$usec> Student's section in course
1.286 matthew 10916:
10917: =item B<$end> Unix time of the roles expiration
10918:
10919: =item B<$start> Unix time of the roles start date
10920:
10921: =item B<$forceid> If defined, allow $uid to be changed
10922:
10923: =item B<$desiredhome> server to use as home server for student
10924:
1.957 raeburn 10925: =item B<$email> Student's permanent e-mail address
10926:
10927: =item B<$type> Type of enrollment (auto or manual)
10928:
1.963 raeburn 10929: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10930:
10931: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10932:
1.963 raeburn 10933: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10934:
1.963 raeburn 10935: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10936:
1.963 raeburn 10937: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10938:
1.286 matthew 10939: =back
1.297 matthew 10940:
10941: =item *
10942:
10943: modify_student_enrollment
10944:
10945: Change a students enrollment status in a class. The environment variable
10946: 'role.request.course' must be defined for this function to proceed.
10947:
10948: Inputs:
10949:
10950: =over 4
10951:
10952: =item $udom, students domain
10953:
10954: =item $uname, students name
10955:
10956: =item $uid, students user id
10957:
10958: =item $first, students first name
10959:
10960: =item $middle
10961:
10962: =item $last
10963:
10964: =item $gene
10965:
10966: =item $usec
10967:
10968: =item $end
10969:
10970: =item $start
10971:
1.957 raeburn 10972: =item $type
10973:
10974: =item $locktype
10975:
10976: =item $cid
10977:
10978: =item $selfenroll
10979:
10980: =item $context
10981:
1.297 matthew 10982: =back
10983:
1.191 harris41 10984:
10985: =item *
10986:
1.243 albertel 10987: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10988: custom role; give a custom role to a user for the level given by URL. Specify
10989: name and domain of role author, and role name
1.191 harris41 10990:
10991: =item *
10992:
1.243 albertel 10993: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10994:
10995: =item *
10996:
1.243 albertel 10997: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10998:
10999: =back
11000:
11001: =head2 Course Infomation
11002:
11003: =over 4
1.191 harris41 11004:
11005: =item *
11006:
1.631 albertel 11007: coursedescription($courseid) : returns a hash of information about the
11008: specified course id, including all environment settings for the
11009: course, the description of the course will be in the hash under the
11010: key 'description'
1.191 harris41 11011:
11012: =item *
11013:
1.624 albertel 11014: resdata($name,$domain,$type,@which) : request for current parameter
11015: setting for a specific $type, where $type is either 'course' or 'user',
11016: @what should be a list of parameters to ask about. This routine caches
11017: answers for 5 minutes.
1.243 albertel 11018:
1.877 foxr 11019: =item *
11020:
11021: get_courseresdata($courseid, $domain) : dump the entire course resource
11022: data base, returning a hash that is keyed by the resource name and has
11023: values that are the resource value. I believe that the timestamps and
11024: versions are also returned.
11025:
11026:
1.243 albertel 11027: =back
11028:
11029: =head2 Course Modification
11030:
11031: =over 4
1.191 harris41 11032:
11033: =item *
11034:
1.243 albertel 11035: writecoursepref($courseid,%prefs) : write preferences (environment
11036: database) for a course
1.191 harris41 11037:
11038: =item *
11039:
1.1011 raeburn 11040: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11041:
11042: =item *
11043:
1.1038 raeburn 11044: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11045:
11046: =back
11047:
11048: =head2 Resource Subroutines
11049:
11050: =over 4
1.191 harris41 11051:
11052: =item *
11053:
1.243 albertel 11054: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11055:
11056: =item *
11057:
1.243 albertel 11058: repcopy($filename) : subscribes to the requested file, and attempts to
11059: replicate from the owning library server, Might return
1.607 raeburn 11060: 'unavailable', 'not_found', 'forbidden', 'ok', or
11061: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11062: resource. Expects the local filesystem pathname
11063: (/home/httpd/html/res/....)
11064:
11065: =back
11066:
11067: =head2 Resource Information
11068:
11069: =over 4
1.191 harris41 11070:
11071: =item *
11072:
1.243 albertel 11073: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11074: a vairety of different possible values, $varname should be a request
11075: string, and the other parameters can be used to specify who and what
11076: one is asking about.
11077:
11078: Possible values for $varname are environment.lastname (or other item
11079: from the envirnment hash), user.name (or someother aspect about the
11080: user), resource.0.maxtries (or some other part and parameter of a
11081: resource)
1.204 albertel 11082:
11083: =item *
11084:
1.243 albertel 11085: directcondval($number) : get current value of a condition; reads from a state
11086: string
1.204 albertel 11087:
11088: =item *
11089:
1.243 albertel 11090: condval($condidx) : value of condition index based on state
1.204 albertel 11091:
11092: =item *
11093:
1.243 albertel 11094: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11095: resource's metadata, $what should be either a specific key, or either
11096: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11097: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11098:
11099: this function automatically caches all requests
1.191 harris41 11100:
11101: =item *
11102:
1.243 albertel 11103: metadata_query($query,$custom,$customshow) : make a metadata query against the
11104: network of library servers; returns file handle of where SQL and regex results
11105: will be stored for query
1.191 harris41 11106:
11107: =item *
11108:
1.243 albertel 11109: symbread($filename) : return symbolic list entry (filename argument optional);
11110: returns the data handle
1.191 harris41 11111:
11112: =item *
11113:
1.243 albertel 11114: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11115: a possible symb for the URL in $thisfn, and if is an encryypted
11116: resource that the user accessed using /enc/ returns a 1 on success, 0
11117: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11118: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11119:
1.191 harris41 11120:
11121: =item *
11122:
1.243 albertel 11123: symbclean($symb) : removes versions numbers from a symb, returns the
11124: cleaned symb
1.191 harris41 11125:
11126: =item *
11127:
1.243 albertel 11128: is_on_map($uri) : checks if the $uri is somewhere on the current
11129: course map, user must be in a course for it to work.
1.191 harris41 11130:
11131: =item *
11132:
1.243 albertel 11133: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11134:
11135: =item *
11136:
1.243 albertel 11137: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11138: a random seed, all arguments are optional, if they aren't sent it uses the
11139: environment to derive them. Note: if symb isn't sent and it can't get one
11140: from &symbread it will use the current time as its return value
1.191 harris41 11141:
11142: =item *
11143:
1.243 albertel 11144: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11145: unfakeable, receipt
1.191 harris41 11146:
11147: =item *
11148:
1.620 albertel 11149: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11150:
11151: =item *
11152:
1.243 albertel 11153: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11154:
11155: =item *
11156:
1.243 albertel 11157: 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 11158:
11159: =item *
11160:
1.243 albertel 11161: 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 11162:
11163: =item *
11164:
1.243 albertel 11165: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11166:
11167: =item *
11168:
1.243 albertel 11169: devalidate($symb) : devalidate temporary spreadsheet calculations,
11170: forcing spreadsheet to reevaluate the resource scores next time.
11171:
11172: =back
11173:
11174: =head2 Storing/Retreiving Data
11175:
11176: =over 4
1.191 harris41 11177:
11178: =item *
11179:
1.243 albertel 11180: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11181: for this url; hashref needs to be given and should be a \%hashname; the
11182: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11183: be derived from the env
1.191 harris41 11184:
11185: =item *
11186:
1.243 albertel 11187: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11188: uses critical subroutine
1.191 harris41 11189:
11190: =item *
11191:
1.243 albertel 11192: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11193: all args are optional
1.191 harris41 11194:
11195: =item *
11196:
1.717 albertel 11197: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11198: dumps the complete (or key matching regexp) namespace into a hash
11199: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11200: normally &store()ed into
11201:
11202: $range should be either an integer '100' (give me the first 100
11203: matching records)
11204: or be two integers sperated by a - with no spaces
11205: '30-50' (give me the 30th through the 50th matching
11206: records)
11207:
11208:
11209: =item *
11210:
11211: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11212: replaces a &store() version of data with a replacement set of data
11213: for a particular resource in a namespace passed in the $storehash hash
11214: reference
11215:
11216: =item *
11217:
1.243 albertel 11218: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11219: works very similar to store/cstore, but all data is stored in a
11220: temporary location and can be reset using tmpreset, $storehash should
11221: be a hash reference, returns nothing on success
1.191 harris41 11222:
11223: =item *
11224:
1.243 albertel 11225: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11226: similar to restore, but all data is stored in a temporary location and
11227: can be reset using tmpreset. Returns a hash of values on success,
11228: error string otherwise.
1.191 harris41 11229:
11230: =item *
11231:
1.243 albertel 11232: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11233: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11234:
11235: =item *
11236:
1.243 albertel 11237: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11238: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11239:
11240: =item *
11241:
1.243 albertel 11242: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11243: namesp ($udom and $uname are optional)
1.191 harris41 11244:
11245: =item *
11246:
1.702 albertel 11247: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11248: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11249: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11250:
1.702 albertel 11251: $range should be either an integer '100' (give me the first 100
11252: matching records)
11253: or be two integers sperated by a - with no spaces
11254: '30-50' (give me the 30th through the 50th matching
11255: records)
1.449 matthew 11256: =item *
11257:
11258: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11259: $store can be a scalar, an array reference, or if the amount to be
11260: incremented is > 1, a hash reference.
11261:
11262: ($udom and $uname are optional)
1.191 harris41 11263:
11264: =item *
11265:
1.243 albertel 11266: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11267: ($udom and $uname are optional)
1.191 harris41 11268:
11269: =item *
11270:
1.243 albertel 11271: cput($namespace,$storehash,$udom,$uname) : critical put
11272: ($udom and $uname are optional)
1.191 harris41 11273:
11274: =item *
11275:
1.748 albertel 11276: newput($namespace,$storehash,$udom,$uname) :
11277:
11278: Attempts to store the items in the $storehash, but only if they don't
11279: currently exist, if this succeeds you can be certain that you have
11280: successfully created a new key value pair in the $namespace db.
11281:
11282:
11283: Args:
11284: $namespace: name of database to store values to
11285: $storehash: hashref to store to the db
11286: $udom: (optional) domain of user containing the db
11287: $uname: (optional) name of user caontaining the db
11288:
11289: Returns:
11290: 'ok' -> succeeded in storing all keys of $storehash
11291: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11292: least <key> already existed in the db (other
11293: requested keys may also already exist)
1.967 bisitz 11294: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11295: 'con_lost' -> unable to contact request server
11296: 'refused' -> action was not allowed by remote machine
11297:
11298:
11299: =item *
11300:
1.243 albertel 11301: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11302: reference filled in from namesp (encrypts the return communication)
11303: ($udom and $uname are optional)
1.191 harris41 11304:
11305: =item *
11306:
1.243 albertel 11307: log($udom,$name,$home,$message) : write to permanent log for user; use
11308: critical subroutine
11309:
1.806 raeburn 11310: =item *
11311:
1.860 raeburn 11312: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11313: array reference filled in from namespace found in domain level on either
11314: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11315:
11316: =item *
11317:
1.860 raeburn 11318: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11319: domain level either on specified domain server ($uhome) or primary domain
11320: server ($udom and $uhome are optional)
1.806 raeburn 11321:
1.943 raeburn 11322: =item *
11323:
11324: get_domain_defaults($target_domain) : returns hash with defaults for
11325: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11326: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11327: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11328: Values are retrieved from cache (if current), or from domain's configuration.db
11329: (if available), or lastly from values in lonTabs/dns_domain,tab,
11330: or lonTabs/domain.tab.
11331:
11332: %domdefaults = &get_auth_defaults($target_domain);
11333:
1.243 albertel 11334: =back
11335:
11336: =head2 Network Status Functions
11337:
11338: =over 4
1.191 harris41 11339:
11340: =item *
11341:
11342: dirlist($uri) : return directory list based on URI
11343:
11344: =item *
11345:
1.243 albertel 11346: spareserver() : find server with least workload from spare.tab
11347:
1.986 foxr 11348:
11349: =item *
11350:
11351: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11352: if there is no corresponding loncapa host.
11353:
1.243 albertel 11354: =back
11355:
1.986 foxr 11356:
1.243 albertel 11357: =head2 Apache Request
11358:
11359: =over 4
1.191 harris41 11360:
11361: =item *
11362:
1.243 albertel 11363: ssi($url,%hash) : server side include, does a complete request cycle on url to
11364: localhost, posts hash
11365:
11366: =back
11367:
11368: =head2 Data to String to Data
11369:
11370: =over 4
1.191 harris41 11371:
11372: =item *
11373:
1.243 albertel 11374: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11375: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11376:
11377: =item *
11378:
1.243 albertel 11379: hashref2str($hashref) : convert a hashref into a string complete with
11380: escaping and '=' and '&' separators, supports elements that are
11381: arrayrefs and hashrefs
1.191 harris41 11382:
11383: =item *
11384:
1.243 albertel 11385: arrayref2str($arrayref) : convert an arrayref into a string complete
11386: with escaping and '&' separators, supports elements that are arrayrefs
11387: and hashrefs
1.191 harris41 11388:
11389: =item *
11390:
1.243 albertel 11391: str2hash($string) : convert string to hash using unescaping and
11392: splitting on '=' and '&', supports elements that are arrayrefs and
11393: hashrefs
1.191 harris41 11394:
11395: =item *
11396:
1.243 albertel 11397: str2array($string) : convert string to hash using unescaping and
11398: splitting on '&', supports elements that are arrayrefs and hashrefs
11399:
11400: =back
11401:
11402: =head2 Logging Routines
11403:
11404: =over 4
11405:
11406: These routines allow one to make log messages in the lonnet.log and
11407: lonnet.perm logfiles.
1.191 harris41 11408:
11409: =item *
11410:
1.243 albertel 11411: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11412:
11413: =item *
11414:
1.243 albertel 11415: logthis() : append message to the normal lonnet.log file, it gets
11416: preiodically rolled over and deleted.
1.191 harris41 11417:
11418: =item *
11419:
1.243 albertel 11420: logperm() : append a permanent message to lonnet.perm.log, this log
11421: file never gets deleted by any automated portion of the system, only
11422: messages of critical importance should go in here.
11423:
11424: =back
11425:
11426: =head2 General File Helper Routines
11427:
11428: =over 4
1.191 harris41 11429:
11430: =item *
11431:
1.481 raeburn 11432: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11433: (a) files in /uploaded
11434: (i) If a local copy of the file exists -
11435: compares modification date of local copy with last-modified date for
11436: definitive version stored on home server for course. If local copy is
11437: stale, requests a new version from the home server and stores it.
11438: If the original has been removed from the home server, then local copy
11439: is unlinked.
11440: (ii) If local copy does not exist -
11441: requests the file from the home server and stores it.
11442:
11443: If $caller is 'uploadrep':
11444: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11445: for request for files originally uploaded via DOCS.
11446: - returns 'ok' if fresh local copy now available, -1 otherwise.
11447:
11448: Otherwise:
11449: This indicates a call from the content generation phase of the request.
11450: - returns the entire contents of the file or -1.
11451:
11452: (b) files in /res
11453: - returns the entire contents of a file or -1;
11454: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11455:
1.712 albertel 11456:
11457: =item *
11458:
11459: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11460: reference
11461:
11462: returns either a stat() list of data about the file or an empty list
11463: if the file doesn't exist or couldn't find out about it (connection
11464: problems or user unknown)
11465:
1.191 harris41 11466: =item *
11467:
1.243 albertel 11468: filelocation($dir,$file) : returns file system location of a file
11469: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11470: directory that relative $file lookups are to looked in ($dir of /a/dir
11471: and a file of ../bob will become /a/bob)
1.191 harris41 11472:
11473: =item *
11474:
11475: hreflocation($dir,$file) : returns file system location or a URL; same as
11476: filelocation except for hrefs
11477:
11478: =item *
11479:
11480: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11481:
1.243 albertel 11482: =back
11483:
1.608 albertel 11484: =head2 Usererfile file routines (/uploaded*)
11485:
11486: =over 4
11487:
11488: =item *
11489:
11490: userfileupload(): main rotine for putting a file in a user or course's
11491: filespace, arguments are,
11492:
1.620 albertel 11493: formname - required - this is the name of the element in $env where the
1.608 albertel 11494: filename, and the contents of the file to create/modifed exist
1.620 albertel 11495: the filename is in $env{'form.'.$formname.'.filename'} and the
11496: contents of the file is located in $env{'form.'.$formname}
1.1056.4.13 raeburn 11497: context - if coursedoc, store the file in the course of the active role
11498: of the current user;
11499: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11500: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11501: subdir - required - subdirectory to put the file in under ../userfiles/
11502: if undefined, it will be placed in "unknown"
11503:
11504: (This routine calls clean_filename() to remove any dangerous
11505: characters from the filename, and then calls finuserfileupload() to
11506: complete the transaction)
11507:
11508: returns either the url of the uploaded file (/uploaded/....) if successful
11509: and /adm/notfound.html if unsuccessful
11510:
11511: =item *
11512:
11513: clean_filename(): routine for cleaing a filename up for storage in
11514: userfile space, argument is:
11515:
11516: filename - proposed filename
11517:
11518: returns: the new clean filename
11519:
11520: =item *
11521:
1.1056.4.13 raeburn 11522: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11523: userspace, probably shouldn't be called directly
11524:
11525: docuname: username or courseid of destination for the file
11526: docudom: domain of user/course of destination for the file
11527: formname: same as for userfileupload()
1.1056.4.13 raeburn 11528: fname: filename (including subdirectories) for the file
11529: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11530: allfiles: reference to hash used to store objects found by parser
11531: codebase: reference to hash used for codebases of java objects found by parser
11532: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11533: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11534: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11535: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11536: context: if 'overwrite', will move the uploaded file from its temporary location to
11537: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1056.4.16 raeburn 11538: mimetype: reference to scalar to accommodate mime type determined
11539: from File::MMagic if $parser = parse.
1.608 albertel 11540:
11541: returns either the url of the uploaded file (/uploaded/....) if successful
1.1056.4.13 raeburn 11542: and /adm/notfound.html if unsuccessful (or an error message if context
11543: was 'overwrite').
11544:
1.608 albertel 11545:
11546: =item *
11547:
11548: renameuserfile(): renames an existing userfile to a new name
11549:
11550: Args:
11551: docuname: username or courseid of destination for the file
11552: docudom: domain of user/course of destination for the file
11553: old: current file name (including any subdirs under userfiles)
11554: new: desired file name (including any subdirs under userfiles)
11555:
11556: =item *
11557:
11558: mkdiruserfile(): creates a directory is a userfiles dir
11559:
11560: Args:
11561: docuname: username or courseid of destination for the file
11562: docudom: domain of user/course of destination for the file
11563: dir: dir to create (including any subdirs under userfiles)
11564:
11565: =item *
11566:
11567: removeuserfile(): removes a file that exists in userfiles
11568:
11569: Args:
11570: docuname: username or courseid of destination for the file
11571: docudom: domain of user/course of destination for the file
11572: fname: filname to delete (including any subdirs under userfiles)
11573:
11574: =item *
11575:
11576: removeuploadedurl(): convience function for removeuserfile()
11577:
11578: Args:
11579: url: a full /uploaded/... url to delete
11580:
1.747 albertel 11581: =item *
11582:
11583: get_portfile_permissions():
11584: Args:
11585: domain: domain of user or course contain the portfolio files
11586: user: name of user or num of course contain the portfolio files
11587: Returns:
11588: hashref of a dump of the proper file_permissions.db
11589:
11590:
11591: =item *
11592:
11593: get_access_controls():
11594:
11595: Args:
11596: current_permissions: the hash ref returned from get_portfile_permissions()
11597: group: (optional) the group you want the files associated with
11598: file: (optional) the file you want access info on
11599:
11600: Returns:
1.749 raeburn 11601: a hash (keys are file names) of hashes containing
11602: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11603: values are XML containing access control settings (see below)
1.747 albertel 11604:
11605: Internal notes:
11606:
1.749 raeburn 11607: access controls are stored in file_permissions.db as key=value pairs.
11608: key -> path to file/file_name\0uniqueID:scope_end_start
11609: where scope -> public,guest,course,group,domains or users.
11610: end -> UNIX time for end of access (0 -> no end date)
11611: start -> UNIX time for start of access
11612:
11613: value -> XML description of access control
11614: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11615: <start></start>
11616: <end></end>
11617:
11618: <password></password> for scope type = guest
11619:
11620: <domain></domain> for scope type = course or group
11621: <number></number>
11622: <roles id="">
11623: <role></role>
11624: <access></access>
11625: <section></section>
11626: <group></group>
11627: </roles>
11628:
11629: <dom></dom> for scope type = domains
11630:
11631: <users> for scope type = users
11632: <user>
11633: <uname></uname>
11634: <udom></udom>
11635: </user>
11636: </users>
11637: </scope>
11638:
11639: Access data is also aggregated for each file in an additional key=value pair:
11640: key -> path to file/file_name\0accesscontrol
11641: value -> reference to hash
11642: hash contains key = value pairs
11643: where key = uniqueID:scope_end_start
11644: value = UNIX time record was last updated
11645:
11646: Used to improve speed of look-ups of access controls for each file.
11647:
11648: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11649:
11650: modify_access_controls():
11651:
11652: Modifies access controls for a portfolio file
11653: Args
11654: 1. file name
11655: 2. reference to hash of required changes,
11656: 3. domain
11657: 4. username
11658: where domain,username are the domain of the portfolio owner
11659: (either a user or a course)
11660:
11661: Returns:
11662: 1. result of additions or updates ('ok' or 'error', with error message).
11663: 2. result of deletions ('ok' or 'error', with error message).
11664: 3. reference to hash of any new or updated access controls.
11665: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11666: key = integer (inbound ID)
11667: value = uniqueID
1.747 albertel 11668:
1.608 albertel 11669: =back
11670:
1.243 albertel 11671: =head2 HTTP Helper Routines
11672:
11673: =over 4
11674:
1.191 harris41 11675: =item *
11676:
11677: escape() : unpack non-word characters into CGI-compatible hex codes
11678:
11679: =item *
11680:
11681: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11682:
1.243 albertel 11683: =back
11684:
11685: =head1 PRIVATE SUBROUTINES
11686:
11687: =head2 Underlying communication routines (Shouldn't call)
11688:
11689: =over 4
11690:
11691: =item *
11692:
11693: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11694:
11695: =item *
11696:
11697: reply() : uses subreply to send a message to remote machine, logs all failures
11698:
11699: =item *
11700:
11701: critical() : passes a critical message to another server; if cannot
11702: get through then place message in connection buffer directory and
11703: returns con_delayed, if incapable of saving message, returns
11704: con_failed
11705:
11706: =item *
11707:
11708: reconlonc() : tries to reconnect lonc client processes.
11709:
11710: =back
11711:
11712: =head2 Resource Access Logging
11713:
11714: =over 4
11715:
11716: =item *
11717:
11718: flushcourselogs() : flush (save) buffer logs and access logs
11719:
11720: =item *
11721:
11722: courselog($what) : save message for course in hash
11723:
11724: =item *
11725:
11726: courseacclog($what) : save message for course using &courselog(). Perform
11727: special processing for specific resource types (problems, exams, quizzes, etc).
11728:
1.191 harris41 11729: =item *
11730:
11731: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11732: as a PerlChildExitHandler
1.243 albertel 11733:
11734: =back
11735:
11736: =head2 Other
11737:
11738: =over 4
11739:
11740: =item *
11741:
11742: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11743:
11744: =back
11745:
11746: =cut
1.877 foxr 11747:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>