Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.118.2.20
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.118. .20(raeb 4:-21): # $Id: lonnet.pm,v 1.1172.2.118.2.19 2021/02/11 20:25:43 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;
1.1172.2.107 raeburn 77: use CGI::Cookie;
1.977 amueller 78:
1.1172.2.104 raeburn 79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138 raeburn 80: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114 raeburn 81: %managerstab $passwdmin);
1.871 albertel 82:
83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
84: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
85: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 86: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 87:
1.1 albertel 88: use IO::Socket;
1.31 www 89: use GDBM_File;
1.208 albertel 90: use HTML::LCParser;
1.88 www 91: use Fcntl qw(:flock);
1.870 albertel 92: use Storable qw(thaw nfreeze);
1.1172.2.79 raeburn 93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 94: use Cache::Memcached;
1.676 albertel 95: use Digest::MD5;
1.790 albertel 96: use Math::Random;
1.1024 raeburn 97: use File::MMagic;
1.807 albertel 98: use LONCAPA qw(:DEFAULT :match);
1.740 www 99: use LONCAPA::Configuration;
1.1160 www 100: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 101: use LONCAPA::Lond;
1.1172.2.110 raeburn 102: use LONCAPA::transliterate;
1.1117 foxr 103:
1.1090 raeburn 104: use File::Copy;
1.676 albertel 105:
1.195 www 106: my $readit;
1.1172.2.79 raeburn 107: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 108:
1.619 albertel 109: require Exporter;
110:
111: our @ISA = qw (Exporter);
112: our @EXPORT = qw(%env);
113:
1.1172.2.9 raeburn 114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 115: {
116: my $logid;
1.1172.2.9 raeburn 117: sub write_log {
118: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
119: if ($context eq 'course') {
120: if (($cnum eq '') || ($cdom eq '')) {
121: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
122: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
123: }
1.957 raeburn 124: }
1.1172.2.13 raeburn 125: $logid ++;
1.957 raeburn 126: my $now = time();
127: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.118. .14(raeb 128:-21): my $ip = &get_requestor_ip();
1.1172.2.9 raeburn 129: my $logentry = {
130: $id => {
131: 'exe_uname' => $env{'user.name'},
132: 'exe_udom' => $env{'user.domain'},
133: 'exe_time' => $now,
1.1172.2.118. .14(raeb 134:-21): 'exe_ip' => $ip,
1.1172.2.9 raeburn 135: 'delflag' => $delflag,
136: 'logentry' => $storehash,
137: 'uname' => $uname,
138: 'udom' => $udom,
139: }
140: };
141: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 142: }
143: }
1.1 albertel 144:
1.163 harris41 145: sub logtouch {
146: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 147: unless (-e "$execdir/logs/lonnet.log") {
1.1172.2.96 raeburn 148: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 149: close $fh;
150: }
151: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
152: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
153: }
154:
1.1 albertel 155: sub logthis {
156: my $message=shift;
157: my $execdir=$perlvar{'lonDaemons'};
158: my $now=time;
159: my $local=localtime($now);
1.1172.2.96 raeburn 160: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 161: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
162: print $fh $logstring;
1.448 albertel 163: close($fh);
164: }
1.1 albertel 165: return 1;
166: }
167:
168: sub logperm {
169: my $message=shift;
170: my $execdir=$perlvar{'lonDaemons'};
171: my $now=time;
172: my $local=localtime($now);
1.1172.2.96 raeburn 173: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 174: print $fh "$now:$message:$local\n";
175: close($fh);
176: }
1.1 albertel 177: return 1;
178: }
179:
1.850 albertel 180: sub create_connection {
1.853 albertel 181: my ($hostname,$lonid) = @_;
1.851 albertel 182: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 183: Type => SOCK_STREAM,
184: Timeout => 10);
185: return 0 if (!$client);
1.890 albertel 186: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 187: my $result = <$client>;
188: chomp($result);
189: return 1 if ($result eq 'done');
190: return 0;
191: }
192:
1.983 raeburn 193: sub get_server_timezone {
194: my ($cnum,$cdom) = @_;
195: my $home=&homeserver($cnum,$cdom);
196: if ($home ne 'no_host') {
197: my $cachetime = 24*3600;
198: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
199: if (defined($cached)) {
200: return $timezone;
201: } else {
202: my $timezone = &reply('servertimezone',$home);
203: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
204: }
205: }
206: }
1.850 albertel 207:
1.1106 raeburn 208: sub get_server_distarch {
209: my ($lonhost,$ignore_cache) = @_;
210: if (defined($lonhost)) {
211: if (!defined(&hostname($lonhost))) {
212: return;
213: }
214: my $cachetime = 12*3600;
215: if (!$ignore_cache) {
216: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
217: if (defined($cached)) {
218: return $distarch;
219: }
220: }
221: my $rep = &reply('serverdistarch',$lonhost);
222: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
223: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
224: $rep eq '') {
225: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
226: }
227: }
228: return;
229: }
230:
1.993 raeburn 231: sub get_server_loncaparev {
1.1073 raeburn 232: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 233: if (defined($lonhost)) {
234: if (!defined(&hostname($lonhost))) {
235: undef($lonhost);
236: }
237: }
238: if (!defined($lonhost)) {
239: if (defined(&domain($dom,'primary'))) {
240: $lonhost=&domain($dom,'primary');
241: if ($lonhost eq 'no_host') {
242: undef($lonhost);
243: }
244: }
245: }
246: if (defined($lonhost)) {
1.1073 raeburn 247: my $cachetime = 12*3600;
248: if (!$ignore_cache) {
249: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
250: if (defined($cached)) {
251: return $loncaparev;
252: }
253: }
254: my ($answer,$loncaparev);
255: my @ids=¤t_machine_ids();
256: if (grep(/^\Q$lonhost\E$/,@ids)) {
257: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 258: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 259: $loncaparev = $1;
260: }
261: } else {
262: $answer = &reply('serverloncaparev',$lonhost);
263: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
264: if ($caller eq 'loncron') {
265: my $ua=new LWP::UserAgent;
1.1082 raeburn 266: $ua->timeout(4);
1.1172.2.118. .3(raebu 267:20): my $hostname = &hostname($lonhost);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118. .3(raebu 270:20): my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
1.1172.2.35 raeburn 359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: }
365:
1.1 albertel 366: # -------------------------------------------------- Non-critical communication
367: sub subreply {
368: my ($cmd,$server)=@_;
1.838 albertel 369: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 370: #
371: # With loncnew process trimming, there's a timing hole between lonc server
372: # process exit and the master server picking up the listen on the AF_UNIX
373: # socket. In that time interval, a lock file will exist:
374:
375: my $lockfile=$peerfile.".lock";
376: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 377: sleep(0.1);
1.549 foxr 378: }
379: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 380: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 381: #
1.550 foxr 382: # We'll give the connection a few tries before abandoning it. If
383: # connection is not possible, we'll con_lost back to the client.
384: #
385: my $client;
386: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
387: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
388: Type => SOCK_STREAM,
389: Timeout => 10);
1.869 albertel 390: if ($client) {
1.550 foxr 391: last; # Connected!
1.850 albertel 392: } else {
1.853 albertel 393: &create_connection(&hostname($server),$server);
1.550 foxr 394: }
1.1172.2.79 raeburn 395: sleep(0.1); # Try again later if failed connection.
1.550 foxr 396: }
397: my $answer;
398: if ($client) {
1.704 albertel 399: print $client "sethost:$server:$cmd\n";
1.550 foxr 400: $answer=<$client>;
401: if (!$answer) { $answer="con_lost"; }
402: chomp($answer);
403: } else {
404: $answer = 'con_lost'; # Failed connection.
405: }
1.1 albertel 406: return $answer;
407: }
408:
409: sub reply {
410: my ($cmd,$server)=@_;
1.838 albertel 411: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 412: my $answer=subreply($cmd,$server);
1.65 www 413: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111 raeburn 414: my $logged = $cmd;
415: if ($cmd =~ /^encrypt:([^:]+):/) {
416: my $subcmd = $1;
417: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
418: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
419: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
420: (undef,undef,my @rest) = split(/:/,$cmd);
421: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
422: splice(@rest,2,1,'Hidden');
423: } elsif ($subcmd eq 'passwd') {
424: splice(@rest,2,2,('Hidden','Hidden'));
425: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
426: ($subcmd eq 'autoexportgrades')) {
427: splice(@rest,3,1,'Hidden');
428: }
429: $logged = join(':',('encrypt:'.$subcmd,@rest));
430: }
431: }
432: &logthis("<font color=\"blue\">WARNING:".
433: " $logged to $server returned $answer</font>");
1.12 www 434: }
1.1 albertel 435: return $answer;
436: }
437:
438: # ----------------------------------------------------------- Send USR1 to lonc
439:
440: sub reconlonc {
1.891 albertel 441: my ($lonid) = @_;
442: if ($lonid) {
1.1172.2.72 raeburn 443: my $hostname = &hostname($lonid);
1.891 albertel 444: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
445: if ($hostname && -e $peerfile) {
446: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
447: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
448: Type => SOCK_STREAM,
449: Timeout => 10);
450: if ($client) {
451: print $client ("reset_retries\n");
452: my $answer=<$client>;
453: #reset just this one.
454: }
455: }
456: return;
457: }
458:
1.836 www 459: &logthis("Trying to reconnect lonc");
1.1 albertel 460: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96 raeburn 461: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 462: my $loncpid=<$fh>;
463: chomp($loncpid);
464: if (kill 0 => $loncpid) {
465: &logthis("lonc at pid $loncpid responding, sending USR1");
466: kill USR1 => $loncpid;
467: sleep 1;
1.836 www 468: } else {
1.12 www 469: &logthis(
1.672 albertel 470: "<font color=\"blue\">WARNING:".
1.12 www 471: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 472: }
473: } else {
1.836 www 474: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 475: }
476: }
477:
478: # ------------------------------------------------------ Critical communication
1.12 www 479:
1.1 albertel 480: sub critical {
481: my ($cmd,$server)=@_;
1.838 albertel 482: unless (&hostname($server)) {
1.672 albertel 483: &logthis("<font color=\"blue\">WARNING:".
1.89 www 484: " Critical message to unknown server ($server)</font>");
485: return 'no_such_host';
486: }
1.1 albertel 487: my $answer=reply($cmd,$server);
488: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 489: &reconlonc($server);
1.589 albertel 490: my $answer=reply($cmd,$server);
1.1 albertel 491: if ($answer eq 'con_lost') {
492: my $now=time;
493: my $middlename=$cmd;
1.5 www 494: $middlename=substr($middlename,0,16);
1.1 albertel 495: $middlename=~s/\W//g;
496: my $dfilename=
1.305 www 497: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
498: $dumpcount++;
1.1 albertel 499: {
1.448 albertel 500: my $dfh;
1.1172.2.96 raeburn 501: if (open($dfh,">",$dfilename)) {
1.448 albertel 502: print $dfh "$cmd\n";
503: close($dfh);
504: }
1.1 albertel 505: }
1.1172.2.79 raeburn 506: sleep 1;
1.1 albertel 507: my $wcmd='';
508: {
1.448 albertel 509: my $dfh;
1.1172.2.96 raeburn 510: if (open($dfh,"<",$dfilename)) {
1.448 albertel 511: $wcmd=<$dfh>;
512: close($dfh);
513: }
1.1 albertel 514: }
515: chomp($wcmd);
1.7 www 516: if ($wcmd eq $cmd) {
1.672 albertel 517: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 518: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 519: &logperm("D:$server:$cmd");
520: return 'con_delayed';
521: } else {
1.672 albertel 522: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 523: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 524: &logperm("F:$server:$cmd");
525: return 'con_failed';
526: }
527: }
528: }
529: return $answer;
1.405 albertel 530: }
531:
1.755 albertel 532: # ------------------------------------------- check if return value is an error
533:
534: sub error {
535: my ($result) = @_;
1.756 albertel 536: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 537: if ($2 == 2) { return undef; }
538: return $1;
539: }
540: return undef;
541: }
542:
1.783 albertel 543: sub convert_and_load_session_env {
544: my ($lonidsdir,$handle)=@_;
545: my @profile;
546: {
1.917 albertel 547: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
548: if (!$opened) {
1.915 albertel 549: return 0;
550: }
1.783 albertel 551: flock($idf,LOCK_SH);
552: @profile=<$idf>;
553: close($idf);
554: }
555: my %temp_env;
556: foreach my $line (@profile) {
1.786 albertel 557: if ($line !~ m/=/) {
558: return 0;
559: }
1.783 albertel 560: chomp($line);
561: my ($envname,$envvalue)=split(/=/,$line,2);
562: $temp_env{&unescape($envname)} = &unescape($envvalue);
563: }
564: unlink("$lonidsdir/$handle.id");
565: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
566: 0640)) {
567: %disk_env = %temp_env;
568: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
569: untie(%disk_env);
570: }
1.786 albertel 571: return 1;
1.783 albertel 572: }
573:
1.374 www 574: # ------------------------------------------- Transfer profile into environment
1.780 albertel 575: my $env_loaded;
576: sub transfer_profile_to_env {
1.788 albertel 577: my ($lonidsdir,$handle,$force_transfer) = @_;
578: if (!$force_transfer && $env_loaded) { return; }
1.374 www 579:
1.720 albertel 580: if (!defined($lonidsdir)) {
581: $lonidsdir = $perlvar{'lonIDsDir'};
582: }
583: if (!defined($handle)) {
584: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
585: }
586:
1.786 albertel 587: my $convert;
588: {
1.917 albertel 589: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
590: if (!$opened) {
1.915 albertel 591: return;
592: }
1.786 albertel 593: flock($idf,LOCK_SH);
594: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
595: &GDBM_READER(),0640)) {
596: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
597: untie(%disk_env);
598: } else {
599: $convert = 1;
600: }
601: }
602: if ($convert) {
603: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
604: &logthis("Failed to load session, or convert session.");
605: }
1.374 www 606: }
1.783 albertel 607:
1.786 albertel 608: my %remove;
1.783 albertel 609: while ( my $envname = each(%env) ) {
1.433 matthew 610: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
611: if ($time < time-300) {
1.783 albertel 612: $remove{$key}++;
1.433 matthew 613: }
614: }
615: }
1.783 albertel 616:
1.619 albertel 617: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 618: $env_loaded=1;
1.783 albertel 619: foreach my $expired_key (keys(%remove)) {
1.433 matthew 620: &delenv($expired_key);
1.374 www 621: }
1.1 albertel 622: }
623:
1.916 albertel 624: # ---------------------------------------------------- Check for valid session
625: sub check_for_valid_session {
1.1172.2.96 raeburn 626: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 627: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108 raeburn 628: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155 raeburn 629: if ($name eq 'lonDAV') {
630: $lonidsdir=$r->dir_config('lonDAVsessDir');
631: } else {
632: $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108 raeburn 633: if ($name eq '') {
634: $name = 'lonID';
635: }
636: }
637: if ($name eq 'lonID') {
638: $secure = 'lonSID';
639: $linkname = 'lonLinkID';
640: $pubname = 'lonPubID';
641: if (exists($cookies{$secure})) {
642: $lonid=$cookies{$secure};
643: } elsif (exists($cookies{$name})) {
644: $lonid=$cookies{$name};
645: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
646: $lonid=$cookies{$linkname};
647: } elsif (exists($cookies{$pubname})) {
648: $lonid=$cookies{$pubname};
649: }
650: } else {
651: $lonid=$cookies{$name};
652: }
653: return undef if (!$lonid);
654:
655: my $handle=&LONCAPA::clean_handle($lonid->value);
656: if (-l "$lonidsdir/$handle.id") {
657: my $link = readlink("$lonidsdir/$handle.id");
658: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
659: $handle = $1;
660: }
1.1155 raeburn 661: }
1.1172.2.96 raeburn 662: if (!-e "$lonidsdir/$handle.id") {
663: if ((ref($domref)) && ($name eq 'lonID') &&
664: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
665: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
666: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
667: $$domref = $possudom;
668: }
669: }
670: return undef;
671: }
1.916 albertel 672:
1.917 albertel 673: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
674: return undef if (!$opened);
1.916 albertel 675:
676: flock($idf,LOCK_SH);
677: my %disk_env;
678: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
679: &GDBM_READER(),0640)) {
680: return undef;
681: }
682:
683: if (!defined($disk_env{'user.name'})
684: || !defined($disk_env{'user.domain'})) {
1.1172.2.107 raeburn 685: untie(%disk_env);
1.916 albertel 686: return undef;
687: }
1.1172.2.18 raeburn 688:
1.1172.2.36 raeburn 689: if (ref($userhashref) eq 'HASH') {
690: $userhashref->{'name'} = $disk_env{'user.name'};
691: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 692: }
1.1172.2.107 raeburn 693: untie(%disk_env);
1.1172.2.18 raeburn 694:
1.916 albertel 695: return $handle;
696: }
697:
1.830 albertel 698: sub timed_flock {
699: my ($file,$lock_type) = @_;
700: my $failed=0;
701: eval {
702: local $SIG{__DIE__}='DEFAULT';
703: local $SIG{ALRM}=sub {
704: $failed=1;
705: die("failed lock");
706: };
707: alarm(13);
708: flock($file,$lock_type);
709: alarm(0);
710: };
711: if ($failed) {
712: return undef;
713: } else {
714: return 1;
715: }
716: }
717:
1.1172.2.107 raeburn 718: sub get_sessionfile_vars {
719: my ($handle,$lonidsdir,$storearr) = @_;
720: my %returnhash;
721: unless (ref($storearr) eq 'ARRAY') {
722: return %returnhash;
723: }
724: if (-l "$lonidsdir/$handle.id") {
725: my $link = readlink("$lonidsdir/$handle.id");
726: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
727: $handle = $1;
728: }
729: }
730: if ((-e "$lonidsdir/$handle.id") &&
731: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
732: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
733: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
734: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
735: flock($idf,LOCK_SH);
736: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
737: &GDBM_READER(),0640)) {
738: foreach my $item (@{$storearr}) {
739: $returnhash{$item} = $disk_env{$item};
740: }
741: untie(%disk_env);
742: }
743: }
744: }
745: }
746: return %returnhash;
747: }
748:
1.5 www 749: # ---------------------------------------------------------- Append Environment
750:
751: sub appenv {
1.949 raeburn 752: my ($newenv,$roles) = @_;
753: if (ref($newenv) eq 'HASH') {
754: foreach my $key (keys(%{$newenv})) {
755: my $refused = 0;
756: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
757: $refused = 1;
758: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 759: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 760: if (grep(/^\Q$role\E$/,@{$roles})) {
761: $refused = 0;
762: }
763: }
764: }
765: if ($refused) {
766: &logthis("<font color=\"blue\">WARNING: ".
767: "Attempt to modify environment ".$key." to ".$newenv->{$key}
768: .'</font>');
769: delete($newenv->{$key});
770: } else {
771: $env{$key}=$newenv->{$key};
772: }
773: }
1.1172.2.96 raeburn 774: my $lonids = $perlvar{'lonIDsDir'};
775: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
776: my $opened = open(my $env_file,'+<',$env{'user.environment'});
777: if ($opened
778: && &timed_flock($env_file,LOCK_EX)
779: &&
780: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
781: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
782: while (my ($key,$value) = each(%{$newenv})) {
783: $disk_env{$key} = $value;
784: }
785: untie(%disk_env);
786: }
1.35 www 787: }
1.191 harris41 788: }
1.56 www 789: return 'ok';
790: }
791: # ----------------------------------------------------- Delete from Environment
792:
793: sub delenv {
1.1104 raeburn 794: my ($delthis,$regexp,$roles) = @_;
795: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
796: my $refused = 1;
797: if (ref($roles) eq 'ARRAY') {
798: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
799: if (grep(/^\Q$role\E$/,@{$roles})) {
800: $refused = 0;
801: }
802: }
803: if ($refused) {
804: &logthis("<font color=\"blue\">WARNING: ".
805: "Attempt to delete from environment ".$delthis);
806: return 'error';
807: }
1.56 www 808: }
1.917 albertel 809: my $opened = open(my $env_file,'+<',$env{'user.environment'});
810: if ($opened
1.915 albertel 811: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 812: &&
813: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
814: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 815: foreach my $key (keys(%disk_env)) {
1.987 raeburn 816: if ($regexp) {
817: if ($key=~/^$delthis/) {
818: delete($env{$key});
819: delete($disk_env{$key});
820: }
821: } else {
822: if ($key=~/^\Q$delthis\E/) {
823: delete($env{$key});
824: delete($disk_env{$key});
825: }
826: }
1.448 albertel 827: }
1.783 albertel 828: untie(%disk_env);
1.5 www 829: }
830: return 'ok';
1.369 albertel 831: }
832:
1.790 albertel 833: sub get_env_multiple {
834: my ($name) = @_;
835: my @values;
836: if (defined($env{$name})) {
837: # exists is it an array
838: if (ref($env{$name})) {
839: @values=@{ $env{$name} };
840: } else {
841: $values[0]=$env{$name};
842: }
843: }
844: return(@values);
845: }
846:
1.958 www 847: # ------------------------------------------------------------------- Locking
848:
849: sub set_lock {
850: my ($text)=@_;
851: $locknum++;
852: my $id=$$.'-'.$locknum;
853: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
854: 'session.lock.'.$id => $text});
855: return $id;
856: }
857:
858: sub get_locks {
859: my $num=0;
860: my %texts=();
861: foreach my $lock (split(/\,/,$env{'session.locks'})) {
862: if ($lock=~/\w/) {
863: $num++;
864: $texts{$lock}=$env{'session.lock.'.$lock};
865: }
866: }
867: return ($num,%texts);
868: }
869:
870: sub remove_lock {
871: my ($id)=@_;
872: my $newlocks='';
873: foreach my $lock (split(/\,/,$env{'session.locks'})) {
874: if (($lock=~/\w/) && ($lock ne $id)) {
875: $newlocks.=','.$lock;
876: }
877: }
878: &appenv({'session.locks' => $newlocks});
879: &delenv('session.lock.'.$id);
880: }
881:
882: sub remove_all_locks {
883: my $activelocks=$env{'session.locks'};
884: foreach my $lock (split(/\,/,$env{'session.locks'})) {
885: if ($lock=~/\w/) {
886: &remove_lock($lock);
887: }
888: }
889: }
890:
891:
1.369 albertel 892: # ------------------------------------------ Find out current server userload
893: sub userload {
894: my $numusers=0;
895: {
896: opendir(LONIDS,$perlvar{'lonIDsDir'});
897: my $filename;
898: my $curtime=time;
899: while ($filename=readdir(LONIDS)) {
1.925 albertel 900: next if ($filename eq '.' || $filename eq '..');
901: next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112 raeburn 902: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 903: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 904: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 905: }
906: closedir(LONIDS);
907: }
908: my $userloadpercent=0;
909: my $maxuserload=$perlvar{'lonUserLoadLim'};
910: if ($maxuserload) {
1.371 albertel 911: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 912: }
1.372 albertel 913: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 914: return $userloadpercent;
1.283 www 915: }
916:
1.1 albertel 917: # ------------------------------ Find server with least workload from spare.tab
1.11 www 918:
1.1 albertel 919: sub spareserver {
1.1083 raeburn 920: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 921: my $spare_server;
1.370 albertel 922: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 923: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
924: : $userloadpercent;
1.1083 raeburn 925: my ($uint_dom,$remotesessions);
926: if (($udom ne '') && (&domain($udom) ne '')) {
927: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
928: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
929: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
930: $remotesessions = $udomdefaults{'remotesessions'};
931: }
1.1123 raeburn 932: my $spareshash = &this_host_spares($udom);
933: if (ref($spareshash) eq 'HASH') {
934: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
935: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 936: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
937: $try_server));
1.1123 raeburn 938: ($spare_server, $lowest_load) =
939: &compare_server_load($try_server, $spare_server, $lowest_load);
940: }
1.1083 raeburn 941: }
1.784 albertel 942:
1.1123 raeburn 943: my $found_server = ($spare_server ne '' && $lowest_load < 100);
944:
945: if (!$found_server) {
946: if (ref($spareshash->{'default'}) eq 'ARRAY') {
947: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 948: next unless (&spare_can_host($udom,$uint_dom,
949: $remotesessions,$try_server));
1.1123 raeburn 950: ($spare_server, $lowest_load) =
951: &compare_server_load($try_server, $spare_server, $lowest_load);
952: }
953: }
954: }
1.784 albertel 955: }
956:
957: if (!$want_server_name) {
1.1001 raeburn 958: if (defined($spare_server)) {
959: my $hostname = &hostname($spare_server);
1.1083 raeburn 960: if (defined($hostname)) {
1.1172.2.118. .3(raebu 961:20): my $protocol = 'http';
962:20): if ($protocol{$spare_server} eq 'https') {
963:20): $protocol = $protocol{$spare_server};
964:20): }
1.1001 raeburn 965: $spare_server = $protocol.'://'.$hostname;
966: }
967: }
1.784 albertel 968: }
969: return $spare_server;
970: }
971:
972: sub compare_server_load {
1.1172.2.41 raeburn 973: my ($try_server, $spare_server, $lowest_load, $required) = @_;
974:
975: if ($required) {
976: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
977: my $remoterev = &get_server_loncaparev(undef,$try_server);
978: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
979: if (($major eq '' && $minor eq '') ||
980: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
981: return ($spare_server,$lowest_load);
982: }
983: }
1.784 albertel 984:
985: my $loadans = &reply('load', $try_server);
986: my $userloadans = &reply('userload',$try_server);
987:
988: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 989: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 990: }
991:
992: my $load;
993: if ($loadans =~ /\d/) {
994: if ($userloadans =~ /\d/) {
995: #both are numbers, pick the bigger one
996: $load = ($loadans > $userloadans) ? $loadans
997: : $userloadans;
1.411 albertel 998: } else {
1.784 albertel 999: $load = $loadans;
1.411 albertel 1000: }
1.784 albertel 1001: } else {
1002: $load = $userloadans;
1003: }
1004:
1005: if (($load =~ /\d/) && ($load < $lowest_load)) {
1006: $spare_server = $try_server;
1007: $lowest_load = $load;
1.370 albertel 1008: }
1.784 albertel 1009: return ($spare_server,$lowest_load);
1.202 matthew 1010: }
1.914 albertel 1011:
1012: # --------------------------- ask offload servers if user already has a session
1013: sub find_existing_session {
1014: my ($udom,$uname) = @_;
1.1123 raeburn 1015: my $spareshash = &this_host_spares($udom);
1016: if (ref($spareshash) eq 'HASH') {
1017: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1018: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1019: return $try_server if (&has_user_session($try_server, $udom, $uname));
1020: }
1021: }
1022: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1023: foreach my $try_server (@{ $spareshash->{'default'} }) {
1024: return $try_server if (&has_user_session($try_server, $udom, $uname));
1025: }
1026: }
1.914 albertel 1027: }
1028: return;
1029: }
1030:
1.1172.2.107 raeburn 1031: # check if user's browser sent load balancer cookie and server still has session
1032: # and is not overloaded.
1033: sub check_for_balancer_cookie {
1034: my ($r,$update_mtime) = @_;
1035: my ($otherserver,$cookie);
1036: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1037: if (exists($cookies{'balanceID'})) {
1038: my $balid = $cookies{'balanceID'};
1039: $cookie=&LONCAPA::clean_handle($balid->value);
1040: my $balancedir=$r->dir_config('lonBalanceDir');
1041: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1042: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1043: my ($possudom,$possuname) = ($1,$2);
1044: my $has_session = 0;
1045: if ((&domain($possudom) ne '') &&
1046: (&homeserver($possuname,$possudom) ne 'no_host')) {
1047: my $try_server;
1048: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1049: if ($opened) {
1050: flock($idf,LOCK_SH);
1051: while (my $line = <$idf>) {
1052: chomp($line);
1053: if (&hostname($line) ne '') {
1054: $try_server = $line;
1055: last;
1056: }
1057: }
1058: close($idf);
1059: if (($try_server) &&
1060: (&has_user_session($try_server,$possudom,$possuname))) {
1061: my $lowest_load = 30000;
1062: ($otherserver,$lowest_load) =
1063: &compare_server_load($try_server,undef,$lowest_load);
1064: if ($otherserver ne '' && $lowest_load < 100) {
1065: $has_session = 1;
1066: } else {
1067: undef($otherserver);
1068: }
1069: }
1070: }
1071: }
1072: if ($has_session) {
1073: if ($update_mtime) {
1074: my $atime = my $mtime = time;
1075: utime($atime,$mtime,"$balancedir/$cookie.id");
1076: }
1077: } else {
1078: unlink("$balancedir/$cookie.id");
1079: }
1080: }
1081: }
1082: }
1083: return ($otherserver,$cookie);
1084: }
1085:
1.1172.2.118. .11(raeb 1086:-20): sub updatebalcookie {
1087:-20): my ($cookie,$balancer,$lastentry)=@_;
1088:-20): if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1089:-20): my ($udom,$uname) = ($1,$2);
1090:-20): my $uprimary_id = &domain($udom,'primary');
1091:-20): my $uintdom = &internet_dom($uprimary_id);
1092:-20): my $intdom = &internet_dom($balancer);
1093:-20): my $serverhomedom = &host_domain($balancer);
1094:-20): if (($uintdom ne '') && ($uintdom eq $intdom)) {
1095:-20): return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1096:-20): }
1097:-20): }
1098:-20): return;
1099:-20): }
1100:-20):
1.1172.2.107 raeburn 1101: sub delbalcookie {
1102: my ($cookie,$balancer) =@_;
1103: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1104: my ($udom,$uname) = ($1,$2);
1105: my $uprimary_id = &domain($udom,'primary');
1106: my $uintdom = &internet_dom($uprimary_id);
1107: my $intdom = &internet_dom($balancer);
1108: my $serverhomedom = &host_domain($balancer);
1109: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.118. .11(raeb 1110:-20): return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107 raeburn 1111: }
1112: }
1113: }
1114:
1.914 albertel 1115: # -------------------------------- ask if server already has a session for user
1116: sub has_user_session {
1117: my ($lonid,$udom,$uname) = @_;
1118: my $result = &reply(join(':','userhassession',
1119: map {&escape($_)} ($udom,$uname)),$lonid);
1120: return 1 if ($result eq 'ok');
1121:
1122: return 0;
1123: }
1124:
1.1076 raeburn 1125: # --------- determine least loaded server in a user's domain which allows login
1126:
1127: sub choose_server {
1.1172.2.47 raeburn 1128: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1129: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1130: my %servers = &get_servers($udom);
1.1076 raeburn 1131: my $lowest_load = 30000;
1.1172.2.47 raeburn 1132: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1133: if ($skiploadbal) {
1134: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1135: unless (defined($cached)) {
1136: my $cachetime = 60*60*24;
1137: my %domconfig =
1138: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1139: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1140: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1141: $cachetime);
1142: }
1143: }
1144: }
1.1076 raeburn 1145: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 1146: my $loginvia;
1.1172.2.47 raeburn 1147: if ($skiploadbal) {
1148: if (ref($balancers) eq 'HASH') {
1149: next if (exists($balancers->{$lonhost}));
1150: }
1151: }
1.1115 raeburn 1152: if ($checkloginvia) {
1153: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1154: if ($loginvia) {
1155: my ($server,$path) = split(/:/,$loginvia);
1156: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1157: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1158: if ($login_host eq $server) {
1159: $portal_path = $path;
1.1151 raeburn 1160: $isredirect = 1;
1.1116 raeburn 1161: }
1162: } else {
1163: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1164: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1165: if ($login_host eq $lonhost) {
1166: $portal_path = '';
1.1151 raeburn 1167: $isredirect = '';
1.1116 raeburn 1168: }
1169: }
1170: } else {
1.1076 raeburn 1171: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1172: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1173: }
1174: }
1175: if ($login_host ne '') {
1.1116 raeburn 1176: $hostname = &hostname($login_host);
1.1076 raeburn 1177: }
1.1172.2.88 raeburn 1178: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1179: }
1180:
1.1172.2.118. .5(raebu 1181:20): sub get_course_sessions {
1182:20): my ($cnum,$cdom,$lastactivity) = @_;
1183:20): my %servers = &internet_dom_servers($cdom);
1184:20): my %returnhash;
1185:20): foreach my $server (sort(keys(%servers))) {
1186:20): my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1187:20): my @pairs=split(/\&/,$rep);
1188:20): unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1189:20): foreach my $item (@pairs) {
1190:20): my ($key,$value)=split(/=/,$item,2);
1191:20): $key = &unescape($key);
1192:20): next if ($key =~ /^error: 2 /);
1193:20): if (exists($returnhash{$key})) {
1194:20): next if ($value < $returnhash{$key});
1195:20): }
1196:20): $returnhash{$key}=$value;
1197:20): }
1198:20): }
1199:20): }
1200:20): return %returnhash;
1201:20): }
1202:20):
1.202 matthew 1203: # --------------------------------------------- Try to change a user's password
1204:
1205: sub changepass {
1.799 raeburn 1206: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1207: $currentpass = &escape($currentpass);
1208: $newpass = &escape($newpass);
1.1030 raeburn 1209: my $lonhost = $perlvar{'lonHostID'};
1210: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1211: $server);
1212: if (! $answer) {
1213: &logthis("No reply on password change request to $server ".
1214: "by $uname in domain $udom.");
1215: } elsif ($answer =~ "^ok") {
1216: &logthis("$uname in $udom successfully changed their password ".
1217: "on $server.");
1218: } elsif ($answer =~ "^pwchange_failure") {
1219: &logthis("$uname in $udom was unable to change their password ".
1220: "on $server. The action was blocked by either lcpasswd ".
1221: "or pwchange");
1222: } elsif ($answer =~ "^non_authorized") {
1223: &logthis("$uname in $udom did not get their password correct when ".
1224: "attempting to change it on $server.");
1225: } elsif ($answer =~ "^auth_mode_error") {
1226: &logthis("$uname in $udom attempted to change their password despite ".
1227: "not being locally or internally authenticated on $server.");
1228: } elsif ($answer =~ "^unknown_user") {
1229: &logthis("$uname in $udom attempted to change their password ".
1230: "on $server but were unable to because $server is not ".
1231: "their home server.");
1232: } elsif ($answer =~ "^refused") {
1233: &logthis("$server refused to change $uname in $udom password because ".
1234: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1235: } elsif ($answer =~ "invalid_client") {
1236: &logthis("$server refused to change $uname in $udom password because ".
1237: "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113 raeburn 1238: } elsif ($answer =~ "^prioruse") {
1239: &logthis("$server refused to change $uname in $udom password because ".
1240: "the password had been used before");
1.202 matthew 1241: }
1242: return $answer;
1.1 albertel 1243: }
1244:
1.169 harris41 1245: # ----------------------- Try to determine user's current authentication scheme
1246:
1247: sub queryauthenticate {
1248: my ($uname,$udom)=@_;
1.456 albertel 1249: my $uhome=&homeserver($uname,$udom);
1250: if (!$uhome) {
1251: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1252: return 'no_host';
1253: }
1254: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1255: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1256: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1257: }
1.456 albertel 1258: return $answer;
1.169 harris41 1259: }
1260:
1.1 albertel 1261: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1262:
1.1 albertel 1263: sub authenticate {
1.1073 raeburn 1264: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1265: $upass=&escape($upass);
1266: $uname= &LONCAPA::clean_username($uname);
1.836 www 1267: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1268: my $newhome;
1.836 www 1269: if ((!$uhome) || ($uhome eq 'no_host')) {
1270: # Maybe the machine was offline and only re-appeared again recently?
1271: &reconlonc();
1272: # One more
1.952 raeburn 1273: $uhome=&homeserver($uname,$udom,1);
1274: if (($uhome eq 'no_host') && $checkdefauth) {
1275: if (defined(&domain($udom,'primary'))) {
1276: $newhome=&domain($udom,'primary');
1277: }
1278: if ($newhome ne '') {
1279: $uhome = $newhome;
1280: }
1281: }
1.836 www 1282: if ((!$uhome) || ($uhome eq 'no_host')) {
1283: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1284: return 'no_host';
1285: }
1.1 albertel 1286: }
1.1073 raeburn 1287: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1288: if ($answer eq 'authorized') {
1.952 raeburn 1289: if ($newhome) {
1290: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1291: return 'no_account_on_host';
1292: } else {
1293: &logthis("User $uname at $udom authorized by $uhome");
1294: return $uhome;
1295: }
1.471 albertel 1296: }
1297: if ($answer eq 'non_authorized') {
1298: &logthis("User $uname at $udom rejected by $uhome");
1299: return 'no_host';
1.9 www 1300: }
1.471 albertel 1301: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1302: return 'no_host';
1303: }
1304:
1.1073 raeburn 1305: sub can_host_session {
1.1074 raeburn 1306: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1307: my $canhost = 1;
1.1074 raeburn 1308: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1309: if (ref($remotesessions) eq 'HASH') {
1310: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1311: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1312: $canhost = 0;
1313: } else {
1314: $canhost = 1;
1315: }
1316: }
1317: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1318: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1319: $canhost = 1;
1320: } else {
1321: $canhost = 0;
1322: }
1323: }
1324: if ($canhost) {
1325: if ($remotesessions->{'version'} ne '') {
1326: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1327: if ($reqmajor ne '' && $reqminor ne '') {
1328: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1329: my $major = $1;
1330: my $minor = $2;
1331: if (($major < $reqmajor ) ||
1332: (($major == $reqmajor) && ($minor < $reqminor))) {
1333: $canhost = 0;
1334: }
1335: } else {
1336: $canhost = 0;
1337: }
1338: }
1339: }
1340: }
1341: }
1342: if ($canhost) {
1343: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1344: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1345: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1346: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1347: if (($uint_dom ne '') &&
1348: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1349: $canhost = 0;
1350: } else {
1351: $canhost = 1;
1352: }
1353: }
1354: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1355: if (($uint_dom ne '') &&
1356: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1357: $canhost = 1;
1358: } else {
1359: $canhost = 0;
1360: }
1361: }
1362: }
1363: }
1364: return $canhost;
1365: }
1366:
1.1083 raeburn 1367: sub spare_can_host {
1368: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1369: my $canhost=1;
1.1172.2.62 raeburn 1370: my $try_server_hostname = &hostname($try_server);
1371: my $serverhomeID = &get_server_homeID($try_server_hostname);
1372: my $serverhomedom = &host_domain($serverhomeID);
1373: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1374: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1375: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1376: $canhost = 0;
1377: }
1378: }
1.1172.2.118. .15(raeb 1379:-21): if ($canhost) {
1380:-21): if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1381:-21): if ($defdomdefaults{'offloadoth'}{$try_server}) {
1382:-21): unless (&shared_institution($udom,$try_server)) {
1383:-21): $canhost = 0;
1384:-21): }
1385:-21): }
1386:-21): }
1387:-21): }
1.1172.2.62 raeburn 1388: if (($canhost) && ($uint_dom)) {
1389: my @intdoms;
1390: my $internet_names = &get_internet_names($try_server);
1391: if (ref($internet_names) eq 'ARRAY') {
1392: @intdoms = @{$internet_names};
1393: }
1394: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1395: my $remoterev = &get_server_loncaparev(undef,$try_server);
1396: $canhost = &can_host_session($udom,$try_server,$remoterev,
1397: $remotesessions,
1398: $defdomdefaults{'hostedsessions'});
1399: }
1.1083 raeburn 1400: }
1401: return $canhost;
1402: }
1403:
1.1123 raeburn 1404: sub this_host_spares {
1405: my ($dom) = @_;
1.1126 raeburn 1406: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1407: my @hosts = ¤t_machine_ids();
1408: foreach my $lonhost (@hosts) {
1409: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1410: $dom_in_use = $dom;
1411: $lonhost_in_use = $lonhost;
1.1123 raeburn 1412: last;
1413: }
1414: }
1.1126 raeburn 1415: if ($dom_in_use ne '') {
1416: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1417: }
1418: if (ref($result) ne 'HASH') {
1419: $lonhost_in_use = $perlvar{'lonHostID'};
1420: $dom_in_use = &host_domain($lonhost_in_use);
1421: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1422: if (ref($result) ne 'HASH') {
1423: $result = \%spareid;
1424: }
1425: }
1426: return $result;
1427: }
1428:
1429: sub spares_for_offload {
1430: my ($dom_in_use,$lonhost_in_use) = @_;
1431: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1432: if (defined($cached)) {
1433: return $result;
1434: } else {
1.1126 raeburn 1435: my $cachetime = 60*60*24;
1436: my %domconfig =
1437: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1438: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1439: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1440: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1441: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1442: }
1443: }
1444: }
1445: }
1.1126 raeburn 1446: return;
1.1123 raeburn 1447: }
1448:
1.1129 raeburn 1449: sub get_lonbalancer_config {
1450: my ($servers) = @_;
1451: my ($currbalancer,$currtargets);
1452: if (ref($servers) eq 'HASH') {
1453: foreach my $server (keys(%{$servers})) {
1454: my %what = (
1455: spareid => 1,
1456: perlvar => 1,
1457: );
1458: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1459: if ($result eq 'ok') {
1460: if (ref($returnhash) eq 'HASH') {
1461: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1462: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1463: $currbalancer = $server;
1464: $currtargets = {};
1465: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1466: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1467: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1468: }
1469: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1470: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1471: }
1472: }
1473: last;
1474: }
1475: }
1476: }
1477: }
1478: }
1479: }
1480: return ($currbalancer,$currtargets);
1481: }
1482:
1483: sub check_loadbalancing {
1.1172.2.88 raeburn 1484: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1485: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107 raeburn 1486: $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129 raeburn 1487: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1488: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1489: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1490: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1491: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1492: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1493: my $domneedscache;
1.1129 raeburn 1494: my $cachetime = 60*60*24;
1495:
1496: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1497: $dom_in_use = $udom;
1498: $homeintdom = 1;
1499: } else {
1500: $dom_in_use = $serverhomedom;
1501: }
1502: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1503: unless (defined($cached)) {
1504: my %domconfig =
1505: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1506: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1507: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1508: } else {
1509: $domneedscache = $dom_in_use;
1.1129 raeburn 1510: }
1511: }
1512: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1513: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1514: &check_balancer_result($result,@hosts);
1.1129 raeburn 1515: if ($is_balancer) {
1516: if (ref($currrules) eq 'HASH') {
1517: if ($homeintdom) {
1518: if ($uname ne '') {
1519: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1520: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1521: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1522: $rule_in_effect = $currrules->{'_LC_author'};
1523: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1524: $rule_in_effect = $currrules->{'_LC_adv'}
1525: }
1526: }
1527: if ($rule_in_effect eq '') {
1528: my %userenv = &userenvironment($udom,$uname,'inststatus');
1529: if ($userenv{'inststatus'} ne '') {
1530: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1531: my ($othertitle,$usertypes,$types) =
1532: &Apache::loncommon::sorted_inst_types($udom);
1533: if (ref($types) eq 'ARRAY') {
1534: foreach my $type (@{$types}) {
1535: if (grep(/^\Q$type\E$/,@statuses)) {
1536: if (exists($currrules->{$type})) {
1537: $rule_in_effect = $currrules->{$type};
1538: }
1539: }
1540: }
1541: }
1542: } else {
1543: if (exists($currrules->{'default'})) {
1544: $rule_in_effect = $currrules->{'default'};
1545: }
1546: }
1547: }
1548: } else {
1549: if (exists($currrules->{'default'})) {
1550: $rule_in_effect = $currrules->{'default'};
1551: }
1552: }
1553: } else {
1554: if ($currrules->{'_LC_external'} ne '') {
1555: $rule_in_effect = $currrules->{'_LC_external'};
1556: }
1557: }
1558: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1559: $uname,$udom);
1560: }
1561: }
1562: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1563: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1564: unless (defined($cached)) {
1565: my %domconfig =
1566: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1567: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1568: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1569: } else {
1570: $domneedscache = $serverhomedom;
1.1129 raeburn 1571: }
1572: }
1573: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1574: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1575: &check_balancer_result($result,@hosts);
1576: if ($is_balancer) {
1.1129 raeburn 1577: if (ref($currrules) eq 'HASH') {
1578: if ($currrules->{'_LC_internetdom'} ne '') {
1579: $rule_in_effect = $currrules->{'_LC_internetdom'};
1580: }
1581: }
1582: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1583: $uname,$udom);
1584: }
1585: } else {
1586: if ($perlvar{'lonBalancer'} eq 'yes') {
1587: $is_balancer = 1;
1588: $offloadto = &this_host_spares($dom_in_use);
1589: }
1.1172.2.75 raeburn 1590: unless (defined($cached)) {
1591: $domneedscache = $serverhomedom;
1592: }
1.1129 raeburn 1593: }
1594: } else {
1595: if ($perlvar{'lonBalancer'} eq 'yes') {
1596: $is_balancer = 1;
1597: $offloadto = &this_host_spares($dom_in_use);
1598: }
1.1172.2.75 raeburn 1599: unless (defined($cached)) {
1600: $domneedscache = $serverhomedom;
1601: }
1602: }
1603: if ($domneedscache) {
1604: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1605: }
1.1172.2.118. .11(raeb 1606:-20): if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5 raeburn 1607: my $lowest_load = 30000;
1608: if (ref($offloadto) eq 'HASH') {
1609: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1610: foreach my $try_server (@{$offloadto->{'primary'}}) {
1611: ($otherserver,$lowest_load) =
1612: &compare_server_load($try_server,$otherserver,$lowest_load);
1613: }
1.1129 raeburn 1614: }
1.1172.2.5 raeburn 1615: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1616:
1.1172.2.5 raeburn 1617: if (!$found_server) {
1618: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1619: foreach my $try_server (@{$offloadto->{'default'}}) {
1620: ($otherserver,$lowest_load) =
1621: &compare_server_load($try_server,$otherserver,$lowest_load);
1622: }
1623: }
1624: }
1625: } elsif (ref($offloadto) eq 'ARRAY') {
1626: if (@{$offloadto} == 1) {
1627: $otherserver = $offloadto->[0];
1628: } elsif (@{$offloadto} > 1) {
1629: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1630: ($otherserver,$lowest_load) =
1631: &compare_server_load($try_server,$otherserver,$lowest_load);
1632: }
1633: }
1634: }
1.1172.2.88 raeburn 1635: unless ($caller eq 'login') {
1636: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1637: $is_balancer = 0;
1638: if ($uname ne '' && $udom ne '') {
1639: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1640: &appenv({'user.loadbalexempt' => $lonhost,
1641: 'user.loadbalcheck.time' => time});
1642: }
1.1172.2.5 raeburn 1643: }
1.1129 raeburn 1644: }
1645: }
1.1172.2.118. .11(raeb 1646:-20): }
1647:-20): if (($is_balancer) && (!$homeintdom)) {
1648:-20): undef($setcookie);
1.1129 raeburn 1649: }
1.1172.2.107 raeburn 1650: return ($is_balancer,$otherserver,$setcookie);
1.1129 raeburn 1651: }
1652:
1.1172.2.12 raeburn 1653: sub check_balancer_result {
1654: my ($result,@hosts) = @_;
1.1172.2.107 raeburn 1655: my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1656: if (ref($result) eq 'HASH') {
1657: if ($result->{'lonhost'} ne '') {
1658: my $currbalancer = $result->{'lonhost'};
1659: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1660: $is_balancer = 1;
1661: $currtargets = $result->{'targets'};
1662: $currrules = $result->{'rules'};
1663: }
1664: } else {
1665: foreach my $key (keys(%{$result})) {
1666: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1667: (ref($result->{$key}) eq 'HASH')) {
1668: $is_balancer = 1;
1669: $currrules = $result->{$key}{'rules'};
1670: $currtargets = $result->{$key}{'targets'};
1.1172.2.107 raeburn 1671: $setcookie = $result->{$key}{'cookie'};
1.1172.2.12 raeburn 1672: last;
1673: }
1674: }
1675: }
1676: }
1.1172.2.107 raeburn 1677: return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1678: }
1679:
1.1129 raeburn 1680: sub get_loadbalancer_targets {
1681: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1682: my $offloadto;
1.1172.2.4 raeburn 1683: if ($rule_in_effect eq 'none') {
1684: return [$perlvar{'lonHostID'}];
1685: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1686: $offloadto = $currtargets;
1687: } else {
1688: if ($rule_in_effect eq 'homeserver') {
1689: my $homeserver = &homeserver($uname,$udom);
1690: if ($homeserver ne 'no_host') {
1691: $offloadto = [$homeserver];
1692: }
1693: } elsif ($rule_in_effect eq 'externalbalancer') {
1694: my %domconfig =
1695: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1696: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1697: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1698: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1699: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1700: }
1701: }
1702: } else {
1.1172.2.7 raeburn 1703: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1704: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1705: if (&hostname($remotebalancer) ne '') {
1706: $offloadto = [$remotebalancer];
1707: }
1708: }
1709: } elsif (&hostname($rule_in_effect) ne '') {
1710: $offloadto = [$rule_in_effect];
1711: }
1712: }
1713: return $offloadto;
1714: }
1715:
1.1127 raeburn 1716: sub internet_dom_servers {
1717: my ($dom) = @_;
1718: my (%uniqservers,%servers);
1719: my $primaryserver = &hostname(&domain($dom,'primary'));
1720: my @machinedoms = &machine_domains($primaryserver);
1721: foreach my $mdom (@machinedoms) {
1722: my %currservers = %servers;
1723: my %server = &get_servers($mdom);
1724: %servers = (%currservers,%server);
1725: }
1726: my %by_hostname;
1727: foreach my $id (keys(%servers)) {
1728: push(@{$by_hostname{$servers{$id}}},$id);
1729: }
1730: foreach my $hostname (sort(keys(%by_hostname))) {
1731: if (@{$by_hostname{$hostname}} > 1) {
1732: my $match = 0;
1733: foreach my $id (@{$by_hostname{$hostname}}) {
1734: if (&host_domain($id) eq $dom) {
1735: $uniqservers{$id} = $hostname;
1736: $match = 1;
1737: }
1738: }
1739: unless ($match) {
1740: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1741: }
1742: } else {
1743: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1744: }
1745: }
1746: return %uniqservers;
1747: }
1748:
1.1 albertel 1749: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1750:
1.599 albertel 1751: my %homecache;
1.1 albertel 1752: sub homeserver {
1.230 stredwic 1753: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1754: my $index="$uname:$udom";
1.426 albertel 1755:
1.599 albertel 1756: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1757:
1758: my %servers = &get_servers($udom,'library');
1759: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1760: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1761: exists($badServerCache{$tryserver}));
1.841 albertel 1762:
1763: my $answer=reply("home:$udom:$uname",$tryserver);
1764: if ($answer eq 'found') {
1765: delete($badServerCache{$tryserver});
1766: return $homecache{$index}=$tryserver;
1767: } elsif ($answer eq 'no_host') {
1768: $badServerCache{$tryserver}=1;
1769: }
1.1 albertel 1770: }
1771: return 'no_host';
1.70 www 1772: }
1773:
1774: # ------------------------------------- Find the usernames behind a list of IDs
1775:
1776: sub idget {
1777: my ($udom,@ids)=@_;
1778: my %returnhash=();
1779:
1.841 albertel 1780: my %servers = &get_servers($udom,'library');
1781: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1782: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1783: $idlist=~tr/A-Z/a-z/;
1784: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1785: my @answer=();
1786: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1787: @answer=split(/\&/,$reply);
1788: } ;
1789: my $i;
1790: for ($i=0;$i<=$#ids;$i++) {
1791: if ($answer[$i]) {
1.1172.2.73 raeburn 1792: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1793: }
1794: }
1795: }
1.70 www 1796: return %returnhash;
1797: }
1798:
1799: # ------------------------------------- Find the IDs behind a list of usernames
1800:
1801: sub idrget {
1802: my ($udom,@unames)=@_;
1803: my %returnhash=();
1.800 albertel 1804: foreach my $uname (@unames) {
1805: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1806: }
1.70 www 1807: return %returnhash;
1808: }
1809:
1810: # ------------------------------- Store away a list of names and associated IDs
1811:
1812: sub idput {
1813: my ($udom,%ids)=@_;
1814: my %servers=();
1.800 albertel 1815: foreach my $uname (keys(%ids)) {
1816: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1817: my $uhom=&homeserver($uname,$udom);
1.70 www 1818: if ($uhom ne 'no_host') {
1.800 albertel 1819: my $id=&escape($ids{$uname});
1.70 www 1820: $id=~tr/A-Z/a-z/;
1.800 albertel 1821: my $esc_unam=&escape($uname);
1.70 www 1822: if ($servers{$uhom}) {
1.800 albertel 1823: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1824: } else {
1.800 albertel 1825: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1826: }
1827: }
1.191 harris41 1828: }
1.800 albertel 1829: foreach my $server (keys(%servers)) {
1830: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1831: }
1.344 www 1832: }
1833:
1.1172.2.30 raeburn 1834: # ---------------------------------------- Delete unwanted IDs from ids.db file
1835:
1836: sub iddel {
1837: my ($udom,$idshashref,$uhome)=@_;
1838: my %result=();
1839: unless (ref($idshashref) eq 'HASH') {
1840: return %result;
1841: }
1842: my %servers=();
1843: while (my ($id,$uname) = each(%{$idshashref})) {
1844: my $uhom;
1845: if ($uhome) {
1846: $uhom = $uhome;
1847: } else {
1848: $uhom=&homeserver($uname,$udom);
1849: }
1850: if ($uhom ne 'no_host') {
1851: if ($servers{$uhom}) {
1852: $servers{$uhom}.='&'.&escape($id);
1853: } else {
1854: $servers{$uhom}=&escape($id);
1855: }
1856: }
1857: }
1858: foreach my $server (keys(%servers)) {
1859: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1860: }
1861: return %result;
1862: }
1863:
1.1023 raeburn 1864: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1865: sub dump_dom {
1.1165 droeschl 1866: my ($namespace, $udom, $regexp) = @_;
1867:
1868: $udom ||= $env{'user.domain'};
1869:
1870: return () unless $udom;
1871:
1872: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1873: }
1874:
1.1023 raeburn 1875: # ------------------------------------------ get items from domain db files
1.806 raeburn 1876:
1877: sub get_dom {
1.860 raeburn 1878: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1879: return if ($udom eq 'public');
1.806 raeburn 1880: my $items='';
1881: foreach my $item (@$storearr) {
1882: $items.=&escape($item).'&';
1883: }
1884: $items=~s/\&$//;
1.860 raeburn 1885: if (!$udom) {
1886: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1887: return if ($udom eq 'public');
1.860 raeburn 1888: if (defined(&domain($udom,'primary'))) {
1889: $uhome=&domain($udom,'primary');
1890: } else {
1.874 albertel 1891: undef($uhome);
1.860 raeburn 1892: }
1893: } else {
1894: if (!$uhome) {
1895: if (defined(&domain($udom,'primary'))) {
1896: $uhome=&domain($udom,'primary');
1897: }
1898: }
1899: }
1900: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.118. .1(raebu 1901:20): my $rep;
.18(raeb 1902:-21): if (grep { $_ eq $uhome } ¤t_machine_ids()) {
1903:-21): # domain information is hosted on this machine
1904:-21): my $cmd = 'getdom';
1905:-21): if ($namespace =~ /^enc/) {
1906:-21): $cmd = 'egetdom';
1907:-21): }
1908:-21): $rep = &LONCAPA::Lond::get_dom("$cmd:$udom:$namespace:$items");
.1(raebu 1909:20): } else {
.18(raeb 1910:-21): if ($namespace =~ /^enc/) {
1911:-21): $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
1912:-21): } else {
1913:-21): $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1914:-21): }
.1(raebu 1915:20): }
1.866 raeburn 1916: my %returnhash;
1.875 albertel 1917: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1918: return %returnhash;
1919: }
1.806 raeburn 1920: my @pairs=split(/\&/,$rep);
1921: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1922: return @pairs;
1923: }
1924: my $i=0;
1925: foreach my $item (@$storearr) {
1926: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1927: $i++;
1928: }
1929: return %returnhash;
1930: } else {
1.880 banghart 1931: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1932: }
1933: }
1934:
1935: # -------------------------------------------- put items in domain db files
1936:
1937: sub put_dom {
1.860 raeburn 1938: my ($namespace,$storehash,$udom,$uhome)=@_;
1939: if (!$udom) {
1940: $udom=$env{'user.domain'};
1941: if (defined(&domain($udom,'primary'))) {
1942: $uhome=&domain($udom,'primary');
1943: } else {
1.874 albertel 1944: undef($uhome);
1.860 raeburn 1945: }
1946: } else {
1947: if (!$uhome) {
1948: if (defined(&domain($udom,'primary'))) {
1949: $uhome=&domain($udom,'primary');
1950: }
1951: }
1952: }
1953: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1954: my $items='';
1955: foreach my $item (keys(%$storehash)) {
1956: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1957: }
1958: $items=~s/\&$//;
1.1172.2.118. .1(raebu 1959:20): if ($namespace =~ /^enc/) {
1960:20): return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
1961:20): } else {
1962:20): return &reply("putdom:$udom:$namespace:$items",$uhome);
1963:20): }
1.806 raeburn 1964: } else {
1.860 raeburn 1965: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1966: }
1967: }
1968:
1.1023 raeburn 1969: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1970: sub newput_dom {
1.1023 raeburn 1971: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1972: my $result;
1973: if (!$udom) {
1974: $udom=$env{'user.domain'};
1975: }
1.1023 raeburn 1976: if ($udom) {
1977: my $uname = &get_domainconfiguser($udom);
1978: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1979: }
1980: return $result;
1981: }
1982:
1.1023 raeburn 1983: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1984: sub del_dom {
1.1023 raeburn 1985: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1986: if (ref($storearr) eq 'ARRAY') {
1987: if (!$udom) {
1988: $udom=$env{'user.domain'};
1989: }
1.1023 raeburn 1990: if ($udom) {
1991: my $uname = &get_domainconfiguser($udom);
1992: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1993: }
1994: }
1995: }
1996:
1.1023 raeburn 1997: # ----------------------------------construct domainconfig user for a domain
1998: sub get_domainconfiguser {
1999: my ($udom) = @_;
2000: return $udom.'-domainconfig';
2001: }
2002:
1.837 raeburn 2003: sub retrieve_inst_usertypes {
2004: my ($udom) = @_;
2005: my (%returnhash,@order);
1.989 raeburn 2006: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2007: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2008: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 2009: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2010: } else {
2011: if (defined(&domain($udom,'primary'))) {
2012: my $uhome=&domain($udom,'primary');
2013: my $rep=&reply("inst_usertypes:$udom",$uhome);
2014: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 2015: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2016: return (\%returnhash,\@order);
2017: }
2018: my ($hashitems,$orderitems) = split(/:/,$rep);
2019: my @pairs=split(/\&/,$hashitems);
2020: foreach my $item (@pairs) {
2021: my ($key,$value)=split(/=/,$item,2);
2022: $key = &unescape($key);
2023: next if ($key =~ /^error: 2 /);
2024: $returnhash{$key}=&thaw_unescape($value);
2025: }
2026: my @esc_order = split(/\&/,$orderitems);
2027: foreach my $item (@esc_order) {
2028: push(@order,&unescape($item));
2029: }
2030: } else {
1.1172.2.44 raeburn 2031: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2032: }
1.1172.2.44 raeburn 2033: return (\%returnhash,\@order);
1.837 raeburn 2034: }
2035: }
2036:
1.868 raeburn 2037: sub is_domainimage {
2038: my ($url) = @_;
1.1172.2.74 raeburn 2039: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 2040: if (&domain($1) ne '') {
2041: return '1';
2042: }
2043: }
2044: return;
2045: }
2046:
1.899 raeburn 2047: sub inst_directory_query {
2048: my ($srch) = @_;
2049: my $udom = $srch->{'srchdomain'};
2050: my %results;
2051: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2052: my $outcome;
1.899 raeburn 2053: if ($homeserver ne '') {
1.1172.2.116 raeburn 2054: unless ($homeserver eq $perlvar{'lonHostID'}) {
2055: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2056: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116 raeburn 2057: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2058: if (($major eq '' && $minor eq '') || ($major < 2) ||
2059: (($major == 2) && ($minor < 11)) ||
2060: (($major == 2) && ($minor == 11) && ($subver < 3))) {
2061: return;
2062: }
2063: }
2064: }
1.904 albertel 2065: my $queryid=&reply("querysend:instdirsearch:".
2066: &escape($srch->{'srchby'}).':'.
2067: &escape($srch->{'srchterm'}).':'.
2068: &escape($srch->{'srchtype'}),$homeserver);
2069: my $host=&hostname($homeserver);
2070: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96 raeburn 2071: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2072: return;
2073: }
2074: my $response = &get_query_reply($queryid);
2075: my $maxtries = 5;
2076: my $tries = 1;
2077: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2078: $response = &get_query_reply($queryid);
2079: $tries ++;
2080: }
2081:
2082: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2083: if ($response eq 'unavailable') {
2084: $outcome = $response;
2085: } else {
2086: $outcome = 'ok';
2087: my @matches = split(/\n/,$response);
2088: foreach my $match (@matches) {
2089: my ($key,$value) = split(/=/,$match);
2090: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2091: }
1.899 raeburn 2092: }
2093: }
2094: }
1.909 raeburn 2095: return ($outcome,%results);
1.899 raeburn 2096: }
2097:
2098: sub usersearch {
2099: my ($srch) = @_;
2100: my $dom = $srch->{'srchdomain'};
2101: my %results;
2102: my %libserv = &all_library();
2103: my $query = 'usersearch';
2104: foreach my $tryserver (keys(%libserv)) {
2105: if (&host_domain($tryserver) eq $dom) {
1.1172.2.116 raeburn 2106: unless ($tryserver eq $perlvar{'lonHostID'}) {
2107: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2108: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.118. .2(raebu 2109:20): my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116 raeburn 2110: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2111: (($major == 2) && ($minor < 11)) ||
2112: (($major == 2) && ($minor == 11) && ($subver < 3)));
2113: }
2114: }
1.899 raeburn 2115: my $host=&hostname($tryserver);
2116: my $queryid=
1.911 raeburn 2117: &reply("querysend:".&escape($query).':'.
2118: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2119: &escape($srch->{'srchtype'}).':'.
2120: &escape($srch->{'srchterm'}),$tryserver);
2121: if ($queryid !~/^\Q$host\E\_/) {
2122: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2123: next;
1.899 raeburn 2124: }
2125: my $reply = &get_query_reply($queryid);
2126: my $maxtries = 1;
2127: my $tries = 1;
2128: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2129: $reply = &get_query_reply($queryid);
2130: $tries ++;
2131: }
2132: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2133: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2134: } else {
1.911 raeburn 2135: my @matches;
2136: if ($reply =~ /\n/) {
2137: @matches = split(/\n/,$reply);
2138: } else {
2139: @matches = split(/\&/,$reply);
2140: }
1.899 raeburn 2141: foreach my $match (@matches) {
2142: my ($uname,$udom,%userhash);
1.911 raeburn 2143: foreach my $entry (split(/:/,$match)) {
2144: my ($key,$value) =
2145: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2146: $userhash{$key} = $value;
2147: if ($key eq 'username') {
2148: $uname = $value;
2149: } elsif ($key eq 'domain') {
2150: $udom = $value;
1.911 raeburn 2151: }
1.899 raeburn 2152: }
2153: $results{$uname.':'.$udom} = \%userhash;
2154: }
2155: }
2156: }
2157: }
2158: return %results;
2159: }
2160:
1.912 raeburn 2161: sub get_instuser {
2162: my ($udom,$uname,$id) = @_;
2163: my $homeserver = &domain($udom,'primary');
2164: my ($outcome,%results);
2165: if ($homeserver ne '') {
2166: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2167: &escape($id).':'.&escape($udom),$homeserver);
2168: my $host=&hostname($homeserver);
2169: if ($queryid !~/^\Q$host\E\_/) {
2170: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2171: return;
2172: }
2173: my $response = &get_query_reply($queryid);
2174: my $maxtries = 5;
2175: my $tries = 1;
2176: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2177: $response = &get_query_reply($queryid);
2178: $tries ++;
2179: }
2180: if (!&error($response) && $response ne 'refused') {
2181: if ($response eq 'unavailable') {
2182: $outcome = $response;
2183: } else {
2184: $outcome = 'ok';
2185: my @matches = split(/\n/,$response);
2186: foreach my $match (@matches) {
2187: my ($key,$value) = split(/=/,$match);
2188: $results{&unescape($key)} = &thaw_unescape($value);
2189: }
2190: }
2191: }
2192: }
2193: my %userinfo;
2194: if (ref($results{$uname}) eq 'HASH') {
2195: %userinfo = %{$results{$uname}};
2196: }
2197: return ($outcome,%userinfo);
2198: }
2199:
1.1172.2.69 raeburn 2200: sub get_multiple_instusers {
2201: my ($udom,$users,$caller) = @_;
2202: my ($outcome,$results);
2203: if (ref($users) eq 'HASH') {
2204: my $count = keys(%{$users});
2205: my $requested = &freeze_escape($users);
2206: my $homeserver = &domain($udom,'primary');
2207: if ($homeserver ne '') {
2208: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2209: my $host=&hostname($homeserver);
2210: if ($queryid !~/^\Q$host\E\_/) {
2211: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2212: ' for host: '.$homeserver.'in domain '.$udom);
2213: return ($outcome,$results);
2214: }
2215: my $response = &get_query_reply($queryid);
2216: my $maxtries = 5;
2217: if ($count > 100) {
2218: $maxtries = 1+int($count/20);
2219: }
2220: my $tries = 1;
2221: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2222: $response = &get_query_reply($queryid);
2223: $tries ++;
2224: }
2225: if ($response eq '') {
2226: $results = {};
2227: foreach my $key (keys(%{$users})) {
2228: my ($uname,$id);
2229: if ($caller eq 'id') {
2230: $id = $key;
2231: } else {
2232: $uname = $key;
2233: }
2234: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2235: $outcome = $resp;
2236: if ($resp eq 'ok') {
2237: %{$results} = (%{$results}, %info);
2238: } else {
2239: last;
2240: }
2241: }
2242: } elsif(!&error($response) && ($response ne 'refused')) {
2243: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2244: $outcome = $response;
2245: } else {
2246: ($outcome,my $userdata) = split(/=/,$response,2);
2247: if ($outcome eq 'ok') {
2248: $results = &thaw_unescape($userdata);
2249: }
2250: }
2251: }
2252: }
2253: }
2254: return ($outcome,$results);
2255: }
2256:
1.912 raeburn 2257: sub inst_rulecheck {
1.923 raeburn 2258: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2259: my %returnhash;
2260: if ($udom ne '') {
2261: if (ref($rules) eq 'ARRAY') {
2262: @{$rules} = map {&escape($_);} (@{$rules});
2263: my $rulestr = join(':',@{$rules});
2264: my $homeserver=&domain($udom,'primary');
2265: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2266: my $response;
2267: if ($item eq 'username') {
2268: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2269: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2270: $homeserver));
1.923 raeburn 2271: } elsif ($item eq 'id') {
2272: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2273: ':'.&escape($id).':'.$rulestr,
2274: $homeserver));
1.945 raeburn 2275: } elsif ($item eq 'selfcreate') {
2276: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2277: &escape($udom).':'.&escape($uname).
2278: ':'.$rulestr,$homeserver));
1.923 raeburn 2279: }
1.912 raeburn 2280: if ($response ne 'refused') {
2281: my @pairs=split(/\&/,$response);
2282: foreach my $item (@pairs) {
2283: my ($key,$value)=split(/=/,$item,2);
2284: $key = &unescape($key);
2285: next if ($key =~ /^error: 2 /);
2286: $returnhash{$key}=&thaw_unescape($value);
2287: }
2288: }
2289: }
2290: }
2291: }
2292: return %returnhash;
2293: }
2294:
2295: sub inst_userrules {
1.923 raeburn 2296: my ($udom,$check) = @_;
1.912 raeburn 2297: my (%ruleshash,@ruleorder);
2298: if ($udom ne '') {
2299: my $homeserver=&domain($udom,'primary');
2300: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2301: my $response;
2302: if ($check eq 'id') {
2303: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2304: $homeserver);
1.943 raeburn 2305: } elsif ($check eq 'email') {
2306: $response=&reply('instemailrules:'.&escape($udom),
2307: $homeserver);
1.923 raeburn 2308: } else {
2309: $response=&reply('instuserrules:'.&escape($udom),
2310: $homeserver);
2311: }
1.912 raeburn 2312: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2313: ($response ne 'unknown_cmd') &&
1.912 raeburn 2314: ($response ne 'no_such_host')) {
2315: my ($hashitems,$orderitems) = split(/:/,$response);
2316: my @pairs=split(/\&/,$hashitems);
2317: foreach my $item (@pairs) {
2318: my ($key,$value)=split(/=/,$item,2);
2319: $key = &unescape($key);
2320: next if ($key =~ /^error: 2 /);
2321: $ruleshash{$key}=&thaw_unescape($value);
2322: }
2323: my @esc_order = split(/\&/,$orderitems);
2324: foreach my $item (@esc_order) {
2325: push(@ruleorder,&unescape($item));
2326: }
2327: }
2328: }
2329: }
2330: return (\%ruleshash,\@ruleorder);
2331: }
2332:
1.976 raeburn 2333: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2334:
2335: sub get_domain_defaults {
1.1172.2.35 raeburn 2336: my ($domain,$ignore_cache) = @_;
2337: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2338: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2339: unless ($ignore_cache) {
2340: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2341: if (defined($cached)) {
2342: if (ref($result) eq 'HASH') {
2343: return %{$result};
2344: }
1.943 raeburn 2345: }
2346: }
2347: my %domdefaults;
2348: my %domconfig =
1.989 raeburn 2349: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2350: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2351: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2352: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2353: 'coursecategories','autoenroll',
2354: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2355: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2356: if (ref($domconfig{'defaults'}) eq 'HASH') {
2357: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2358: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2359: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2360: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2361: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2362: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2363: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2364: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2365: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2366: } else {
2367: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2368: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2369: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2370: }
1.976 raeburn 2371: if (ref($domconfig{'quotas'}) eq 'HASH') {
2372: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2373: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2374: } else {
2375: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2376: }
1.1172.2.6 raeburn 2377: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2378: foreach my $item (@usertools) {
2379: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2380: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2381: }
2382: }
1.1172.2.29 raeburn 2383: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2384: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2385: }
1.976 raeburn 2386: }
1.985 raeburn 2387: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2388: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2389: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2390: }
2391: }
1.1172.2.9 raeburn 2392: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2393: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2394: }
1.989 raeburn 2395: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2396: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2397: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2398: }
2399: }
1.1047 raeburn 2400: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2401: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2402: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2403: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2404: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2405: }
1.1172.2.41 raeburn 2406: foreach my $type (@coursetypes) {
2407: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2408: unless ($type eq 'community') {
2409: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2410: }
2411: }
2412: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2413: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2414: }
1.1172.2.60 raeburn 2415: if ($domdefaults{'postsubmit'} eq 'on') {
2416: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2417: $domdefaults{$type.'postsubtimeout'} =
2418: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2419: }
2420: }
1.1172.2.30 raeburn 2421: }
1.1172.2.67 raeburn 2422: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2423: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2424: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2425: if (@clonecodes) {
2426: $domdefaults{'canclone'} = join('+',@clonecodes);
2427: }
2428: }
2429: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2430: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2431: }
1.1172.2.103 raeburn 2432: if ($domconfig{'coursedefaults'}{'texengine'}) {
2433: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2434: }
1.1047 raeburn 2435: }
1.1073 raeburn 2436: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2437: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2438: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2439: }
2440: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2441: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2442: }
1.1172.2.62 raeburn 2443: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2444: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2445: }
1.1172.2.118. .16(raeb 2446:-21): if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
.15(raeb 2447:-21): $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2448:-21): }
1.1073 raeburn 2449: }
1.1172.2.41 raeburn 2450: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2451: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2452: my @settings = ('types','registered','enroll_dates','access_dates','section',
2453: 'approval','limit');
2454: foreach my $type (@coursetypes) {
2455: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2456: my @mgrdc = ();
2457: foreach my $item (@settings) {
2458: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2459: push(@mgrdc,$item);
2460: }
2461: }
2462: if (@mgrdc) {
2463: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2464: }
2465: }
2466: }
2467: }
2468: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2469: foreach my $type (@coursetypes) {
2470: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2471: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2472: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2473: }
2474: }
2475: }
2476: }
2477: }
1.1172.2.46 raeburn 2478: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2479: $domdefaults{'catauth'} = 'std';
2480: $domdefaults{'catunauth'} = 'std';
2481: if ($domconfig{'coursecategories'}{'auth'}) {
2482: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2483: }
2484: if ($domconfig{'coursecategories'}{'unauth'}) {
2485: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2486: }
2487: }
1.1172.2.76 raeburn 2488: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2489: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2490: }
1.1172.2.89 raeburn 2491: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2492: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2493: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2494: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2495: }
2496: }
1.1172.2.23 raeburn 2497: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2498: return %domdefaults;
2499: }
2500:
1.1172.2.106 raeburn 2501: sub get_dom_cats {
2502: my ($dom) = @_;
2503: return unless (&domain($dom));
2504: my ($cats,$cached)=&is_cached_new('cats',$dom);
2505: unless (defined($cached)) {
2506: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2507: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2508: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2509: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2510: } else {
2511: $cats = {};
2512: }
2513: } else {
2514: $cats = {};
2515: }
2516: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2517: }
2518: return $cats;
2519: }
2520:
2521: sub get_dom_instcats {
2522: my ($dom) = @_;
2523: return unless (&domain($dom));
2524: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2525: unless (defined($cached)) {
2526: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2527: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2528: if ($totcodes > 0) {
2529: my $caller = 'global';
2530: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2531: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2532: $instcats = {
2533: codes => \%codes,
2534: codetitles => \@codetitles,
2535: cat_titles => \%cat_titles,
2536: cat_order => \%cat_order,
2537: };
2538: &do_cache_new('instcats',$dom,$instcats,3600);
2539: }
2540: }
2541: }
2542: return $instcats;
2543: }
2544:
2545: sub retrieve_instcodes {
2546: my ($coursecodes,$dom) = @_;
2547: my $totcodes;
2548: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2549: foreach my $course (keys(%courses)) {
2550: if (ref($courses{$course}) eq 'HASH') {
2551: if ($courses{$course}{'inst_code'} ne '') {
2552: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2553: $totcodes ++;
2554: }
2555: }
2556: }
2557: return $totcodes;
2558: }
2559:
1.1172.2.113 raeburn 2560: # --------------------------------------------- Get domain config for passwords
2561:
2562: sub get_passwdconf {
2563: my ($dom) = @_;
2564: my (%passwdconf,$gotconf,$lookup);
2565: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2566: if (defined($cached)) {
2567: if (ref($result) eq 'HASH') {
2568: %passwdconf = %{$result};
2569: $gotconf = 1;
2570: }
2571: }
2572: unless ($gotconf) {
2573: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2574: if (ref($domconfig{'passwords'}) eq 'HASH') {
2575: %passwdconf = %{$domconfig{'passwords'}};
2576: }
2577: my $cachetime = 24*60*60;
2578: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2579: }
2580: return %passwdconf;
2581: }
2582:
1.1172.2.118. .1(raebu 2583:20): sub course_portal_url {
2584:20): my ($cnum,$cdom) = @_;
2585:20): my $chome = &homeserver($cnum,$cdom);
2586:20): my $hostname = &hostname($chome);
2587:20): my $protocol = $protocol{$chome};
2588:20): $protocol = 'http' if ($protocol ne 'https');
2589:20): my %domdefaults = &get_domain_defaults($cdom);
2590:20): my $firsturl;
2591:20): if ($domdefaults{'portal_def'}) {
2592:20): $firsturl = $domdefaults{'portal_def'};
2593:20): } else {
2594:20): $firsturl = $protocol.'://'.$hostname;
2595:20): }
2596:20): return $firsturl;
2597:20): }
2598:20):
1.344 www 2599: # --------------------------------------------------- Assign a key to a student
2600:
2601: sub assign_access_key {
1.364 www 2602: #
2603: # a valid key looks like uname:udom#comments
2604: # comments are being appended
2605: #
1.498 www 2606: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2607: $kdom=
1.620 albertel 2608: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2609: $knum=
1.620 albertel 2610: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2611: $cdom=
1.620 albertel 2612: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2613: $cnum=
1.620 albertel 2614: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2615: $udom=$env{'user.name'} unless (defined($udom));
2616: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2617: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2618: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2619: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2620: # assigned to this person
2621: # - this should not happen,
1.345 www 2622: # unless something went wrong
2623: # the first time around
2624: # ready to assign
1.364 www 2625: $logentry=$1.'; '.$logentry;
1.496 www 2626: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2627: $kdom,$knum) eq 'ok') {
1.345 www 2628: # key now belongs to user
1.346 www 2629: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2630: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2631: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2632: return 'ok';
2633: } else {
2634: return
2635: 'error: Count not permanently assign key, will need to be re-entered later.';
2636: }
2637: } else {
2638: return 'error: Could not assign key, try again later.';
2639: }
1.364 www 2640: } elsif (!$existing{$ckey}) {
1.345 www 2641: # the key does not exist
2642: return 'error: The key does not exist';
2643: } else {
2644: # the key is somebody else's
2645: return 'error: The key is already in use';
2646: }
1.344 www 2647: }
2648:
1.364 www 2649: # ------------------------------------------ put an additional comment on a key
2650:
2651: sub comment_access_key {
2652: #
2653: # a valid key looks like uname:udom#comments
2654: # comments are being appended
2655: #
2656: my ($ckey,$cdom,$cnum,$logentry)=@_;
2657: $cdom=
1.620 albertel 2658: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2659: $cnum=
1.620 albertel 2660: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2661: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2662: if ($existing{$ckey}) {
2663: $existing{$ckey}.='; '.$logentry;
2664: # ready to assign
1.367 www 2665: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2666: $cdom,$cnum) eq 'ok') {
2667: return 'ok';
2668: } else {
2669: return 'error: Count not store comment.';
2670: }
2671: } else {
2672: # the key does not exist
2673: return 'error: The key does not exist';
2674: }
2675: }
2676:
1.344 www 2677: # ------------------------------------------------------ Generate a set of keys
2678:
2679: sub generate_access_keys {
1.364 www 2680: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2681: $cdom=
1.620 albertel 2682: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2683: $cnum=
1.620 albertel 2684: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2685: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2686: unless (($cdom) && ($cnum)) { return 0; }
2687: if ($number>10000) { return 0; }
2688: sleep(2); # make sure don't get same seed twice
2689: srand(time()^($$+($$<<15))); # from "Programming Perl"
2690: my $total=0;
2691: for (my $i=1;$i<=$number;$i++) {
2692: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2693: sprintf("%lx",int(100000*rand)).'-'.
2694: sprintf("%lx",int(100000*rand));
2695: $newkey=~s/1/g/g; # folks mix up 1 and l
2696: $newkey=~s/0/h/g; # and also 0 and O
2697: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2698: if ($existing{$newkey}) {
2699: $i--;
2700: } else {
1.364 www 2701: if (&put('accesskeys',
2702: { $newkey => '# generated '.localtime().
1.620 albertel 2703: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2704: '; '.$logentry },
2705: $cdom,$cnum) eq 'ok') {
1.344 www 2706: $total++;
2707: }
2708: }
2709: }
1.620 albertel 2710: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2711: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2712: return $total;
2713: }
2714:
2715: # ------------------------------------------------------- Validate an accesskey
2716:
2717: sub validate_access_key {
2718: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2719: $cdom=
1.620 albertel 2720: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2721: $cnum=
1.620 albertel 2722: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2723: $udom=$env{'user.domain'} unless (defined($udom));
2724: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2725: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2726: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2727: }
2728:
2729: # ------------------------------------- Find the section of student in a course
1.652 albertel 2730: sub devalidate_getsection_cache {
2731: my ($udom,$unam,$courseid)=@_;
2732: my $hashid="$udom:$unam:$courseid";
2733: &devalidate_cache_new('getsection',$hashid);
2734: }
1.298 matthew 2735:
1.815 albertel 2736: sub courseid_to_courseurl {
2737: my ($courseid) = @_;
2738: #already url style courseid
2739: return $courseid if ($courseid =~ m{^/});
2740:
2741: if (exists($env{'course.'.$courseid.'.num'})) {
2742: my $cnum = $env{'course.'.$courseid.'.num'};
2743: my $cdom = $env{'course.'.$courseid.'.domain'};
2744: return "/$cdom/$cnum";
2745: }
2746:
2747: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2748: if (exists($courseinfo{'num'})) {
2749: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2750: }
2751:
2752: return undef;
2753: }
2754:
1.298 matthew 2755: sub getsection {
2756: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2757: my $cachetime=1800;
1.551 albertel 2758:
2759: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2760: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2761: if (defined($cached)) { return $result; }
2762:
1.298 matthew 2763: my %Pending;
2764: my %Expired;
2765: #
2766: # Each role can either have not started yet (pending), be active,
2767: # or have expired.
2768: #
2769: # If there is an active role, we are done.
2770: #
2771: # If there is more than one role which has not started yet,
2772: # choose the one which will start sooner
2773: # If there is one role which has not started yet, return it.
2774: #
2775: # If there is more than one expired role, choose the one which ended last.
2776: # If there is a role which has expired, return it.
2777: #
1.815 albertel 2778: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2779: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2780: foreach my $key (keys(%roleshash)) {
1.479 albertel 2781: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2782: my $section=$1;
2783: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2784: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2785: my $now=time;
1.548 albertel 2786: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2787: $Expired{$end}=$section;
2788: next;
2789: }
1.548 albertel 2790: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2791: $Pending{$start}=$section;
2792: next;
2793: }
1.599 albertel 2794: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2795: }
2796: #
2797: # Presumedly there will be few matching roles from the above
2798: # loop and the sorting time will be negligible.
2799: if (scalar(keys(%Pending))) {
2800: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2801: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2802: }
2803: if (scalar(keys(%Expired))) {
2804: my @sorted = sort {$a <=> $b} keys(%Expired);
2805: my $time = pop(@sorted);
1.599 albertel 2806: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2807: }
1.599 albertel 2808: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2809: }
1.70 www 2810:
1.599 albertel 2811: sub save_cache {
2812: &purge_remembered();
1.722 albertel 2813: #&Apache::loncommon::validate_page();
1.620 albertel 2814: undef(%env);
1.780 albertel 2815: undef($env_loaded);
1.599 albertel 2816: }
1.452 albertel 2817:
1.599 albertel 2818: my $to_remember=-1;
2819: my %remembered;
2820: my %accessed;
2821: my $kicks=0;
2822: my $hits=0;
1.849 albertel 2823: sub make_key {
2824: my ($name,$id) = @_;
1.872 albertel 2825: if (length($id) > 65
2826: && length(&escape($id)) > 200) {
2827: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2828: }
1.849 albertel 2829: return &escape($name.':'.$id);
2830: }
2831:
1.599 albertel 2832: sub devalidate_cache_new {
2833: my ($name,$id,$debug) = @_;
2834: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2835: my $remembered_id=$name.':'.$id;
1.849 albertel 2836: $id=&make_key($name,$id);
1.599 albertel 2837: $memcache->delete($id);
1.1172.2.81 raeburn 2838: delete($remembered{$remembered_id});
2839: delete($accessed{$remembered_id});
1.599 albertel 2840: }
2841:
2842: sub is_cached_new {
2843: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2844: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2845: # keys in %remembered hash, which persists for
2846: # duration of request (no restriction on key length).
2847: if (exists($remembered{$remembered_id})) {
2848: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2849: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2850: $hits++;
1.1172.2.81 raeburn 2851: return ($remembered{$remembered_id},1);
1.599 albertel 2852: }
1.1172.2.81 raeburn 2853: $id=&make_key($name,$id);
1.599 albertel 2854: my $value = $memcache->get($id);
2855: if (!(defined($value))) {
2856: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2857: return (undef,undef);
1.416 albertel 2858: }
1.599 albertel 2859: if ($value eq '__undef__') {
2860: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2861: $value=undef;
2862: }
1.1172.2.81 raeburn 2863: &make_room($remembered_id,$value,$debug);
1.599 albertel 2864: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2865: return ($value,1);
2866: }
2867:
2868: sub do_cache_new {
2869: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2870: my $remembered_id=$name.':'.$id;
1.849 albertel 2871: $id=&make_key($name,$id);
1.599 albertel 2872: my $setvalue=$value;
2873: if (!defined($setvalue)) {
2874: $setvalue='__undef__';
2875: }
1.623 albertel 2876: if (!defined($time) ) {
2877: $time=600;
2878: }
1.599 albertel 2879: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2880: my $result = $memcache->set($id,$setvalue,$time);
2881: if (! $result) {
1.872 albertel 2882: &logthis("caching of id -> $id failed");
1.910 albertel 2883: $memcache->disconnect_all();
1.872 albertel 2884: }
1.600 albertel 2885: # need to make a copy of $value
1.1172.2.81 raeburn 2886: &make_room($remembered_id,$value,$debug);
1.599 albertel 2887: return $value;
2888: }
2889:
2890: sub make_room {
1.1172.2.81 raeburn 2891: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2892:
1.1172.2.81 raeburn 2893: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2894: : $value;
1.599 albertel 2895: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2896: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2897: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2898: my $to_kick;
2899: my $max_time=0;
2900: foreach my $other (keys(%accessed)) {
2901: if (&tv_interval($accessed{$other}) > $max_time) {
2902: $to_kick=$other;
2903: $max_time=&tv_interval($accessed{$other});
2904: }
2905: }
2906: delete($remembered{$to_kick});
2907: delete($accessed{$to_kick});
2908: $kicks++;
2909: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2910: return;
2911: }
2912:
1.599 albertel 2913: sub purge_remembered {
1.604 albertel 2914: #&logthis("Tossing ".scalar(keys(%remembered)));
2915: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2916: undef(%remembered);
2917: undef(%accessed);
1.428 albertel 2918: }
1.70 www 2919: # ------------------------------------- Read an entry from a user's environment
2920:
2921: sub userenvironment {
2922: my ($udom,$unam,@what)=@_;
1.976 raeburn 2923: my $items;
2924: foreach my $item (@what) {
2925: $items.=&escape($item).'&';
2926: }
2927: $items=~s/\&$//;
1.70 www 2928: my %returnhash=();
1.1009 raeburn 2929: my $uhome = &homeserver($unam,$udom);
2930: unless ($uhome eq 'no_host') {
2931: my @answer=split(/\&/,
2932: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2933: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2934: return %returnhash;
2935: }
1.1009 raeburn 2936: my $i;
2937: for ($i=0;$i<=$#what;$i++) {
2938: $returnhash{$what[$i]}=&unescape($answer[$i]);
2939: }
1.70 www 2940: }
2941: return %returnhash;
1.1 albertel 2942: }
2943:
1.617 albertel 2944: # ---------------------------------------------------------- Get a studentphoto
2945: sub studentphoto {
2946: my ($udom,$unam,$ext) = @_;
2947: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2948: if (defined($env{'request.course.id'})) {
1.708 raeburn 2949: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2950: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2951: return(&retrievestudentphoto($udom,$unam,$ext));
2952: } else {
2953: my ($result,$perm_reqd)=
1.707 albertel 2954: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2955: if ($result eq 'ok') {
2956: if (!($perm_reqd eq 'yes')) {
2957: return(&retrievestudentphoto($udom,$unam,$ext));
2958: }
2959: }
2960: }
2961: }
2962: } else {
2963: my ($result,$perm_reqd) =
1.707 albertel 2964: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2965: if ($result eq 'ok') {
2966: if (!($perm_reqd eq 'yes')) {
2967: return(&retrievestudentphoto($udom,$unam,$ext));
2968: }
2969: }
2970: }
2971: return '/adm/lonKaputt/lonlogo_broken.gif';
2972: }
2973:
2974: sub retrievestudentphoto {
2975: my ($udom,$unam,$ext,$type) = @_;
2976: my $home=&Apache::lonnet::homeserver($unam,$udom);
2977: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2978: if ($ret eq 'ok') {
2979: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2980: if ($type eq 'thumbnail') {
2981: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2982: }
2983: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2984: return $tokenurl;
2985: } else {
2986: if ($type eq 'thumbnail') {
2987: return '/adm/lonKaputt/genericstudent_tn.gif';
2988: } else {
2989: return '/adm/lonKaputt/lonlogo_broken.gif';
2990: }
1.617 albertel 2991: }
2992: }
2993:
1.263 www 2994: # -------------------------------------------------------------------- New chat
2995:
2996: sub chatsend {
1.724 raeburn 2997: my ($newentry,$anon,$group)=@_;
1.620 albertel 2998: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2999: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3000: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3001: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3002: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3003: &escape($newentry)).':'.$group,$chome);
1.292 www 3004: }
3005:
3006: # ------------------------------------------ Find current version of a resource
3007:
3008: sub getversion {
3009: my $fname=&clutter(shift);
1.1172.2.10 raeburn 3010: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3011: return ¤tversion(&filelocation('',$fname));
3012: }
3013:
3014: sub currentversion {
3015: my $fname=shift;
3016: my $author=$fname;
3017: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3018: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3019: my $home=&homeserver($uname,$udom);
1.292 www 3020: if ($home eq 'no_host') {
3021: return -1;
3022: }
1.1112 www 3023: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3024: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3025: return -1;
3026: }
1.1112 www 3027: return $answer;
1.263 www 3028: }
3029:
1.1111 www 3030: #
3031: # Return special version number of resource if set by override, empty otherwise
3032: #
3033: sub usedversion {
3034: my $fname=shift;
3035: unless ($fname) { $fname=$env{'request.uri'}; }
3036: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3037: if ($urlversion) { return $urlversion; }
3038: return '';
3039: }
3040:
1.1 albertel 3041: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3042:
1.1 albertel 3043: sub subscribe {
3044: my $fname=shift;
1.761 raeburn 3045: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3046: $fname=~s/[\n\r]//g;
1.1 albertel 3047: my $author=$fname;
3048: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3049: my ($udom,$uname)=split(/\//,$author);
3050: my $home=homeserver($uname,$udom);
1.335 albertel 3051: if ($home eq 'no_host') {
3052: return 'not_found';
1.1 albertel 3053: }
3054: my $answer=reply("sub:$fname",$home);
1.64 www 3055: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3056: $answer.=' by '.$home;
3057: }
1.1 albertel 3058: return $answer;
3059: }
3060:
1.8 www 3061: # -------------------------------------------------------------- Replicate file
3062:
3063: sub repcopy {
3064: my $filename=shift;
1.23 www 3065: $filename=~s/\/+/\//g;
1.1142 raeburn 3066: my $londocroot = $perlvar{'lonDocRoot'};
3067: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3068: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3069: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3070: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3071: return &repcopy_userfile($filename);
3072: }
1.532 albertel 3073: $filename=~s/[\n\r]//g;
1.8 www 3074: my $transname="$filename.in.transfer";
1.828 www 3075: # FIXME: this should flock
1.607 raeburn 3076: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3077: my $remoteurl=subscribe($filename);
1.64 www 3078: if ($remoteurl =~ /^con_lost by/) {
3079: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3080: return 'unavailable';
1.8 www 3081: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3082: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3083: return 'not_found';
1.64 www 3084: } elsif ($remoteurl =~ /^rejected by/) {
3085: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3086: return 'forbidden';
1.20 www 3087: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3088: return 'ok';
1.8 www 3089: } else {
1.290 www 3090: my $author=$filename;
3091: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3092: my ($udom,$uname)=split(/\//,$author);
3093: my $home=homeserver($uname,$udom);
3094: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3095: my @parts=split(/\//,$filename);
3096: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3097: if ($path ne "$londocroot/res") {
1.8 www 3098: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3099: return 'bad_request';
1.8 www 3100: }
3101: my $count;
3102: for ($count=5;$count<$#parts;$count++) {
3103: $path.="/$parts[$count]";
3104: if ((-e $path)!=1) {
3105: mkdir($path,0777);
3106: }
3107: }
3108: my $ua=new LWP::UserAgent;
3109: my $request=new HTTP::Request('GET',"$remoteurl");
3110: my $response=$ua->request($request,$transname);
3111: if ($response->is_error()) {
3112: unlink($transname);
3113: my $message=$response->status_line;
1.672 albertel 3114: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3115: ." LWP get: $message: $filename</font>");
1.607 raeburn 3116: return 'unavailable';
1.8 www 3117: } else {
1.16 www 3118: if ($remoteurl!~/\.meta$/) {
3119: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3120: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3121: if ($mresponse->is_error()) {
3122: unlink($filename.'.meta');
3123: &logthis(
1.672 albertel 3124: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3125: }
3126: }
1.8 www 3127: rename($transname,$filename);
1.607 raeburn 3128: return 'ok';
1.8 www 3129: }
1.290 www 3130: }
1.8 www 3131: }
1.330 www 3132: }
3133:
1.1172.2.118. .5(raebu 3134:20): # ------------------------------------------------- Unsubscribe from a resource
3135:20):
3136:20): sub unsubscribe {
3137:20): my ($fname) = @_;
3138:20): my $answer;
3139:20): if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3140:20): $fname=~s/[\n\r]//g;
3141:20): my $author=$fname;
3142:20): $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3143:20): my ($udom,$uname)=split(/\//,$author);
3144:20): my $home=homeserver($uname,$udom);
3145:20): if ($home eq 'no_host') {
3146:20): $answer = 'no_host';
3147:20): } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3148:20): $answer = 'home';
3149:20): } else {
.7(raebu 3150:20): $answer = reply("unsub:$fname",$home);
.5(raebu 3151:20): }
3152:20): return $answer;
3153:20): }
3154:20):
1.330 www 3155: # ------------------------------------------------ Get server side include body
3156: sub ssi_body {
1.381 albertel 3157: my ($filelink,%form)=@_;
1.606 matthew 3158: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3159: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3160: }
1.953 www 3161: my $output='';
3162: my $response;
1.980 raeburn 3163: if ($filelink=~/^https?\:/) {
1.954 raeburn 3164: ($output,$response)=&externalssi($filelink);
1.953 www 3165: } else {
1.1004 droeschl 3166: $filelink .= $filelink=~/\?/ ? '&' : '?';
3167: $filelink .= 'inhibitmenu=yes';
1.953 www 3168: ($output,$response)=&ssi($filelink,%form);
3169: }
1.778 albertel 3170: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3171: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3172: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3173: if (wantarray) {
3174: return ($output, $response);
3175: } else {
3176: return $output;
3177: }
1.8 www 3178: }
3179:
1.15 www 3180: # --------------------------------------------------------- Server Side Include
3181:
1.782 albertel 3182: sub absolute_url {
3183: my ($host_name) = @_;
3184: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3185: if ($host_name eq '') {
3186: $host_name = $ENV{'SERVER_NAME'};
3187: }
3188: return $protocol.$host_name;
3189: }
3190:
1.942 foxr 3191: #
3192: # Server side include.
3193: # Parameters:
3194: # fn Possibly encrypted resource name/id.
3195: # form Hash that describes how the rendering should be done
3196: # and other things.
1.944 foxr 3197: # Returns:
1.950 raeburn 3198: # Scalar context: The content of the response.
3199: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3200: #
1.15 www 3201: sub ssi {
3202:
1.944 foxr 3203: my ($fn,%form)=@_;
1.1172.2.100 raeburn 3204: my ($request,$response);
1.711 albertel 3205:
3206: $form{'no_update_last_known'}=1;
1.895 albertel 3207: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3208: if (%form) {
1.782 albertel 3209: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 3210: $request->content(join('&',map {
3211: my $name = escape($_);
3212: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3213: ? join("&$name=", map {escape($_) } @{$form{$_}})
3214: : &escape($form{$_}) );
3215: } keys(%form)));
1.23 www 3216: } else {
1.782 albertel 3217: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3218: }
3219:
1.15 www 3220: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 3221:
1.1172.2.101 raeburn 3222: if (($env{'request.course.id'}) &&
3223: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3224: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3225: ($form{'grade_symb'} ne '') &&
3226: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3227: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 3228: if (LWP::UserAgent->VERSION >= 5.834) {
3229: my $ua=new LWP::UserAgent;
3230: $ua->local_address('127.0.0.1');
3231: $response = $ua->request($request);
3232: } else {
3233: {
3234: require LWP::Protocol::http;
3235: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3236: my $ua=new LWP::UserAgent;
3237: $response = $ua->request($request);
3238: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3239: }
3240: }
3241: } else {
3242: my $ua=new LWP::UserAgent;
3243: $response = $ua->request($request);
3244: }
1.944 foxr 3245: if (wantarray) {
1.1172.2.3 raeburn 3246: return ($response->content, $response);
1.944 foxr 3247: } else {
1.1172.2.3 raeburn 3248: return $response->content;
1.942 foxr 3249: }
1.324 www 3250: }
3251:
3252: sub externalssi {
3253: my ($url)=@_;
3254: my $ua=new LWP::UserAgent;
3255: my $request=new HTTP::Request('GET',$url);
3256: my $response=$ua->request($request);
1.954 raeburn 3257: if (wantarray) {
3258: return ($response->content, $response);
3259: } else {
3260: return $response->content;
3261: }
1.15 www 3262: }
1.254 www 3263:
1.1172.2.98 raeburn 3264: # If the local copy of a replicated resource is outdated, trigger a
3265: # connection from the homeserver to flush the delayed queue. If no update
3266: # happens, remove local copies of outdated resource (and corresponding
3267: # metadata file).
3268:
3269: sub remove_stale_resfile {
3270: my ($url) = @_;
3271: my $removed;
3272: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3273: my $audom = $1;
3274: my $auname = $2;
3275: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3276: my $homeserver = &homeserver($auname,$audom);
3277: unless (($homeserver eq 'no_host') ||
3278: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3279: my $fname = &filelocation('',$url);
3280: if (-e $fname) {
3281: my $hostname = &hostname($homeserver);
3282: if ($hostname) {
1.1172.2.118. .3(raebu 3283:20): my $protocol = $protocol{$homeserver};
3284:20): $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98 raeburn 3285: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.118. .3(raebu 3286:20): my $ua=new LWP::UserAgent;
3287:20): $ua->timeout(5);
1.1172.2.98 raeburn 3288: my $request=new HTTP::Request('HEAD',$uri);
3289: my $response=$ua->request($request);
3290: if ($response->is_success()) {
3291: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3292: my $locmodtime = (stat($fname))[9];
3293: if ($locmodtime < $remmodtime) {
3294: my $stale;
3295: my $answer = &reply('pong',$homeserver);
3296: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3297: sleep(0.2);
3298: $locmodtime = (stat($fname))[9];
3299: if ($locmodtime < $remmodtime) {
3300: my $posstransfer = $fname.'.in.transfer';
3301: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3302: $removed = 1;
3303: } else {
3304: $stale = 1;
3305: }
3306: } else {
3307: $removed = 1;
3308: }
3309: } else {
3310: $stale = 1;
3311: }
3312: if ($stale) {
1.1172.2.118. .5(raebu 3313:20): if (unlink($fname)) {
3314:20): if ($uri!~/\.meta$/) {
3315:20): if (-e $fname.'.meta') {
3316:20): unlink($fname.'.meta');
3317:20): }
3318:20): }
3319:20): my $unsubresult = &unsubscribe($fname);
3320:20): unless ($unsubresult eq 'ok') {
3321:20): &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3322:20): }
3323:20): $removed = 1;
1.1172.2.98 raeburn 3324: }
3325: }
3326: }
3327: }
3328: }
3329: }
3330: }
3331: }
3332: }
3333: return $removed;
3334: }
3335:
1.492 albertel 3336: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3337:
3338: sub allowuploaded {
3339: my ($srcurl,$url)=@_;
3340: $url=&clutter(&declutter($url));
3341: my $dir=$url;
3342: $dir=~s/\/[^\/]+$//;
3343: my %httpref=();
3344: my $httpurl=&hreflocation('',$url);
3345: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3346: &Apache::lonnet::appenv(\%httpref);
1.254 www 3347: }
1.477 raeburn 3348:
1.1172.2.13 raeburn 3349: #
3350: # Determine if the current user should be able to edit a particular resource,
3351: # when viewing in course context.
3352: # (a) When viewing resource used to determine if "Edit" item is included in
3353: # Functions.
3354: # (b) When displaying folder contents in course editor, used to determine if
3355: # "Edit" link will be displayed alongside resource.
3356: #
3357: # input: six args -- filename (decluttered), course number, course domain,
3358: # url, symb (if registered) and group (if this is a group
3359: # item -- e.g., bulletin board, group page etc.).
3360: # output: array of five scalars --
3361: # $cfile -- url for file editing if editable on current server
3362: # $home -- homeserver of resource (i.e., for author if published,
3363: # or course if uploaded.).
3364: # $switchserver -- 1 if server switch will be needed.
3365: # $forceedit -- 1 if icon/link should be to go to edit mode
3366: # $forceview -- 1 if icon/link should be to go to view mode
3367: #
3368:
3369: sub can_edit_resource {
3370: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3371: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3372: #
3373: # For aboutme pages user can only edit his/her own.
3374: #
3375: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3376: my ($sdom,$sname) = ($1,$2);
3377: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3378: $home = $env{'user.home'};
3379: $cfile = $resurl;
3380: if ($env{'form.forceedit'}) {
3381: $forceview = 1;
3382: } else {
3383: $forceedit = 1;
3384: }
3385: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3386: } else {
3387: return;
3388: }
3389: }
3390:
3391: if ($env{'request.course.id'}) {
3392: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3393: if ($group ne '') {
3394: # if this is a group homepage or group bulletin board, check group privs
3395: my $allowed = 0;
3396: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3397: if ((&allowed('mdg',$env{'request.course.id'}.
3398: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3399: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3400: $allowed = 1;
3401: }
3402: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3403: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3404: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3405: $allowed = 1;
3406: }
3407: }
3408: if ($allowed) {
3409: $home=&homeserver($cnum,$cdom);
3410: if ($env{'form.forceedit'}) {
3411: $forceview = 1;
3412: } else {
3413: $forceedit = 1;
3414: }
3415: $cfile = $resurl;
3416: } else {
3417: return;
3418: }
3419: } else {
1.1172.2.15 raeburn 3420: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3421: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3422: return;
3423: }
3424: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3425: #
3426: # No edit allowed where CC has switched to student role.
3427: #
3428: return;
3429: }
3430: }
3431: }
3432:
3433: if ($file ne '') {
3434: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3435: if (&is_course_upload($file,$cnum,$cdom)) {
3436: $uploaded = 1;
3437: $incourse = 1;
3438: if ($file =~/\.(htm|html|css|js|txt)$/) {
3439: $cfile = &hreflocation('',$file);
3440: if ($env{'form.forceedit'}) {
3441: $forceview = 1;
3442: } else {
3443: $forceedit = 1;
3444: }
3445: }
3446: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3447: $incourse = 1;
3448: if ($env{'form.forceedit'}) {
3449: $forceview = 1;
3450: } else {
3451: $forceedit = 1;
3452: }
3453: $cfile = $resurl;
3454: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3455: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3456: $incourse = 1;
3457: if ($env{'form.forceedit'}) {
3458: $forceview = 1;
3459: } else {
3460: $forceedit = 1;
3461: }
3462: $cfile = $resurl;
3463: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3464: $incourse = 1;
3465: $cfile = $resurl.'/smpedit';
3466: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3467: $incourse = 1;
3468: if ($env{'form.forceedit'}) {
3469: $forceview = 1;
3470: } else {
3471: $forceedit = 1;
3472: }
3473: $cfile = $resurl;
1.1172.2.118. .5(raebu 3474:20): } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3475:20): my ($map,$id,$res) = &decode_symb($symb);
3476:20): if ($map =~ /\.page$/) {
3477:20): $incourse = 1;
3478:20): if ($env{'form.forceedit'}) {
3479:20): $forceview = 1;
3480:20): $cfile = $map;
3481:20): } else {
3482:20): $forceedit = 1;
3483:20): $cfile = '/adm/wrapper'.$resurl;
3484:20): }
3485:20): }
.1(raebu 3486:20): } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3487:20): $incourse = 1;
3488:20): if ($env{'form.forceedit'}) {
3489:20): $forceview = 1;
3490:20): } else {
3491:20): $forceedit = 1;
3492:20): }
3493:20): $cfile = $resurl;
1.1172.2.15 raeburn 3494: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3495: $incourse = 1;
3496: if ($env{'form.forceedit'}) {
3497: $forceview = 1;
3498: } else {
3499: $forceedit = 1;
3500: }
3501: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3502: }
3503: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3504: my $template = '/res/lib/templates/simpleproblem.problem';
3505: if (&is_on_map($template)) {
3506: $incourse = 1;
3507: $forceview = 1;
3508: $cfile = $template;
3509: }
3510: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3511: $incourse = 1;
3512: if ($env{'form.forceedit'}) {
3513: $forceview = 1;
3514: } else {
3515: $forceedit = 1;
3516: }
3517: $cfile = $resurl;
1.1172.2.118. .1(raebu 3518:20): } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3519:20): $incourse = 1;
3520:20): if ($env{'form.forceedit'}) {
3521:20): $forceview = 1;
3522:20): } else {
3523:20): $forceedit = 1;
3524:20): }
3525:20): $cfile = $resurl;
1.1172.2.13 raeburn 3526: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3527: $incourse = 1;
3528: $forceview = 1;
3529: if ($symb) {
3530: my ($map,$id,$res)=&decode_symb($symb);
3531: $env{'request.symb'} = $symb;
3532: $cfile = &clutter($res);
3533: } else {
3534: $cfile = $env{'form.suppurl'};
1.1172.2.118. .1(raebu 3535:20): my $escfile = &unescape($cfile);
3536:20): if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3537:20): $cfile = '/adm/wrapper'.$escfile;
3538:20): } else {
3539:20): $escfile =~ s{^http://}{};
3540:20): $cfile = &escape("/adm/wrapper/ext/$escfile");
3541:20): }
1.1172.2.13 raeburn 3542: }
1.1172.2.31 raeburn 3543: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3544: if ($env{'form.forceedit'}) {
3545: $forceview = 1;
3546: } else {
3547: $forceedit = 1;
3548: }
3549: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3550: }
3551: }
3552: if ($uploaded || $incourse) {
3553: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3554: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3555: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3556: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3557: # Check that the user has permission to edit this resource
3558: my $setpriv = 1;
3559: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3560: if (defined($cfudom)) {
3561: $home=&homeserver($cfuname,$cfudom);
3562: $cfile=$file;
3563: }
3564: }
3565: if (($cfile ne '') && (!$incourse || $uploaded) &&
3566: (($home ne '') && ($home ne 'no_host'))) {
3567: my @ids=¤t_machine_ids();
3568: unless (grep(/^\Q$home\E$/,@ids)) {
3569: $switchserver=1;
3570: }
3571: }
3572: }
3573: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3574: }
3575:
3576: sub is_course_upload {
3577: my ($file,$cnum,$cdom) = @_;
3578: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3579: $uploadpath =~ s{^\/}{};
3580: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3581: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3582: return 1;
3583: }
3584: return;
3585: }
3586:
3587: sub in_course {
3588: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3589: if ($hideprivileged) {
3590: my $skipuser;
1.1172.2.23 raeburn 3591: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3592: my @possdoms = ($cdom);
3593: if ($coursehash{'checkforpriv'}) {
3594: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3595: }
3596: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3597: $skipuser = 1;
3598: if ($coursehash{'nothideprivileged'}) {
3599: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3600: my $user;
3601: if ($item =~ /:/) {
3602: $user = $item;
3603: } else {
3604: $user = join(':',split(/[\@]/,$item));
3605: }
3606: if ($user eq $uname.':'.$udom) {
3607: undef($skipuser);
3608: last;
3609: }
3610: }
3611: }
3612: if ($skipuser) {
3613: return 0;
3614: }
3615: }
3616: }
3617: $type ||= 'any';
3618: if (!defined($cdom) || !defined($cnum)) {
3619: my $cid = $env{'request.course.id'};
3620: $cdom = $env{'course.'.$cid.'.domain'};
3621: $cnum = $env{'course.'.$cid.'.num'};
3622: }
3623: my $typesref;
3624: if (($type eq 'any') || ($type eq 'all')) {
3625: $typesref = ['active','previous','future'];
3626: } elsif ($type eq 'previous' || $type eq 'future') {
3627: $typesref = [$type];
3628: }
3629: my %roles = &get_my_roles($uname,$udom,'userroles',
3630: $typesref,undef,[$cdom]);
3631: my ($tmp) = keys(%roles);
3632: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3633: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3634: if (@course_roles > 0) {
3635: return 1;
3636: }
3637: return 0;
3638: }
3639:
1.478 albertel 3640: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3641: # input: action, courseID, current domain, intended
1.637 raeburn 3642: # path to file, source of file, instruction to parse file for objects,
3643: # ref to hash for embedded objects,
3644: # ref to hash for codebase of java objects.
1.1095 raeburn 3645: # reference to scalar to accommodate mime type determined
3646: # from File::MMagic if $parser = parse.
1.637 raeburn 3647: #
1.485 raeburn 3648: # output: url to file (if action was uploaddoc),
3649: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3650: #
1.478 albertel 3651: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3652: # course.
1.477 raeburn 3653: #
1.478 albertel 3654: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3655: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3656: # course's home server.
1.477 raeburn 3657: #
1.478 albertel 3658: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3659: # be copied from $source (current location) to
3660: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3661: # and will then be copied to
3662: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3663: # course's home server.
1.485 raeburn 3664: #
1.481 raeburn 3665: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3666: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3667: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3668: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3669: # in course's home server.
1.637 raeburn 3670: #
1.477 raeburn 3671:
3672: sub process_coursefile {
1.1095 raeburn 3673: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3674: $mimetype)=@_;
1.477 raeburn 3675: my $fetchresult;
1.638 albertel 3676: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3677: if ($action eq 'propagate') {
1.638 albertel 3678: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3679: $home);
1.481 raeburn 3680: } else {
1.477 raeburn 3681: my $fpath = '';
3682: my $fname = $file;
1.478 albertel 3683: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3684: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3685: my $filepath = &build_filepath($fpath);
1.481 raeburn 3686: if ($action eq 'copy') {
3687: if ($source eq '') {
3688: $fetchresult = 'no source file';
3689: return $fetchresult;
3690: } else {
3691: my $destination = $filepath.'/'.$fname;
3692: rename($source,$destination);
3693: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3694: $home);
1.481 raeburn 3695: }
3696: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3697: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3698: print $fh $env{'form.'.$source};
1.481 raeburn 3699: close($fh);
1.637 raeburn 3700: if ($parser eq 'parse') {
1.1024 raeburn 3701: my $mm = new File::MMagic;
1.1095 raeburn 3702: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3703: if ($type eq 'text/html') {
1.1024 raeburn 3704: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3705: unless ($parse_result eq 'ok') {
3706: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3707: }
1.637 raeburn 3708: }
1.1095 raeburn 3709: if (ref($mimetype)) {
3710: $$mimetype = $type;
3711: }
1.637 raeburn 3712: }
1.477 raeburn 3713: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3714: $home);
1.481 raeburn 3715: if ($fetchresult eq 'ok') {
3716: return '/uploaded/'.$fpath.'/'.$fname;
3717: } else {
3718: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3719: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3720: return '/adm/notfound.html';
3721: }
1.477 raeburn 3722: }
3723: }
1.485 raeburn 3724: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3725: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3726: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3727: }
3728: return $fetchresult;
3729: }
3730:
1.637 raeburn 3731: sub build_filepath {
3732: my ($fpath) = @_;
3733: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3734: unless ($fpath eq '') {
3735: my @parts=split('/',$fpath);
3736: foreach my $part (@parts) {
3737: $filepath.= '/'.$part;
3738: if ((-e $filepath)!=1) {
3739: mkdir($filepath,0777);
3740: }
3741: }
3742: }
3743: return $filepath;
3744: }
3745:
3746: sub store_edited_file {
1.638 albertel 3747: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3748: my $file = $primary_url;
3749: $file =~ s#^/uploaded/$docudom/$docuname/##;
3750: my $fpath = '';
3751: my $fname = $file;
3752: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3753: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3754: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3755: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3756: print $fh $content;
3757: close($fh);
1.638 albertel 3758: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3759: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3760: $home);
1.637 raeburn 3761: if ($$fetchresult eq 'ok') {
3762: return '/uploaded/'.$fpath.'/'.$fname;
3763: } else {
1.638 albertel 3764: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3765: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3766: return '/adm/notfound.html';
3767: }
3768: }
3769:
1.531 albertel 3770: sub clean_filename {
1.831 albertel 3771: my ($fname,$args)=@_;
1.315 www 3772: # Replace Windows backslashes by forward slashes
1.257 www 3773: $fname=~s/\\/\//g;
1.831 albertel 3774: if (!$args->{'keep_path'}) {
3775: # Get rid of everything but the actual filename
3776: $fname=~s/^.*\/([^\/]+)$/$1/;
3777: }
1.315 www 3778: # Replace spaces by underscores
3779: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 3780: # Transliterate non-ascii text to ascii
3781: my $lang = &Apache::lonlocal::current_language();
3782: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3783: # Replace all other weird characters by nothing
1.831 albertel 3784: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3785: # Replace all .\d. sequences with _\d. so they no longer look like version
3786: # numbers
3787: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.118. .19(raeb 3788:-21): # Replace three or more adjacent underscores with one for consistency
3789:-21): # with loncfile::filename_check() so complete url can be extracted by
3790:-21): # lonnet::decode_symb()
3791:-21): $fname=~s/_{3,}/_/g;
1.531 albertel 3792: return $fname;
3793: }
1.1172.2.110 raeburn 3794:
1.1051 raeburn 3795: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3796: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3797: # image with the same aspect ratio as the original, but with dimensions which do
3798: # not exceed $resizewidth and $resizeheight.
3799:
1.984 neumanie 3800: sub resizeImage {
1.1051 raeburn 3801: my ($img_path,$resizewidth,$resizeheight) = @_;
3802: my $ima = Image::Magick->new;
3803: my $resized;
3804: if (-e $img_path) {
3805: $ima->Read($img_path);
3806: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3807: my $width = $ima->Get('width');
3808: my $height = $ima->Get('height');
3809: if ($width > $resizewidth) {
3810: my $factor = $width/$resizewidth;
3811: my $newheight = $height/$factor;
3812: $ima->Scale(width=>$resizewidth,height=>$newheight);
3813: $resized = 1;
3814: }
3815: }
3816: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3817: my $width = $ima->Get('width');
3818: my $height = $ima->Get('height');
3819: if ($height > $resizeheight) {
3820: my $factor = $height/$resizeheight;
3821: my $newwidth = $width/$factor;
3822: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3823: $resized = 1;
3824: }
3825: }
3826: if ($resized) {
3827: $ima->Write($img_path);
3828: }
3829: }
3830: return;
1.977 amueller 3831: }
3832:
1.608 albertel 3833: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3834: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3835: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3836: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.109 raeburn 3837: # canceloverwrite, scantron or ''.
1.1090 raeburn 3838: # if 'coursedoc': upload to the current course
3839: # if 'existingfile': write file to tmp/overwrites directory
3840: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3841: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3842: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 3843: # $parser - instruction to parse file for objects ($parser = parse) or
3844: # if context is 'scantron', $parser is hashref of csv column mapping
3845: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3846: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3847: # $allfiles - reference to hash for embedded objects
3848: # $codebase - reference to hash for codebase of java objects
3849: # $desuname - username for permanent storage of uploaded file
3850: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3851: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3852: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3853: # $resizewidth - width (pixels) to which to resize uploaded image
3854: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3855: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3856: # from File::MMagic.
1.858 raeburn 3857: #
1.686 albertel 3858: # output: url of file in userspace, or error: <message>
3859: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3860:
1.531 albertel 3861: sub userfileupload {
1.1090 raeburn 3862: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3863: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3864: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3865: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3866: $fname=&clean_filename($fname);
1.1090 raeburn 3867: # See if there is anything left
1.257 www 3868: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 3869: # If filename now begins with a . prepend unix timestamp _ milliseconds
3870: if ($fname =~ /^\./) {
3871: my ($s,$usec) = &gettimeofday();
3872: while (length($usec) < 6) {
3873: $usec = '0'.$usec;
3874: }
3875: $fname = $s.'_'.substr($usec,0,3).$fname;
3876: }
1.1090 raeburn 3877: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3878: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3879: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3880: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3881: my $now = time;
1.1090 raeburn 3882: my $filepath;
1.1095 raeburn 3883: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3884: $filepath = 'tmp/helprequests/'.$now;
3885: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3886: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3887: '_'.$env{'user.domain'}.'/pending';
3888: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3889: my ($docuname,$docudom);
1.1172.2.96 raeburn 3890: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3891: $docudom = $destudom;
3892: } else {
3893: $docudom = $env{'user.domain'};
3894: }
1.1172.2.96 raeburn 3895: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3896: $docuname = $destuname;
3897: } else {
3898: $docuname = $env{'user.name'};
3899: }
3900: if (exists($env{'form.group'})) {
3901: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3902: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3903: }
3904: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3905: if ($context eq 'canceloverwrite') {
3906: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3907: if (-e $tempfile) {
3908: my @info = stat($tempfile);
3909: if ($info[9] eq $env{'form.timestamp'}) {
3910: unlink($tempfile);
3911: }
3912: }
3913: return;
1.523 raeburn 3914: }
3915: }
1.1090 raeburn 3916: # Create the directory if not present
1.741 raeburn 3917: my @parts=split(/\//,$filepath);
3918: my $fullpath = $perlvar{'lonDaemons'};
3919: for (my $i=0;$i<@parts;$i++) {
3920: $fullpath .= '/'.$parts[$i];
3921: if ((-e $fullpath)!=1) {
3922: mkdir($fullpath,0777);
3923: }
3924: }
1.1172.2.96 raeburn 3925: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3926: print $fh $env{'form.'.$formname};
3927: close($fh);
1.1090 raeburn 3928: if ($context eq 'existingfile') {
3929: my @info = stat($fullpath.'/'.$fname);
3930: return ($fullpath.'/'.$fname,$info[9]);
3931: } else {
3932: return $fullpath.'/'.$fname;
3933: }
1.523 raeburn 3934: }
1.995 raeburn 3935: if ($subdir eq 'scantron') {
3936: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3937: } else {
1.995 raeburn 3938: $fname="$subdir/$fname";
3939: }
1.1090 raeburn 3940: if ($context eq 'coursedoc') {
1.638 albertel 3941: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3942: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3943: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3944: return &finishuserfileupload($docuname,$docudom,
3945: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3946: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3947: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3948: } else {
1.1172.2.21 raeburn 3949: if ($env{'form.folder'}) {
3950: $fname=$env{'form.folder'}.'/'.$fname;
3951: }
1.638 albertel 3952: return &process_coursefile('uploaddoc',$docuname,$docudom,
3953: $fname,$formname,$parser,
1.1095 raeburn 3954: $allfiles,$codebase,$mimetype);
1.481 raeburn 3955: }
1.719 banghart 3956: } elsif (defined($destuname)) {
3957: my $docuname=$destuname;
3958: my $docudom=$destudom;
1.860 raeburn 3959: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3960: $parser,$allfiles,$codebase,
1.1051 raeburn 3961: $thumbwidth,$thumbheight,
1.1095 raeburn 3962: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3963: } else {
1.638 albertel 3964: my $docuname=$env{'user.name'};
3965: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3966: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3967: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3968: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3969: }
1.860 raeburn 3970: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3971: $parser,$allfiles,$codebase,
1.1051 raeburn 3972: $thumbwidth,$thumbheight,
1.1095 raeburn 3973: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3974: }
1.271 www 3975: }
3976:
3977: sub finishuserfileupload {
1.860 raeburn 3978: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3979: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3980: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3981: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3982:
1.860 raeburn 3983: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3984: $file=$fname;
3985: if ($fname=~m|/|) {
3986: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3987: $path.=$fnamepath.'/';
3988: }
1.259 www 3989: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3990: my $count;
3991: for ($count=4;$count<=$#parts;$count++) {
3992: $filepath.="/$parts[$count]";
3993: if ((-e $filepath)!=1) {
3994: mkdir($filepath,0777);
3995: }
3996: }
1.984 neumanie 3997:
1.258 www 3998: # Save the file
3999: {
1.1172.2.96 raeburn 4000: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4001: &logthis('Failed to create '.$filepath.'/'.$file);
4002: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4003: return '/adm/notfound.html';
4004: }
1.1090 raeburn 4005: if ($context eq 'overwrite') {
1.1117 foxr 4006: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4007: my $target = $filepath.'/'.$file;
4008: if (-e $source) {
4009: my @info = stat($source);
4010: if ($info[9] eq $env{'form.timestamp'}) {
4011: unless (&File::Copy::move($source,$target)) {
4012: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4013: return "Moving from $source failed";
4014: }
4015: } else {
4016: return "Temporary file: $source had unexpected date/time for last modification";
4017: }
4018: } else {
4019: return "Temporary file: $source missing";
4020: }
4021: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4022: &logthis('Failed to write to '.$filepath.'/'.$file);
4023: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4024: return '/adm/notfound.html';
4025: }
1.570 albertel 4026: close(FH);
1.1051 raeburn 4027: if ($resizewidth && $resizeheight) {
4028: my $mm = new File::MMagic;
4029: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4030: if ($mime_type =~ m{^image/}) {
4031: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4032: }
1.977 amueller 4033: }
1.258 www 4034: }
1.1152 raeburn 4035: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4036: if (ref($mimetype)) {
4037: if ($$mimetype eq '') {
4038: my $mm = new File::MMagic;
4039: my $type = $mm->checktype_filename($filepath.'/'.$file);
4040: $$mimetype = $type;
4041: }
4042: }
4043: }
1.1172.2.109 raeburn 4044: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4045: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4046: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4047: $allfiles,$codebase);
4048: unless ($parse_result eq 'ok') {
4049: &logthis('Failed to parse '.$filepath.$file.
4050: ' for embedded media: '.$parse_result);
4051: }
1.637 raeburn 4052: }
1.1172.2.109 raeburn 4053: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4054: my $format = $env{'form.scantron_format'};
4055: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4056: }
1.860 raeburn 4057: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4058: my $input = $filepath.'/'.$file;
4059: my $output = $filepath.'/'.'tn-'.$file;
4060: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 4061: my @args = ('convert','-sample',$thumbsize,$input,$output);
4062: system({$args[0]} @args);
1.860 raeburn 4063: if (-e $filepath.'/'.'tn-'.$file) {
4064: $fetchthumb = 1;
4065: }
4066: }
1.858 raeburn 4067:
1.259 www 4068: # Notify homeserver to grep it
4069: #
1.984 neumanie 4070: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4071: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4072: if ($fetchresult eq 'ok') {
1.860 raeburn 4073: if ($fetchthumb) {
4074: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4075: if ($thumbresult ne 'ok') {
4076: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4077: $docuhome.': '.$thumbresult);
4078: }
4079: }
1.259 www 4080: #
1.258 www 4081: # Return the URL to it
1.494 albertel 4082: return '/uploaded/'.$path.$file;
1.263 www 4083: } else {
1.494 albertel 4084: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4085: ': '.$fetchresult);
1.263 www 4086: return '/adm/notfound.html';
1.858 raeburn 4087: }
1.493 albertel 4088: }
4089:
1.637 raeburn 4090: sub extract_embedded_items {
1.961 raeburn 4091: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4092: my @state = ();
1.1164 raeburn 4093: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4094: my %javafiles = (
4095: codebase => '',
4096: code => '',
4097: archive => ''
4098: );
4099: my %mediafiles = (
4100: src => '',
4101: movie => '',
4102: );
1.648 raeburn 4103: my $p;
4104: if ($content) {
4105: $p = HTML::LCParser->new($content);
4106: } else {
1.961 raeburn 4107: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4108: }
1.641 albertel 4109: while (my $t=$p->get_token()) {
1.640 albertel 4110: if ($t->[0] eq 'S') {
4111: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4112: push(@state, $tagname);
1.648 raeburn 4113: if (lc($tagname) eq 'allow') {
4114: &add_filetype($allfiles,$attr->{'src'},'src');
4115: }
1.640 albertel 4116: if (lc($tagname) eq 'img') {
4117: &add_filetype($allfiles,$attr->{'src'},'src');
4118: }
1.886 albertel 4119: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 4120: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4121: &add_filetype($allfiles,$attr->{'href'},'href');
4122: }
1.886 albertel 4123: }
1.645 raeburn 4124: if (lc($tagname) eq 'script') {
1.1164 raeburn 4125: my $src;
1.645 raeburn 4126: if ($attr->{'archive'} =~ /\.jar$/i) {
4127: &add_filetype($allfiles,$attr->{'archive'},'archive');
4128: } else {
1.1164 raeburn 4129: if ($attr->{'src'} ne '') {
4130: $src = $attr->{'src'};
4131: &add_filetype($allfiles,$src,'src');
4132: }
4133: }
4134: my $text = $p->get_trimmed_text();
4135: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4136: my @swfargs = split(/,/,$1);
4137: foreach my $item (@swfargs) {
4138: $item =~ s/["']//g;
4139: $item =~ s/^\s+//;
4140: $item =~ s/\s+$//;
4141: }
4142: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4143: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4144: push(@{$related{$swfargs[0]}},$swfargs[2]);
4145: } else {
4146: $related{$swfargs[0]} = [$swfargs[2]];
4147: }
4148: }
1.645 raeburn 4149: }
4150: }
4151: if (lc($tagname) eq 'link') {
4152: if (lc($attr->{'rel'}) eq 'stylesheet') {
4153: &add_filetype($allfiles,$attr->{'href'},'href');
4154: }
4155: }
1.640 albertel 4156: if (lc($tagname) eq 'object' ||
4157: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4158: foreach my $item (keys(%javafiles)) {
4159: $javafiles{$item} = '';
4160: }
1.1164 raeburn 4161: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4162: $lastids{lc($tagname)} = $attr->{'id'};
4163: }
1.640 albertel 4164: }
4165: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4166: my $name = lc($attr->{'name'});
4167: foreach my $item (keys(%javafiles)) {
4168: if ($name eq $item) {
4169: $javafiles{$item} = $attr->{'value'};
4170: last;
4171: }
4172: }
1.1164 raeburn 4173: my $pathfrom;
1.640 albertel 4174: foreach my $item (keys(%mediafiles)) {
4175: if ($name eq $item) {
1.1164 raeburn 4176: $pathfrom = $attr->{'value'};
4177: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4178: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4179: last;
4180: }
4181: }
1.1164 raeburn 4182: if ($name eq 'flashvars') {
4183: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4184: }
4185: if ($pathfrom ne '') {
4186: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4187: $pathfrom);
4188: }
1.640 albertel 4189: }
4190: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4191: foreach my $item (keys(%javafiles)) {
4192: if ($attr->{$item}) {
4193: $javafiles{$item} = $attr->{$item};
4194: last;
4195: }
4196: }
4197: foreach my $item (keys(%mediafiles)) {
4198: if ($attr->{$item}) {
4199: &add_filetype($allfiles,$attr->{$item},$item);
4200: last;
4201: }
4202: }
1.1164 raeburn 4203: if (lc($tagname) eq 'embed') {
4204: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4205: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4206: $attr->{'src'});
4207: }
4208: }
1.640 albertel 4209: }
1.1172.2.35 raeburn 4210: if (lc($tagname) eq 'iframe') {
4211: my $src = $attr->{'src'} ;
4212: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4213: &add_filetype($allfiles,$src,'src');
4214: } elsif ($src =~ m{^/}) {
4215: if ($env{'request.course.id'}) {
4216: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4217: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4218: my $url = &hreflocation('',$fullpath);
4219: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4220: my $relpath = $1;
4221: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4222: &add_filetype($allfiles,$1,'src');
4223: }
4224: }
4225: }
4226: }
4227: }
1.1164 raeburn 4228: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4229: pop(@state);
1.1164 raeburn 4230: }
1.640 albertel 4231: } elsif ($t->[0] eq 'E') {
4232: my ($tagname) = ($t->[1]);
4233: if ($javafiles{'codebase'} ne '') {
4234: $javafiles{'codebase'} .= '/';
4235: }
4236: if (lc($tagname) eq 'applet' ||
4237: lc($tagname) eq 'object' ||
4238: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4239: ) {
4240: foreach my $item (keys(%javafiles)) {
4241: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4242: my $file=$javafiles{'codebase'}.$javafiles{$item};
4243: &add_filetype($allfiles,$file,$item);
4244: }
4245: }
4246: }
4247: pop @state;
4248: }
4249: }
1.1164 raeburn 4250: foreach my $id (sort(keys(%flashvars))) {
4251: if ($shockwave{$id} ne '') {
4252: my @pairs = split(/\&/,$flashvars{$id});
4253: foreach my $pair (@pairs) {
4254: my ($key,$value) = split(/\=/,$pair);
4255: if ($key eq 'thumb') {
4256: &add_filetype($allfiles,$value,$key);
4257: } elsif ($key eq 'content') {
4258: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4259: my ($ext) = ($value =~ /\.([^.]+)$/);
4260: if ($ext ne '') {
4261: &add_filetype($allfiles,$path.$value,$ext);
4262: }
4263: }
4264: }
4265: }
4266: }
1.637 raeburn 4267: return 'ok';
4268: }
4269:
1.639 albertel 4270: sub add_filetype {
4271: my ($allfiles,$file,$type)=@_;
4272: if (exists($allfiles->{$file})) {
4273: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4274: push(@{$allfiles->{$file}}, &escape($type));
4275: }
4276: } else {
4277: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4278: }
4279: }
4280:
1.1164 raeburn 4281: sub embedded_dependency {
4282: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4283: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4284: if (($identifier ne '') &&
4285: (ref($related->{$identifier}) eq 'ARRAY') &&
4286: ($pathfrom ne '')) {
4287: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4288: foreach my $dep (@{$related->{$identifier}}) {
4289: &add_filetype($allfiles,$path.$dep,'object');
4290: }
4291: }
4292: }
4293: return;
4294: }
4295:
1.1172.2.109 raeburn 4296: sub bubblesheet_converter {
4297: my ($cdom,$fullpath,$config,$format) = @_;
4298: if ((&domain($cdom) ne '') &&
4299: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4300: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4301: my (%csvcols,%csvoptions);
4302: if (ref($config->{'fields'}) eq 'HASH') {
4303: %csvcols = %{$config->{'fields'}};
4304: }
4305: if (ref($config->{'options'}) eq 'HASH') {
4306: %csvoptions = %{$config->{'options'}};
4307: }
4308: my %csvbynum = reverse(%csvcols);
4309: my %scantronconf = &get_scantron_config($format,$cdom);
4310: if (keys(%scantronconf)) {
4311: my %bynum = (
4312: $scantronconf{CODEstart} => 'CODEstart',
4313: $scantronconf{IDstart} => 'IDstart',
4314: $scantronconf{PaperID} => 'PaperID',
4315: $scantronconf{FirstName} => 'FirstName',
4316: $scantronconf{LastName} => 'LastName',
4317: $scantronconf{Qstart} => 'Qstart',
4318: );
4319: my @ordered;
4320: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4321: push(@ordered,$bynum{$item});
4322: }
4323: my %mapstart = (
4324: CODEstart => 'CODE',
4325: IDstart => 'ID',
4326: PaperID => 'PaperID',
4327: FirstName => 'FirstName',
4328: LastName => 'LastName',
4329: Qstart => 'FirstQuestion',
4330: );
4331: my %maplength = (
4332: CODEstart => 'CODElength',
4333: IDstart => 'IDlength',
4334: PaperID => 'PaperIDlength',
4335: FirstName => 'FirstNamelength',
4336: LastName => 'LastNamelength',
4337: );
4338: if (open(my $fh,'<',$fullpath)) {
4339: my $output;
4340: my %lettdig = &letter_to_digits();
4341: my %diglett = reverse(%lettdig);
4342: my $numletts = scalar(keys(%lettdig));
4343: my $num = 0;
4344: while (my $line=<$fh>) {
4345: $num ++;
4346: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4347: $line =~ s{[\r\n]+$}{};
4348: my %found;
4349: my @values = split(/,/,$line);
4350: my ($qstart,$record);
4351: for (my $i=0; $i<@values; $i++) {
4352: if ((($qstart ne '') && ($i > $qstart)) ||
4353: ($csvbynum{$i} eq 'FirstQuestion')) {
4354: if ($values[$i] eq '') {
4355: $values[$i] = $scantronconf{'Qoff'};
4356: } elsif ($scantronconf{'Qon'} eq 'number') {
4357: if ($values[$i] =~ /^[A-Ja-j]$/) {
4358: $values[$i] = $lettdig{uc($values[$i])};
4359: }
4360: } elsif ($scantronconf{'Qon'} eq 'letter') {
4361: if ($values[$i] =~ /^[0-9]$/) {
4362: $values[$i] = $diglett{$values[$i]};
4363: }
4364: } else {
4365: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4366: my $digit;
4367: if ($values[$i] =~ /^[A-Ja-j]$/) {
4368: $digit = $lettdig{uc($values[$i])}-1;
4369: if ($values[$i] eq 'J') {
4370: $digit += $numletts;
4371: }
4372: } elsif ($values[$i] =~ /^[0-9]$/) {
4373: $digit = $values[$i]-1;
4374: if ($values[$i] eq '0') {
4375: $digit += $numletts;
4376: }
4377: }
4378: my $qval='';
4379: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4380: if ($j == $digit) {
4381: $qval .= $scantronconf{'Qon'};
4382: } else {
4383: $qval .= $scantronconf{'Qoff'};
4384: }
4385: }
4386: $values[$i] = $qval;
4387: }
4388: }
4389: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4390: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4391: }
4392: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4393: if ($numblank > 0) {
4394: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4395: }
4396: if ($csvbynum{$i} eq 'FirstQuestion') {
4397: $qstart = $i;
4398: $found{$csvbynum{$i}} = $values[$i];
4399: } else {
4400: $found{'FirstQuestion'} .= $values[$i];
4401: }
4402: } elsif (exists($csvbynum{$i})) {
4403: if ($csvoptions{'rem'}) {
4404: $values[$i] =~ s/^\s+//;
4405: }
4406: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4407: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4408: $values[$i] = '0'.$values[$i];
4409: }
4410: }
4411: $found{$csvbynum{$i}} = $values[$i];
4412: }
4413: }
4414: foreach my $item (@ordered) {
4415: my $currlength = 1+length($record);
4416: my $numspaces = $scantronconf{$item} - $currlength;
4417: if ($numspaces > 0) {
4418: $record .= (' ' x $numspaces);
4419: }
4420: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4421: unless ($item eq 'Qstart') {
4422: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4423: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4424: }
4425: }
4426: $record .= $found{$mapstart{$item}};
4427: }
4428: }
4429: $output .= "$record\n";
4430: }
4431: close($fh);
4432: if ($output) {
4433: if (open(my $fh,'>',$fullpath)) {
4434: print $fh $output;
4435: close($fh);
4436: }
4437: }
4438: }
4439: }
4440: return;
4441: }
4442: }
4443:
4444: sub letter_to_digits {
4445: my %lettdig = (
4446: A => 1,
4447: B => 2,
4448: C => 3,
4449: D => 4,
4450: E => 5,
4451: F => 6,
4452: G => 7,
4453: H => 8,
4454: I => 9,
4455: J => 0,
4456: );
4457: return %lettdig;
4458: }
4459:
4460: sub get_scantron_config {
4461: my ($which,$cdom) = @_;
4462: my @lines = &get_scantronformat_file($cdom);
4463: my %config;
4464: #FIXME probably should move to XML it has already gotten a bit much now
4465: foreach my $line (@lines) {
4466: my ($name,$descrip)=split(/:/,$line);
4467: if ($name ne $which ) { next; }
4468: chomp($line);
4469: my @config=split(/:/,$line);
4470: $config{'name'}=$config[0];
4471: $config{'description'}=$config[1];
4472: $config{'CODElocation'}=$config[2];
4473: $config{'CODEstart'}=$config[3];
4474: $config{'CODElength'}=$config[4];
4475: $config{'IDstart'}=$config[5];
4476: $config{'IDlength'}=$config[6];
4477: $config{'Qstart'}=$config[7];
4478: $config{'Qlength'}=$config[8];
4479: $config{'Qoff'}=$config[9];
4480: $config{'Qon'}=$config[10];
4481: $config{'PaperID'}=$config[11];
4482: $config{'PaperIDlength'}=$config[12];
4483: $config{'FirstName'}=$config[13];
4484: $config{'FirstNamelength'}=$config[14];
4485: $config{'LastName'}=$config[15];
4486: $config{'LastNamelength'}=$config[16];
4487: $config{'BubblesPerRow'}=$config[17];
4488: last;
4489: }
4490: return %config;
4491: }
4492:
4493: sub get_scantronformat_file {
4494: my ($cdom) = @_;
4495: if ($cdom eq '') {
4496: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4497: }
4498: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4499: my $gottab = 0;
4500: my @lines;
4501: if (ref($domconfig{'scantron'}) eq 'HASH') {
4502: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4503: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4504: if ($formatfile ne '-1') {
4505: @lines = split("\n",$formatfile,-1);
4506: $gottab = 1;
4507: }
4508: }
4509: }
4510: if (!$gottab) {
4511: my $confname = $cdom.'-domainconfig';
4512: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4513: my $formatfile = &getfile($default);
4514: if ($formatfile ne '-1') {
4515: @lines = split("\n",$formatfile,-1);
4516: $gottab = 1;
4517: }
4518: }
4519: if (!$gottab) {
4520: my @domains = ¤t_machine_domains();
4521: if (grep(/^\Q$cdom\E$/,@domains)) {
4522: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4523: @lines = <$fh>;
4524: close($fh);
4525: }
4526: } else {
4527: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4528: @lines = <$fh>;
4529: close($fh);
4530: }
4531: }
4532: }
4533: return @lines;
4534: }
4535:
1.493 albertel 4536: sub removeuploadedurl {
1.984 neumanie 4537: my ($url)=@_;
4538: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4539: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4540: }
4541:
4542: sub removeuserfile {
4543: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4544: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4545: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4546: if ($result eq 'ok') {
1.798 raeburn 4547: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4548: my $metafile = $fname.'.meta';
4549: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4550: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4551: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4552: my $sqlresult =
1.823 albertel 4553: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4554: 'portfolio_metadata',$group,
4555: 'delete');
1.798 raeburn 4556: }
4557: }
4558: return $result;
1.257 www 4559: }
1.15 www 4560:
1.530 albertel 4561: sub mkdiruserfile {
4562: my ($docuname,$docudom,$dir)=@_;
4563: my $home=&homeserver($docuname,$docudom);
4564: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4565: }
4566:
1.531 albertel 4567: sub renameuserfile {
4568: my ($docuname,$docudom,$old,$new)=@_;
4569: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4570: my $result = &reply("renameuserfile:$docudom:$docuname:".
4571: &escape("$old").':'.&escape("$new"),$home);
4572: if ($result eq 'ok') {
4573: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4574: my $oldmeta = $old.'.meta';
4575: my $newmeta = $new.'.meta';
4576: my $metaresult =
4577: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4578: my $url = "/uploaded/$docudom/$docuname/$old";
4579: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4580: my $sqlresult =
1.823 albertel 4581: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4582: 'portfolio_metadata',$group,
4583: 'delete');
1.798 raeburn 4584: }
4585: }
4586: return $result;
1.531 albertel 4587: }
4588:
1.14 www 4589: # ------------------------------------------------------------------------- Log
4590:
4591: sub log {
4592: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4593: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4594: }
4595:
4596: # ------------------------------------------------------------------ Course Log
1.352 www 4597: #
4598: # This routine flushes several buffers of non-mission-critical nature
4599: #
1.157 www 4600:
4601: sub flushcourselogs {
1.352 www 4602: &logthis('Flushing log buffers');
4603: #
4604: # course logs
4605: # This is a log of all transactions in a course, which can be used
4606: # for data mining purposes
4607: #
4608: # It also collects the courseid database, which lists last transaction
4609: # times and course titles for all courseids
4610: #
4611: my %courseidbuffer=();
1.921 raeburn 4612: foreach my $crsid (keys(%courselogs)) {
1.352 www 4613: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4614: &escape($courselogs{$crsid}),
4615: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4616: delete $courselogs{$crsid};
4617: } else {
4618: &logthis('Failed to flush log buffer for '.$crsid);
4619: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4620: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4621: " exceeded maximum size, deleting.</font>");
4622: delete $courselogs{$crsid};
4623: }
1.352 www 4624: }
1.920 raeburn 4625: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4626: 'description' => $coursedescrbuf{$crsid},
4627: 'inst_code' => $courseinstcodebuf{$crsid},
4628: 'type' => $coursetypebuf{$crsid},
4629: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4630: };
1.191 harris41 4631: }
1.352 www 4632: #
4633: # Write course id database (reverse lookup) to homeserver of courses
4634: # Is used in pickcourse
4635: #
1.840 albertel 4636: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4637: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4638: $courseidbuffer{$crs_home},
4639: $crs_home,'timeonly');
1.352 www 4640: }
4641: #
4642: # File accesses
4643: # Writes to the dynamic metadata of resources to get hit counts, etc.
4644: #
1.449 matthew 4645: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4646: if ($entry =~ /___count$/) {
4647: my ($dom,$name);
1.807 albertel 4648: ($dom,$name,undef)=
1.811 albertel 4649: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4650: if (! defined($dom) || $dom eq '' ||
4651: ! defined($name) || $name eq '') {
1.620 albertel 4652: my $cid = $env{'request.course.id'};
4653: $dom = $env{'request.'.$cid.'.domain'};
4654: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4655: }
1.450 matthew 4656: my $value = $accesshash{$entry};
4657: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4658: my %temphash=($url => $value);
1.449 matthew 4659: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4660: if ($result eq 'ok') {
4661: delete $accesshash{$entry};
4662: }
4663: } else {
1.811 albertel 4664: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4665: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4666: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4667: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4668: delete $accesshash{$entry};
4669: }
1.185 www 4670: }
1.191 harris41 4671: }
1.352 www 4672: #
4673: # Roles
4674: # Reverse lookup of user roles for course faculty/staff and co-authorship
4675: #
1.800 albertel 4676: foreach my $entry (keys(%userrolehash)) {
1.351 www 4677: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4678: split(/\:/,$entry);
4679: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4680: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4681: $rudom,$runame) eq 'ok') {
4682: delete $userrolehash{$entry};
4683: }
4684: }
1.662 raeburn 4685: #
1.1172.2.90 raeburn 4686: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4687: #
4688: my %domrolebuffer = ();
1.1000 raeburn 4689: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4690: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4691: if ($domrolebuffer{$rudom}) {
4692: $domrolebuffer{$rudom}.='&'.&escape($entry).
4693: '='.&escape($domainrolehash{$entry});
4694: } else {
4695: $domrolebuffer{$rudom}.=&escape($entry).
4696: '='.&escape($domainrolehash{$entry});
4697: }
4698: delete $domainrolehash{$entry};
4699: }
4700: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4701: my %servers;
4702: if (defined(&domain($dom,'primary'))) {
4703: my $primary=&domain($dom,'primary');
4704: my $hostname=&hostname($primary);
4705: $servers{$primary} = $hostname;
4706: } else {
4707: %servers = &get_servers($dom,'library');
4708: }
1.841 albertel 4709: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4710: if (&reply('domroleput:'.$dom.':'.
4711: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4712: last;
4713: } else {
1.841 albertel 4714: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4715: }
1.662 raeburn 4716: }
4717: }
1.186 www 4718: $dumpcount++;
1.157 www 4719: }
4720:
4721: sub courselog {
4722: my $what=shift;
1.158 www 4723: $what=time.':'.$what;
1.620 albertel 4724: unless ($env{'request.course.id'}) { return ''; }
4725: $coursedombuf{$env{'request.course.id'}}=
4726: $env{'course.'.$env{'request.course.id'}.'.domain'};
4727: $coursenumbuf{$env{'request.course.id'}}=
4728: $env{'course.'.$env{'request.course.id'}.'.num'};
4729: $coursehombuf{$env{'request.course.id'}}=
4730: $env{'course.'.$env{'request.course.id'}.'.home'};
4731: $coursedescrbuf{$env{'request.course.id'}}=
4732: $env{'course.'.$env{'request.course.id'}.'.description'};
4733: $courseinstcodebuf{$env{'request.course.id'}}=
4734: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4735: $courseownerbuf{$env{'request.course.id'}}=
4736: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4737: $coursetypebuf{$env{'request.course.id'}}=
4738: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4739: if (defined $courselogs{$env{'request.course.id'}}) {
4740: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4741: } else {
1.620 albertel 4742: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4743: }
1.620 albertel 4744: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4745: &flushcourselogs();
4746: }
1.158 www 4747: }
4748:
4749: sub courseacclog {
4750: my $fnsymb=shift;
1.620 albertel 4751: unless ($env{'request.course.id'}) { return ''; }
4752: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4753: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4754: $what.=':POST';
1.583 matthew 4755: # FIXME: Probably ought to escape things....
1.800 albertel 4756: foreach my $key (keys(%env)) {
4757: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4758: my $formitem = $1;
4759: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4760: $what.=':'.$formitem.'='.$env{$key};
4761: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.118. .12(raeb 4762:-20): if ($formitem eq 'proctorpassword') {
4763:-20): $what.=':'.$formitem.'=' . '*' x length($env{$key});
4764:-20): } else {
4765:-20): $what.=':'.$formitem.'='.$env{$key};
4766:-20): }
1.975 raeburn 4767: }
1.158 www 4768: }
1.191 harris41 4769: }
1.583 matthew 4770: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4771: # FIXME: We should not be depending on a form parameter that someone
4772: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4773: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4774: $what.= ':POST';
4775: # FIXME: Probably ought to escape things....
4776: foreach my $element ('courseexp','crsfulltext','crsrelated',
4777: 'crsdiscuss') {
1.620 albertel 4778: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4779: }
4780: }
1.158 www 4781: }
4782: &courselog($what);
1.149 www 4783: }
4784:
1.185 www 4785: sub countacc {
4786: my $url=&declutter(shift);
1.458 matthew 4787: return if (! defined($url) || $url eq '');
1.620 albertel 4788: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4789: #
4790: # Mark that this url was used in this course
4791: #
1.620 albertel 4792: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4793: #
4794: # Increase the access count for this resource in this child process
4795: #
1.281 www 4796: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4797: $accesshash{$key}++;
1.185 www 4798: }
1.349 www 4799:
1.361 www 4800: sub linklog {
4801: my ($from,$to)=@_;
4802: $from=&declutter($from);
4803: $to=&declutter($to);
4804: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4805: $accesshash{$to.'___'.$from.'___goto'}=1;
4806: }
1.1160 www 4807:
4808: sub statslog {
4809: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4810: if ($users<2) { return; }
4811: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4812: 'course' => $env{'request.course.id'},
4813: 'sections' => '"all"',
4814: 'num_students' => $users,
4815: 'part' => $part,
4816: 'symb' => $symb,
4817: 'mean_tries' => $av_attempts,
4818: 'deg_of_diff' => $degdiff});
4819: foreach my $key (keys(%dynstore)) {
4820: $accesshash{$key}=$dynstore{$key};
4821: }
4822: }
1.361 www 4823:
1.349 www 4824: sub userrolelog {
4825: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4826: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4827: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4828: $userrolehash
4829: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4830: =$tend.':'.$tstart;
1.662 raeburn 4831: }
1.1169 droeschl 4832: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4833: $userrolehash
4834: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4835: =$tend.':'.$tstart;
4836: }
1.1172.2.90 raeburn 4837: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4838: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4839: $domainrolehash
4840: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4841: = $tend.':'.$tstart;
4842: }
1.351 www 4843: }
4844:
1.957 raeburn 4845: sub courserolelog {
4846: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4847: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4848: my $cdom = $1;
4849: my $cnum = $2;
4850: my $sec = $3;
4851: my $namespace = 'rolelog';
4852: my %storehash = (
4853: role => $trole,
4854: start => $tstart,
4855: end => $tend,
4856: selfenroll => $selfenroll,
4857: context => $context,
4858: );
4859: if ($trole eq 'gr') {
4860: $namespace = 'groupslog';
4861: $storehash{'group'} = $sec;
4862: } else {
4863: $storehash{'section'} = $sec;
4864: }
4865: &write_log('course',$namespace,\%storehash,$delflag,$username,
4866: $domain,$cnum,$cdom);
4867: if (($trole ne 'st') || ($sec ne '')) {
4868: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4869: }
4870: }
4871: return;
4872: }
4873:
1.1172.2.9 raeburn 4874: sub domainrolelog {
4875: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4876: if ($area =~ m{^/($match_domain)/$}) {
4877: my $cdom = $1;
4878: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4879: my $namespace = 'rolelog';
4880: my %storehash = (
4881: role => $trole,
4882: start => $tstart,
4883: end => $tend,
4884: context => $context,
4885: );
4886: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4887: $domain,$domconfiguser,$cdom);
4888: }
4889: return;
4890:
4891: }
4892:
4893: sub coauthorrolelog {
4894: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4895: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4896: my $audom = $1;
4897: my $auname = $2;
4898: my $namespace = 'rolelog';
4899: my %storehash = (
4900: role => $trole,
4901: start => $tstart,
4902: end => $tend,
4903: context => $context,
4904: );
4905: &write_log('author',$namespace,\%storehash,$delflag,$username,
4906: $domain,$auname,$audom);
4907: }
4908: return;
4909: }
4910:
1.351 www 4911: sub get_course_adv_roles {
1.948 raeburn 4912: my ($cid,$codes) = @_;
1.620 albertel 4913: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4914: my %coursehash=&coursedescription($cid);
1.988 raeburn 4915: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4916: my %nothide=();
1.800 albertel 4917: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4918: if ($user !~ /:/) {
4919: $nothide{join(':',split(/[\@]/,$user))}=1;
4920: } else {
4921: $nothide{$user}=1;
4922: }
1.470 www 4923: }
1.1172.2.23 raeburn 4924: my @possdoms = ($coursehash{'domain'});
4925: if ($coursehash{'checkforpriv'}) {
4926: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4927: }
1.351 www 4928: my %returnhash=();
4929: my %dumphash=
4930: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4931: my $now=time;
1.997 raeburn 4932: my %privileged;
1.1000 raeburn 4933: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4934: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4935: if (($tstart) && ($tstart<0)) { next; }
4936: if (($tend) && ($tend<$now)) { next; }
4937: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4938: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4939: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4940: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4941: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4942: if ($role eq 'cr') { next; }
1.948 raeburn 4943: if ($codes) {
4944: if ($section) { $role .= ':'.$section; }
4945: if ($returnhash{$role}) {
4946: $returnhash{$role}.=','.$username.':'.$domain;
4947: } else {
4948: $returnhash{$role}=$username.':'.$domain;
4949: }
1.351 www 4950: } else {
1.988 raeburn 4951: my $key=&plaintext($role,$crstype);
1.973 bisitz 4952: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4953: if ($returnhash{$key}) {
4954: $returnhash{$key}.=','.$username.':'.$domain;
4955: } else {
4956: $returnhash{$key}=$username.':'.$domain;
4957: }
1.351 www 4958: }
1.948 raeburn 4959: }
1.400 www 4960: return %returnhash;
4961: }
4962:
4963: sub get_my_roles {
1.937 raeburn 4964: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4965: unless (defined($uname)) { $uname=$env{'user.name'}; }
4966: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4967: my (%dumphash,%nothide);
1.1086 raeburn 4968: if ($context eq 'userroles') {
1.1166 raeburn 4969: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4970: } else {
1.1172.2.23 raeburn 4971: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4972: if ($hidepriv) {
4973: my %coursehash=&coursedescription($udom.'_'.$uname);
4974: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4975: if ($user !~ /:/) {
4976: $nothide{join(':',split(/[\@]/,$user))} = 1;
4977: } else {
4978: $nothide{$user} = 1;
4979: }
4980: }
4981: }
1.858 raeburn 4982: }
1.400 www 4983: my %returnhash=();
4984: my $now=time;
1.999 raeburn 4985: my %privileged;
1.800 albertel 4986: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4987: my ($role,$tend,$tstart);
4988: if ($context eq 'userroles') {
1.1149 raeburn 4989: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4990: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4991: } else {
4992: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4993: }
1.400 www 4994: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4995: my $status = 'active';
1.939 raeburn 4996: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4997: $status = 'previous';
4998: }
4999: if (($tstart) && ($now<$tstart)) {
5000: $status = 'future';
5001: }
5002: if (ref($types) eq 'ARRAY') {
5003: if (!grep(/^\Q$status\E$/,@{$types})) {
5004: next;
5005: }
5006: } else {
5007: if ($status ne 'active') {
5008: next;
5009: }
5010: }
1.867 raeburn 5011: my ($rolecode,$username,$domain,$section,$area);
5012: if ($context eq 'userroles') {
1.1172.2.9 raeburn 5013: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5014: (undef,$domain,$username,$section) = split(/\//,$area);
5015: } else {
5016: ($role,$username,$domain,$section) = split(/\:/,$entry);
5017: }
1.832 raeburn 5018: if (ref($roledoms) eq 'ARRAY') {
5019: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5020: next;
5021: }
5022: }
5023: if (ref($roles) eq 'ARRAY') {
5024: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5025: if ($role =~ /^cr\//) {
5026: if (!grep(/^cr$/,@{$roles})) {
5027: next;
5028: }
1.1104 raeburn 5029: } elsif ($role =~ /^gr\//) {
5030: if (!grep(/^gr$/,@{$roles})) {
5031: next;
5032: }
1.922 raeburn 5033: } else {
5034: next;
5035: }
1.832 raeburn 5036: }
1.867 raeburn 5037: }
1.937 raeburn 5038: if ($hidepriv) {
1.1172.2.23 raeburn 5039: my @privroles = ('dc','su');
1.999 raeburn 5040: if ($context eq 'userroles') {
1.1172.2.23 raeburn 5041: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5042: } else {
1.1172.2.23 raeburn 5043: my $possdoms = [$domain];
5044: if (ref($roledoms) eq 'ARRAY') {
5045: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5046: }
1.1172.2.23 raeburn 5047: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5048: if (!$nothide{$username.':'.$domain}) {
5049: next;
5050: }
5051: }
1.937 raeburn 5052: }
5053: }
1.933 raeburn 5054: if ($withsec) {
5055: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5056: $tstart.':'.$tend;
5057: } else {
5058: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5059: }
1.832 raeburn 5060: }
1.373 www 5061: return %returnhash;
1.399 www 5062: }
5063:
1.1172.2.89 raeburn 5064: sub get_all_adhocroles {
5065: my ($dom) = @_;
5066: my @roles_by_num = ();
5067: my %domdefaults = &get_domain_defaults($dom);
5068: my (%description,%access_in_dom,%access_info);
5069: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5070: my $count = 0;
5071: my %domcurrent = %{$domdefaults{'adhocroles'}};
5072: my %ordered;
5073: foreach my $role (sort(keys(%domcurrent))) {
5074: my ($order,$desc,$access_in_dom);
5075: if (ref($domcurrent{$role}) eq 'HASH') {
5076: $order = $domcurrent{$role}{'order'};
5077: $desc = $domcurrent{$role}{'desc'};
5078: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5079: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5080: }
5081: if ($order eq '') {
5082: $order = $count;
5083: }
5084: $ordered{$order} = $role;
5085: if ($desc ne '') {
5086: $description{$role} = $desc;
5087: } else {
5088: $description{$role}= $role;
5089: }
5090: $count++;
5091: }
5092: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5093: push(@roles_by_num,$ordered{$item});
5094: }
5095: }
5096: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5097: }
5098:
5099: sub get_my_adhocroles {
5100: my ($cid,$checkreg) = @_;
5101: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5102: if ($env{'request.course.id'} eq $cid) {
5103: $cdom = $env{'course.'.$cid.'.domain'};
5104: $cnum = $env{'course.'.$cid.'.num'};
5105: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5106: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5107: $cdom = $1;
5108: $cnum = $2;
5109: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5110: $cdom,$cnum);
5111: }
5112: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5113: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5114: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5115: if ($rosterhash{$user} ne '') {
5116: my $type = (split(/:/,$rosterhash{$user}))[5];
5117: return ([],{}) if ($type eq 'auto');
5118: }
5119: }
5120: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5121: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5122: my $then=$env{'user.login.time'};
5123: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5124: if (!$update) {
5125: $update = $then;
5126: }
5127: my @liveroles;
5128: foreach my $role ('dh','da') {
5129: if ($env{"user.role.$role./$cdom/"}) {
5130: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5131: my $limit = $update;
5132: if ($env{'request.role'} eq "$role./$cdom/") {
5133: $limit = $then;
5134: }
5135: my $activerole = 1;
5136: if ($tstart && $tstart>$limit) { $activerole = 0; }
5137: if ($tend && $tend <$limit) { $activerole = 0; }
5138: if ($activerole) {
5139: push(@liveroles,$role);
5140: }
5141: }
5142: }
5143: if (@liveroles) {
1.1172.2.89 raeburn 5144: if (&homeserver($cnum,$cdom) ne 'no_host') {
5145: my ($accessref,$accessinfo,%access_in_dom);
5146: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5147: if (ref($roles_by_num) eq 'ARRAY') {
5148: if (@{$roles_by_num}) {
5149: my %settings;
5150: if ($env{'request.course.id'} eq $cid) {
5151: foreach my $envkey (keys(%env)) {
5152: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5153: $settings{$1} = $env{$envkey};
5154: }
5155: }
5156: } else {
5157: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5158: }
5159: my %setincrs;
5160: if ($settings{'internal.adhocaccess'}) {
5161: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5162: }
5163: my @statuses;
5164: if ($env{'environment.inststatus'}) {
5165: @statuses = split(/,/,$env{'environment.inststatus'});
5166: }
5167: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5168: if (ref($accessref) eq 'HASH') {
5169: %access_in_dom = %{$accessref};
5170: }
5171: foreach my $role (@{$roles_by_num}) {
5172: my ($curraccess,@okstatus,@personnel);
5173: if ($setincrs{$role}) {
5174: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5175: if ($curraccess eq 'status') {
5176: @okstatus = split(/\&/,$rest);
5177: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5178: @personnel = split(/\&/,$rest);
5179: }
5180: } else {
5181: $curraccess = $access_in_dom{$role};
5182: if (ref($accessinfo) eq 'HASH') {
5183: if ($curraccess eq 'status') {
5184: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5185: @okstatus = @{$accessinfo->{$role}};
5186: }
5187: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5188: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5189: @personnel = @{$accessinfo->{$role}};
5190: }
5191: }
5192: }
5193: }
5194: if ($curraccess eq 'none') {
5195: next;
5196: } elsif ($curraccess eq 'all') {
5197: push(@possroles,$role);
1.1172.2.90 raeburn 5198: } elsif ($curraccess eq 'dh') {
5199: if (grep(/^dh$/,@liveroles)) {
5200: push(@possroles,$role);
5201: } else {
5202: next;
5203: }
5204: } elsif ($curraccess eq 'da') {
5205: if (grep(/^da$/,@liveroles)) {
5206: push(@possroles,$role);
5207: } else {
5208: next;
5209: }
1.1172.2.89 raeburn 5210: } elsif ($curraccess eq 'status') {
5211: if (@okstatus) {
5212: if (!@statuses) {
5213: if (grep(/^default$/,@okstatus)) {
5214: push(@possroles,$role);
5215: }
5216: } else {
5217: foreach my $status (@okstatus) {
5218: if (grep(/^\Q$status\E$/,@statuses)) {
5219: push(@possroles,$role);
5220: last;
5221: }
5222: }
5223: }
5224: }
5225: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5226: if (grep(/^\Q$user\E$/,@personnel)) {
5227: if ($curraccess eq 'exc') {
5228: push(@possroles,$role);
5229: }
5230: } elsif ($curraccess eq 'inc') {
5231: push(@possroles,$role);
5232: }
5233: }
5234: }
5235: }
5236: }
5237: }
5238: }
5239: }
5240: }
5241: unless (ref($description) eq 'HASH') {
5242: if (ref($roles_by_num) eq 'ARRAY') {
5243: my %desc;
5244: map { $desc{$_} = $_; } (@{$roles_by_num});
5245: $description = \%desc;
5246: } else {
5247: $description = {};
5248: }
5249: }
5250: return (\@possroles,$description);
5251: }
5252:
1.399 www 5253: # ----------------------------------------------------- Frontpage Announcements
5254: #
5255: #
5256:
5257: sub postannounce {
5258: my ($server,$text)=@_;
1.844 albertel 5259: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5260: unless ($text=~/\w/) { $text=''; }
5261: return &reply('setannounce:'.&escape($text),$server);
5262: }
5263:
5264: sub getannounce {
1.448 albertel 5265:
1.1172.2.96 raeburn 5266: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5267: my $announcement='';
1.800 albertel 5268: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5269: close($fh);
1.399 www 5270: if ($announcement=~/\w/) {
5271: return
5272: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5273: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5274: } else {
5275: return '';
5276: }
5277: } else {
5278: return '';
5279: }
1.351 www 5280: }
1.353 www 5281:
5282: # ---------------------------------------------------------- Course ID routines
5283: # Deal with domain's nohist_courseid.db files
5284: #
5285:
5286: sub courseidput {
1.921 raeburn 5287: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5288: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5289: my $outcome;
5290: if ($caller eq 'timeonly') {
5291: my $cids = '';
5292: foreach my $item (keys(%$storehash)) {
5293: $cids.=&escape($item).'&';
5294: }
5295: $cids=~s/\&$//;
5296: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5297: $coursehome);
5298: } else {
5299: my $items = '';
5300: foreach my $item (keys(%$storehash)) {
5301: $items.= &escape($item).'='.
5302: &freeze_escape($$storehash{$item}).'&';
5303: }
5304: $items=~s/\&$//;
5305: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5306: $coursehome);
1.918 raeburn 5307: }
5308: if ($outcome eq 'unknown_cmd') {
5309: my $what;
5310: foreach my $cid (keys(%$storehash)) {
5311: $what .= &escape($cid).'=';
1.921 raeburn 5312: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5313: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5314: }
5315: $what =~ s/\:$/&/;
5316: }
5317: $what =~ s/\&$//;
5318: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5319: } else {
5320: return $outcome;
5321: }
1.353 www 5322: }
5323:
5324: sub courseiddump {
1.921 raeburn 5325: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5326: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5327: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5328: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5329: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5330: my $as_hash = 1;
5331: my %returnhash;
5332: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5333: my %libserv = &all_library();
5334: foreach my $tryserver (keys(%libserv)) {
5335: if ( ( $hostidflag == 1
5336: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5337: || (!defined($hostidflag)) ) {
5338:
1.918 raeburn 5339: if (($domfilter eq '') ||
5340: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5341: my $rep;
5342: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5343: $rep = &LONCAPA::Lond::dump_course_id_handler(
5344: join(":", (&host_domain($tryserver), $sincefilter,
5345: &escape($descfilter), &escape($instcodefilter),
5346: &escape($ownerfilter), &escape($coursefilter),
5347: &escape($typefilter), &escape($regexp_ok),
5348: $as_hash, &escape($selfenrollonly),
5349: &escape($catfilter), $showhidden, $caller,
5350: &escape($cloner), &escape($cc_clone), $cloneonly,
5351: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5352: &escape($creationcontext),$domcloner,$hasuniquecode,
5353: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5354: } else {
5355: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5356: $sincefilter.':'.&escape($descfilter).':'.
5357: &escape($instcodefilter).':'.&escape($ownerfilter).
5358: ':'.&escape($coursefilter).':'.&escape($typefilter).
5359: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5360: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5361: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5362: &escape($cc_clone).':'.$cloneonly.':'.
5363: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5364: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5365: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5366: }
5367:
1.918 raeburn 5368: my @pairs=split(/\&/,$rep);
5369: foreach my $item (@pairs) {
5370: my ($key,$value)=split(/\=/,$item,2);
5371: $key = &unescape($key);
5372: next if ($key =~ /^error: 2 /);
5373: my $result = &thaw_unescape($value);
5374: if (ref($result) eq 'HASH') {
5375: $returnhash{$key}=$result;
5376: } else {
1.921 raeburn 5377: my @responses = split(/:/,$value);
5378: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5379: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5380: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5381: }
1.1008 raeburn 5382: }
1.353 www 5383: }
5384: }
5385: }
5386: }
5387: return %returnhash;
5388: }
5389:
1.1055 raeburn 5390: sub courselastaccess {
5391: my ($cdom,$cnum,$hostidref) = @_;
5392: my %returnhash;
5393: if ($cdom && $cnum) {
5394: my $chome = &homeserver($cnum,$cdom);
5395: if ($chome ne 'no_host') {
5396: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5397: &extract_lastaccess(\%returnhash,$rep);
5398: }
5399: } else {
5400: if (!$cdom) { $cdom=''; }
5401: my %libserv = &all_library();
5402: foreach my $tryserver (keys(%libserv)) {
5403: if (ref($hostidref) eq 'ARRAY') {
5404: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5405: }
5406: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5407: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5408: &extract_lastaccess(\%returnhash,$rep);
5409: }
5410: }
5411: }
5412: return %returnhash;
5413: }
5414:
5415: sub extract_lastaccess {
5416: my ($returnhash,$rep) = @_;
5417: if (ref($returnhash) eq 'HASH') {
5418: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5419: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5420: $rep eq '') {
5421: my @pairs=split(/\&/,$rep);
5422: foreach my $item (@pairs) {
5423: my ($key,$value)=split(/\=/,$item,2);
5424: $key = &unescape($key);
5425: next if ($key =~ /^error: 2 /);
5426: $returnhash->{$key} = &thaw_unescape($value);
5427: }
5428: }
5429: }
5430: return;
5431: }
5432:
1.658 raeburn 5433: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5434:
5435: sub dcmailput {
1.685 raeburn 5436: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5437: my $status = &Apache::lonnet::critical(
1.740 www 5438: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5439: &escape($message),$server);
1.662 raeburn 5440: return $status;
5441: }
5442:
1.658 raeburn 5443: sub dcmaildump {
5444: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5445: my %returnhash=();
1.846 albertel 5446:
5447: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5448: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5449: &escape($enddate).':';
5450: my @esc_senders=map { &escape($_)} @$senders;
5451: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5452: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5453: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5454: if (($key) && ($value)) {
5455: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5456: }
5457: }
5458: }
5459: return %returnhash;
5460: }
1.662 raeburn 5461: # ---------------------------------------------------------- Domain roles
5462:
5463: sub get_domain_roles {
5464: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5465: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5466: $startdate = '.';
5467: }
1.1018 raeburn 5468: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5469: $enddate = '.';
5470: }
1.922 raeburn 5471: my $rolelist;
5472: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5473: $rolelist = join('&',@{$roles});
1.922 raeburn 5474: }
1.662 raeburn 5475: my %personnel = ();
1.841 albertel 5476:
5477: my %servers = &get_servers($dom,'library');
5478: foreach my $tryserver (keys(%servers)) {
5479: %{$personnel{$tryserver}}=();
5480: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5481: &escape($startdate).':'.
5482: &escape($enddate).':'.
5483: &escape($rolelist), $tryserver))) {
5484: my ($key,$value) = split(/\=/,$line,2);
5485: if (($key) && ($value)) {
5486: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5487: }
5488: }
1.662 raeburn 5489: }
5490: return %personnel;
5491: }
1.658 raeburn 5492:
1.1172.2.89 raeburn 5493: sub get_active_domroles {
5494: my ($dom,$roles) = @_;
5495: return () unless (ref($roles) eq 'ARRAY');
5496: my $now = time;
5497: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5498: my %domroles;
5499: foreach my $server (keys(%dompersonnel)) {
5500: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5501: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5502: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5503: }
5504: }
5505: return %domroles;
5506: }
5507:
1.1057 www 5508: # ----------------------------------------------------------- Interval timing
1.149 www 5509:
1.1153 www 5510: {
5511: # Caches needed for speedup of navmaps
5512: # We don't want to cache this for very long at all (5 seconds at most)
5513: #
5514: # The user for whom we cache
5515: my $cachedkey='';
5516: # The cached times for this user
5517: my %cachedtimes=();
5518: # When this was last done
1.1172.2.66 raeburn 5519: my $cachedtime='';
1.1153 www 5520:
5521: sub load_all_first_access {
1.1172.2.118. .1(raebu 5522:20): my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5523: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.118. .1(raebu 5524:20): (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5525:20): (!$ignorecache)) {
1.1154 raeburn 5526: return;
5527: }
5528: $cachedtime=time;
5529: $cachedkey=$uname.':'.$udom;
5530: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5531: }
5532:
1.504 albertel 5533: sub get_first_access {
1.1172.2.118. .1(raebu 5534:20): my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5535: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5536: if ($argsymb) { $symb=$argsymb; }
5537: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5538: if ($argmap) { $map = $argmap; }
1.926 albertel 5539: if ($type eq 'course') {
5540: $res='course';
5541: } elsif ($type eq 'map') {
1.588 albertel 5542: $res=&symbread($map);
5543: } else {
5544: $res=$symb;
5545: }
1.1172.2.118. .1(raebu 5546:20): &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5547: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5548: }
5549:
5550: sub set_first_access {
1.1162 raeburn 5551: my ($type,$interval)=@_;
1.790 albertel 5552: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5553: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5554: if ($type eq 'course') {
5555: $res='course';
5556: } elsif ($type eq 'map') {
1.588 albertel 5557: $res=&symbread($map);
5558: } else {
5559: $res=$symb;
5560: }
1.1153 www 5561: $cachedkey='';
1.1162 raeburn 5562: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5563: if ($firstaccess) {
5564: &logthis("First access time already set ($firstaccess) when attempting ".
5565: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5566: "in $courseid");
5567: return 'already_set';
5568: } else {
1.1162 raeburn 5569: my $start = time;
5570: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5571: $udom,$uname);
5572: if ($putres eq 'ok') {
5573: &put('timerinterval',{"$courseid\0$res"=>$interval},
5574: $udom,$uname);
5575: &appenv(
5576: {
5577: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5578: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5579: }
5580: );
1.1172.2.97 raeburn 5581: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5582: $cachedtimes{"$courseid\0$res"} = $start;
5583: }
1.1172.2.102 raeburn 5584: } elsif ($putres ne 'refused') {
5585: &logthis("Result: $putres when attempting to set first access time ".
5586: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5587: }
5588: return $putres;
1.505 albertel 5589: }
5590: return 'already_set';
1.504 albertel 5591: }
1.1153 www 5592: }
1.1172.2.32 raeburn 5593:
5594: sub checkout {
5595: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5596: my $now=time;
5597: my $lonhost=$perlvar{'lonHostID'};
1.1172.2.118. .14(raeb 5598:-21): my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5599: my $infostr=&escape(
5600: 'CHECKOUTTOKEN&'.
5601: $tuname.'&'.
5602: $tudom.'&'.
5603: $tcrsid.'&'.
5604: $symb.'&'.
1.1172.2.118. .14(raeb 5605:-21): $now.'&'.$ip);
1.1172.2.32 raeburn 5606: my $token=&reply('tmpput:'.$infostr,$lonhost);
5607: if ($token=~/^error\:/) {
5608: &logthis("<font color=\"blue\">WARNING: ".
5609: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5610: "</font>");
5611: return '';
5612: }
5613:
5614: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5615: $token=~tr/a-z/A-Z/;
5616:
5617: my %infohash=('resource.0.outtoken' => $token,
5618: 'resource.0.checkouttime' => $now,
1.1172.2.118. .14(raeb 5619:-21): 'resource.0.outremote' => $ip);
1.1172.2.32 raeburn 5620:
5621: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5622: return '';
5623: } else {
5624: &logthis("<font color=\"blue\">WARNING: ".
5625: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5626: "</font>");
5627: }
5628:
5629: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5630: &escape('Checkout '.$infostr.' - '.
5631: $token)) ne 'ok') {
5632: return '';
5633: } else {
5634: &logthis("<font color=\"blue\">WARNING: ".
5635: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5636: "</font>");
5637: }
5638: return $token;
5639: }
5640:
5641: # ------------------------------------------------------------ Check in an item
5642:
5643: sub checkin {
5644: my $token=shift;
5645: my $now=time;
5646: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5647: $lonhost=~tr/A-Z/a-z/;
5648: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5649: $dtoken=~s/\W/\_/g;
1.1172.2.118. .14(raeb 5650:-21): my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5651: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5652: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5653:
5654: unless (($tuname) && ($tudom)) {
5655: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5656: return '';
5657: }
5658:
5659: unless (&allowed('mgr',$tcrsid)) {
5660: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5661: $env{'user.name'}.' - '.$env{'user.domain'});
5662: return '';
5663: }
5664:
5665: my %infohash=('resource.0.intoken' => $token,
5666: 'resource.0.checkintime' => $now,
1.1172.2.118. .14(raeb 5667:-21): 'resource.0.inremote' => $ip);
1.1172.2.32 raeburn 5668:
5669: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5670: return '';
5671: }
5672:
5673: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5674: &escape('Checkin - '.$token)) ne 'ok') {
5675: return '';
5676: }
5677:
5678: return ($symb,$tuname,$tudom,$tcrsid);
5679: }
5680:
1.110 www 5681: # --------------------------------------------- Set Expire Date for Spreadsheet
5682:
5683: sub expirespread {
5684: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5685: my $cid=$env{'request.course.id'};
1.110 www 5686: if ($cid) {
5687: my $now=time;
5688: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5689: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5690: $env{'course.'.$cid.'.num'}.
1.110 www 5691: ':nohist_expirationdates:'.
5692: &escape($key).'='.$now,
1.620 albertel 5693: $env{'course.'.$cid.'.home'})
1.110 www 5694: }
5695: return 'ok';
1.14 www 5696: }
5697:
1.109 www 5698: # ----------------------------------------------------- Devalidate Spreadsheets
5699:
5700: sub devalidate {
1.325 www 5701: my ($symb,$uname,$udom)=@_;
1.620 albertel 5702: my $cid=$env{'request.course.id'};
1.109 www 5703: if ($cid) {
1.391 matthew 5704: # delete the stored spreadsheets for
5705: # - the student level sheet of this user in course's homespace
5706: # - the assessment level sheet for this resource
5707: # for this user in user's homespace
1.553 albertel 5708: # - current conditional state info
1.325 www 5709: my $key=$uname.':'.$udom.':';
1.109 www 5710: my $status=
1.299 matthew 5711: &del('nohist_calculatedsheets',
1.391 matthew 5712: [$key.'studentcalc:'],
1.620 albertel 5713: $env{'course.'.$cid.'.domain'},
5714: $env{'course.'.$cid.'.num'})
1.133 albertel 5715: .' '.
5716: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5717: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5718: unless ($status eq 'ok ok') {
5719: &logthis('Could not devalidate spreadsheet '.
1.325 www 5720: $uname.' at '.$udom.' for '.
1.109 www 5721: $symb.': '.$status);
1.133 albertel 5722: }
1.553 albertel 5723: &delenv('user.state.'.$cid);
1.109 www 5724: }
5725: }
5726:
1.265 albertel 5727: sub get_scalar {
5728: my ($string,$end) = @_;
5729: my $value;
5730: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5731: $value = $1;
5732: } elsif ($$string =~ s/^([^&]*?)&//) {
5733: $value = $1;
5734: }
5735: return &unescape($value);
5736: }
5737:
5738: sub array2str {
5739: my (@array) = @_;
5740: my $result=&arrayref2str(\@array);
5741: $result=~s/^__ARRAY_REF__//;
5742: $result=~s/__END_ARRAY_REF__$//;
5743: return $result;
5744: }
5745:
1.204 albertel 5746: sub arrayref2str {
5747: my ($arrayref) = @_;
1.265 albertel 5748: my $result='__ARRAY_REF__';
1.204 albertel 5749: foreach my $elem (@$arrayref) {
1.265 albertel 5750: if(ref($elem) eq 'ARRAY') {
5751: $result.=&arrayref2str($elem).'&';
5752: } elsif(ref($elem) eq 'HASH') {
5753: $result.=&hashref2str($elem).'&';
5754: } elsif(ref($elem)) {
5755: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5756: } else {
5757: $result.=&escape($elem).'&';
5758: }
5759: }
5760: $result=~s/\&$//;
1.265 albertel 5761: $result .= '__END_ARRAY_REF__';
1.204 albertel 5762: return $result;
5763: }
5764:
1.168 albertel 5765: sub hash2str {
1.204 albertel 5766: my (%hash) = @_;
5767: my $result=&hashref2str(\%hash);
1.265 albertel 5768: $result=~s/^__HASH_REF__//;
5769: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5770: return $result;
5771: }
5772:
5773: sub hashref2str {
5774: my ($hashref)=@_;
1.265 albertel 5775: my $result='__HASH_REF__';
1.800 albertel 5776: foreach my $key (sort(keys(%$hashref))) {
5777: if (ref($key) eq 'ARRAY') {
5778: $result.=&arrayref2str($key).'=';
5779: } elsif (ref($key) eq 'HASH') {
5780: $result.=&hashref2str($key).'=';
5781: } elsif (ref($key)) {
1.265 albertel 5782: $result.='=';
1.800 albertel 5783: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5784: } else {
1.1132 raeburn 5785: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5786: }
5787:
1.800 albertel 5788: if(ref($hashref->{$key}) eq 'ARRAY') {
5789: $result.=&arrayref2str($hashref->{$key}).'&';
5790: } elsif(ref($hashref->{$key}) eq 'HASH') {
5791: $result.=&hashref2str($hashref->{$key}).'&';
5792: } elsif(ref($hashref->{$key})) {
1.265 albertel 5793: $result.='&';
1.800 albertel 5794: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5795: } else {
1.800 albertel 5796: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5797: }
5798: }
1.168 albertel 5799: $result=~s/\&$//;
1.265 albertel 5800: $result .= '__END_HASH_REF__';
1.168 albertel 5801: return $result;
5802: }
5803:
5804: sub str2hash {
1.265 albertel 5805: my ($string)=@_;
5806: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5807: return %$hash;
5808: }
5809:
5810: sub str2hashref {
1.168 albertel 5811: my ($string) = @_;
1.265 albertel 5812:
5813: my %hash;
5814:
5815: if($string !~ /^__HASH_REF__/) {
5816: if (! ($string eq '' || !defined($string))) {
5817: $hash{'error'}='Not hash reference';
5818: }
5819: return (\%hash, $string);
5820: }
5821:
5822: $string =~ s/^__HASH_REF__//;
5823:
5824: while($string !~ /^__END_HASH_REF__/) {
5825: #key
5826: my $key='';
5827: if($string =~ /^__HASH_REF__/) {
5828: ($key, $string)=&str2hashref($string);
5829: if(defined($key->{'error'})) {
5830: $hash{'error'}='Bad data';
5831: return (\%hash, $string);
5832: }
5833: } elsif($string =~ /^__ARRAY_REF__/) {
5834: ($key, $string)=&str2arrayref($string);
5835: if($key->[0] eq 'Array reference error') {
5836: $hash{'error'}='Bad data';
5837: return (\%hash, $string);
5838: }
5839: } else {
5840: $string =~ s/^(.*?)=//;
1.267 albertel 5841: $key=&unescape($1);
1.265 albertel 5842: }
5843: $string =~ s/^=//;
5844:
5845: #value
5846: my $value='';
5847: if($string =~ /^__HASH_REF__/) {
5848: ($value, $string)=&str2hashref($string);
5849: if(defined($value->{'error'})) {
5850: $hash{'error'}='Bad data';
5851: return (\%hash, $string);
5852: }
5853: } elsif($string =~ /^__ARRAY_REF__/) {
5854: ($value, $string)=&str2arrayref($string);
5855: if($value->[0] eq 'Array reference error') {
5856: $hash{'error'}='Bad data';
5857: return (\%hash, $string);
5858: }
5859: } else {
5860: $value=&get_scalar(\$string,'__END_HASH_REF__');
5861: }
5862: $string =~ s/^&//;
5863:
5864: $hash{$key}=$value;
1.204 albertel 5865: }
1.265 albertel 5866:
5867: $string =~ s/^__END_HASH_REF__//;
5868:
5869: return (\%hash, $string);
1.204 albertel 5870: }
5871:
5872: sub str2array {
1.265 albertel 5873: my ($string)=@_;
5874: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5875: return @$array;
5876: }
5877:
5878: sub str2arrayref {
1.204 albertel 5879: my ($string) = @_;
1.265 albertel 5880: my @array;
5881:
5882: if($string !~ /^__ARRAY_REF__/) {
5883: if (! ($string eq '' || !defined($string))) {
5884: $array[0]='Array reference error';
5885: }
5886: return (\@array, $string);
5887: }
5888:
5889: $string =~ s/^__ARRAY_REF__//;
5890:
5891: while($string !~ /^__END_ARRAY_REF__/) {
5892: my $value='';
5893: if($string =~ /^__HASH_REF__/) {
5894: ($value, $string)=&str2hashref($string);
5895: if(defined($value->{'error'})) {
5896: $array[0] ='Array reference error';
5897: return (\@array, $string);
5898: }
5899: } elsif($string =~ /^__ARRAY_REF__/) {
5900: ($value, $string)=&str2arrayref($string);
5901: if($value->[0] eq 'Array reference error') {
5902: $array[0] ='Array reference error';
5903: return (\@array, $string);
5904: }
5905: } else {
5906: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5907: }
5908: $string =~ s/^&//;
5909:
5910: push(@array, $value);
1.191 harris41 5911: }
1.265 albertel 5912:
5913: $string =~ s/^__END_ARRAY_REF__//;
5914:
5915: return (\@array, $string);
1.168 albertel 5916: }
5917:
1.167 albertel 5918: # -------------------------------------------------------------------Temp Store
5919:
1.168 albertel 5920: sub tmpreset {
5921: my ($symb,$namespace,$domain,$stuname) = @_;
5922: if (!$symb) {
5923: $symb=&symbread();
1.620 albertel 5924: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5925: }
5926: $symb=escape($symb);
5927:
1.620 albertel 5928: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5929: $namespace=~s/\//\_/g;
5930: $namespace=~s/\W//g;
5931:
1.620 albertel 5932: if (!$domain) { $domain=$env{'user.domain'}; }
5933: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5934: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.118. .17(raeb 5935:-21): $stuname=&get_requestor_ip();
1.591 albertel 5936: }
1.1117 foxr 5937: my $path=LONCAPA::tempdir();
1.168 albertel 5938: my %hash;
5939: if (tie(%hash,'GDBM_File',
5940: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5941: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5942: foreach my $key (keys(%hash)) {
1.180 albertel 5943: if ($key=~ /:$symb/) {
1.168 albertel 5944: delete($hash{$key});
5945: }
5946: }
5947: }
5948: }
5949:
1.167 albertel 5950: sub tmpstore {
1.168 albertel 5951: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5952:
5953: if (!$symb) {
5954: $symb=&symbread();
1.620 albertel 5955: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5956: }
5957: $symb=escape($symb);
5958:
5959: if (!$namespace) {
5960: # I don't think we would ever want to store this for a course.
5961: # it seems this will only be used if we don't have a course.
1.620 albertel 5962: #$namespace=$env{'request.course.id'};
1.168 albertel 5963: #if (!$namespace) {
1.620 albertel 5964: $namespace=$env{'request.state'};
1.168 albertel 5965: #}
5966: }
5967: $namespace=~s/\//\_/g;
5968: $namespace=~s/\W//g;
1.620 albertel 5969: if (!$domain) { $domain=$env{'user.domain'}; }
5970: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5971: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.118. .17(raeb 5972:-21): $stuname=&get_requestor_ip();
1.591 albertel 5973: }
1.168 albertel 5974: my $now=time;
5975: my %hash;
1.1117 foxr 5976: my $path=LONCAPA::tempdir();
1.168 albertel 5977: if (tie(%hash,'GDBM_File',
5978: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5979: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5980: $hash{"version:$symb"}++;
5981: my $version=$hash{"version:$symb"};
5982: my $allkeys='';
5983: foreach my $key (keys(%$storehash)) {
5984: $allkeys.=$key.':';
1.591 albertel 5985: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5986: }
5987: $hash{"$version:$symb:timestamp"}=$now;
5988: $allkeys.='timestamp';
5989: $hash{"$version:keys:$symb"}=$allkeys;
5990: if (untie(%hash)) {
5991: return 'ok';
5992: } else {
5993: return "error:$!";
5994: }
5995: } else {
5996: return "error:$!";
5997: }
5998: }
1.167 albertel 5999:
1.168 albertel 6000: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6001:
1.168 albertel 6002: sub tmprestore {
6003: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6004:
1.168 albertel 6005: if (!$symb) {
6006: $symb=&symbread();
1.620 albertel 6007: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6008: }
6009: $symb=escape($symb);
6010:
1.620 albertel 6011: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6012:
1.620 albertel 6013: if (!$domain) { $domain=$env{'user.domain'}; }
6014: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6015: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.118. .17(raeb 6016:-21): $stuname=&get_requestor_ip();
1.591 albertel 6017: }
1.168 albertel 6018: my %returnhash;
6019: $namespace=~s/\//\_/g;
6020: $namespace=~s/\W//g;
6021: my %hash;
1.1117 foxr 6022: my $path=LONCAPA::tempdir();
1.168 albertel 6023: if (tie(%hash,'GDBM_File',
6024: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6025: &GDBM_READER(),0640)) {
1.168 albertel 6026: my $version=$hash{"version:$symb"};
6027: $returnhash{'version'}=$version;
6028: my $scope;
6029: for ($scope=1;$scope<=$version;$scope++) {
6030: my $vkeys=$hash{"$scope:keys:$symb"};
6031: my @keys=split(/:/,$vkeys);
6032: my $key;
6033: $returnhash{"$scope:keys"}=$vkeys;
6034: foreach $key (@keys) {
1.591 albertel 6035: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6036: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6037: }
6038: }
1.168 albertel 6039: if (!(untie(%hash))) {
6040: return "error:$!";
6041: }
6042: } else {
6043: return "error:$!";
6044: }
6045: return %returnhash;
1.167 albertel 6046: }
6047:
1.9 www 6048: # ----------------------------------------------------------------------- Store
6049:
6050: sub store {
1.1172.2.64 raeburn 6051: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6052: my $home='';
6053:
1.168 albertel 6054: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6055:
1.213 www 6056: $symb=&symbclean($symb);
1.122 albertel 6057: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6058:
1.620 albertel 6059: if (!$domain) { $domain=$env{'user.domain'}; }
6060: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6061:
6062: &devalidate($symb,$stuname,$domain);
1.109 www 6063:
6064: $symb=escape($symb);
1.187 www 6065: if (!$namespace) {
1.620 albertel 6066: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6067: return '';
6068: }
6069: }
1.620 albertel 6070: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6071:
1.1172.2.118. .17(raeb 6072:-21): $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6073: $$storehash{'host'}=$perlvar{'lonHostID'};
6074:
1.12 www 6075: my $namevalue='';
1.800 albertel 6076: foreach my $key (keys(%$storehash)) {
6077: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6078: }
1.12 www 6079: $namevalue=~s/\&$//;
1.187 www 6080: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 6081: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6082: }
6083:
1.47 www 6084: # -------------------------------------------------------------- Critical Store
6085:
6086: sub cstore {
1.1172.2.64 raeburn 6087: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6088: my $home='';
6089:
1.168 albertel 6090: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6091:
1.213 www 6092: $symb=&symbclean($symb);
1.122 albertel 6093: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6094:
1.620 albertel 6095: if (!$domain) { $domain=$env{'user.domain'}; }
6096: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6097:
6098: &devalidate($symb,$stuname,$domain);
1.109 www 6099:
6100: $symb=escape($symb);
1.187 www 6101: if (!$namespace) {
1.620 albertel 6102: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6103: return '';
6104: }
6105: }
1.620 albertel 6106: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6107:
1.1172.2.118. .17(raeb 6108:-21): $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6109: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6110:
1.47 www 6111: my $namevalue='';
1.800 albertel 6112: foreach my $key (keys(%$storehash)) {
6113: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6114: }
1.47 www 6115: $namevalue=~s/\&$//;
1.187 www 6116: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6117: return critical
1.1172.2.64 raeburn 6118: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6119: }
6120:
1.9 www 6121: # --------------------------------------------------------------------- Restore
6122:
6123: sub restore {
1.124 www 6124: my ($symb,$namespace,$domain,$stuname) = @_;
6125: my $home='';
6126:
1.168 albertel 6127: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6128:
1.122 albertel 6129: if (!$symb) {
1.1172.2.26 raeburn 6130: return if ($namespace eq 'courserequests');
6131: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6132: } else {
1.1172.2.26 raeburn 6133: unless ($namespace eq 'courserequests') {
6134: $symb=&escape(&symbclean($symb));
6135: }
1.122 albertel 6136: }
1.188 www 6137: if (!$namespace) {
1.620 albertel 6138: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6139: return '';
6140: }
6141: }
1.620 albertel 6142: if (!$domain) { $domain=$env{'user.domain'}; }
6143: if (!$stuname) { $stuname=$env{'user.name'}; }
6144: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6145: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6146:
1.12 www 6147: my %returnhash=();
1.800 albertel 6148: foreach my $line (split(/\&/,$answer)) {
6149: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6150: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6151: }
1.75 www 6152: my $version;
6153: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6154: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6155: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6156: }
1.75 www 6157: }
1.13 www 6158: return %returnhash;
1.34 www 6159: }
6160:
6161: # ---------------------------------------------------------- Course Description
1.1118 foxr 6162: #
6163: #
1.34 www 6164:
6165: sub coursedescription {
1.731 albertel 6166: my ($courseid,$args)=@_;
1.34 www 6167: $courseid=~s/^\///;
1.49 www 6168: $courseid=~s/\_/\//g;
1.34 www 6169: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6170: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6171: my $normalid=$cdomain.'_'.$cnum;
6172: # need to always cache even if we get errors otherwise we keep
6173: # trying and trying and trying to get the course description.
6174: my %envhash=();
6175: my %returnhash=();
1.731 albertel 6176:
6177: my $expiretime=600;
6178: if ($env{'request.course.id'} eq $normalid) {
6179: $expiretime=120;
6180: }
6181:
6182: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6183: if (!$args->{'freshen_cache'}
6184: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6185: foreach my $key (keys(%env)) {
6186: next if ($key !~ /^\Q$prefix\E(.*)/);
6187: my ($setting) = $1;
6188: $returnhash{$setting} = $env{$key};
6189: }
6190: return %returnhash;
6191: }
6192:
1.1118 foxr 6193: # get the data again
6194:
1.731 albertel 6195: if (!$args->{'one_time'}) {
6196: $envhash{'course.'.$normalid.'.last_cache'}=time;
6197: }
1.811 albertel 6198:
1.34 www 6199: if ($chome ne 'no_host') {
1.302 albertel 6200: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6201: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6202: my $username = $env{'user.name'}; # Defult username
6203: if(defined $args->{'user'}) {
6204: $username = $args->{'user'};
6205: }
1.129 albertel 6206: $returnhash{'home'}= $chome;
6207: $returnhash{'domain'} = $cdomain;
6208: $returnhash{'num'} = $cnum;
1.741 raeburn 6209: if (!defined($returnhash{'type'})) {
6210: $returnhash{'type'} = 'Course';
6211: }
1.130 albertel 6212: while (my ($name,$value) = each %returnhash) {
1.53 www 6213: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6214: }
1.270 www 6215: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6216: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6217: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6218: $envhash{'course.'.$normalid.'.home'}=$chome;
6219: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6220: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6221: }
6222: }
1.731 albertel 6223: if (!$args->{'one_time'}) {
1.949 raeburn 6224: &appenv(\%envhash);
1.731 albertel 6225: }
1.302 albertel 6226: return %returnhash;
1.461 www 6227: }
6228:
1.1080 raeburn 6229: sub update_released_required {
6230: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6231: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6232: $cid = $env{'request.course.id'};
6233: $cdom = $env{'course.'.$cid.'.domain'};
6234: $cnum = $env{'course.'.$cid.'.num'};
6235: $chome = $env{'course.'.$cid.'.home'};
6236: }
6237: if ($needsrelease) {
6238: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6239: my $needsupdate;
6240: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6241: $needsupdate = 1;
6242: } else {
6243: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6244: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6245: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6246: $needsupdate = 1;
6247: }
6248: }
6249: if ($needsupdate) {
6250: my %needshash = (
6251: 'internal.releaserequired' => $needsrelease,
6252: );
6253: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6254: if ($putresult eq 'ok') {
6255: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6256: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6257: if (ref($crsinfo{$cid}) eq 'HASH') {
6258: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6259: &courseidput($cdom,\%crsinfo,$chome,'notime');
6260: }
6261: }
6262: }
6263: }
6264: return;
6265: }
6266:
1.461 www 6267: # -------------------------------------------------See if a user is privileged
6268:
6269: sub privileged {
1.1172.2.23 raeburn 6270: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6271: my $now = time;
1.1172.2.23 raeburn 6272: my $roles;
6273: if (ref($possroles) eq 'ARRAY') {
6274: $roles = $possroles;
6275: } else {
6276: $roles = ['dc','su'];
6277: }
6278: if (ref($possdomains) eq 'ARRAY') {
6279: my %privileged = &privileged_by_domain($possdomains,$roles);
6280: foreach my $dom (@{$possdomains}) {
6281: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6282: (ref($privileged{$dom}) eq 'HASH')) {
6283: foreach my $role (@{$roles}) {
6284: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6285: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6286: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6287: return 1 unless (($end && $end < $now) ||
6288: ($start && $start > $now));
6289: }
6290: }
6291: }
6292: }
6293: }
6294: } else {
6295: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6296: my $now = time;
1.1170 droeschl 6297:
1.1172.2.58 raeburn 6298: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6299: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6300: if (grep(/^\Q$trole\E$/,@{$roles})) {
6301: return 1 unless ($tend && $tend < $now)
6302: or ($tstart && $tstart > $now);
1.1170 droeschl 6303: }
1.1172.2.23 raeburn 6304: }
6305: }
1.461 www 6306: return 0;
1.9 www 6307: }
1.1 albertel 6308:
1.1172.2.23 raeburn 6309: sub privileged_by_domain {
6310: my ($domains,$roles) = @_;
6311: my %privileged = ();
6312: my $cachetime = 60*60*24;
6313: my $now = time;
6314: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6315: return %privileged;
6316: }
6317: foreach my $dom (@{$domains}) {
6318: next if (ref($privileged{$dom}) eq 'HASH');
6319: my $needroles;
6320: foreach my $role (@{$roles}) {
6321: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6322: if (defined($cached)) {
6323: if (ref($result) eq 'HASH') {
6324: $privileged{$dom}{$role} = $result;
6325: }
6326: } else {
6327: $needroles = 1;
6328: }
6329: }
6330: if ($needroles) {
6331: my %dompersonnel = &get_domain_roles($dom,$roles);
6332: $privileged{$dom} = {};
6333: foreach my $server (keys(%dompersonnel)) {
6334: if (ref($dompersonnel{$server}) eq 'HASH') {
6335: foreach my $item (keys(%{$dompersonnel{$server}})) {
6336: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6337: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6338: next if ($end && $end < $now);
6339: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6340: $dompersonnel{$server}{$item};
6341: }
6342: }
6343: }
6344: if (ref($privileged{$dom}) eq 'HASH') {
6345: foreach my $role (@{$roles}) {
6346: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6347: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6348: } else {
6349: my %hash = ();
6350: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6351: }
6352: }
6353: }
6354: }
6355: }
6356: return %privileged;
6357: }
6358:
1.103 harris41 6359: # -------------------------------------------------------- Get user privileges
1.11 www 6360:
6361: sub rolesinit {
1.1169 droeschl 6362: my ($domain, $username) = @_;
6363: my %userroles = ('user.login.time' => time);
6364: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6365:
6366: # firstaccess and timerinterval are related to timed maps/resources.
6367: # also, blocking can be triggered by an activating timer
6368: # it's saved in the user's %env.
6369: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6370: my %timerinterval = &dump('timerinterval', $domain, $username);
6371: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6372: %timerintchk, %timerintenv);
6373:
1.1162 raeburn 6374: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6375: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6376: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6377: }
1.1169 droeschl 6378:
1.1162 raeburn 6379: foreach my $key (keys(%timerinterval)) {
6380: my ($cid,$rest) = split(/\0/,$key);
6381: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6382: }
1.1169 droeschl 6383:
1.11 www 6384: my %allroles=();
1.1162 raeburn 6385: my %allgroups=();
1.11 www 6386:
1.1172.2.58 raeburn 6387: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6388: my $role = $rolesdump{$area};
6389: $area =~ s/\_\w\w$//;
6390:
6391: my ($trole, $tend, $tstart, $group_privs);
6392:
6393: if ($role =~ /^cr/) {
6394: # Custom role, defined by a user
6395: # e.g., user.role.cr/msu/smith/mynewrole
6396: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6397: $trole = $1;
6398: ($tend, $tstart) = split('_', $2);
6399: } else {
6400: $trole = $role;
6401: }
6402: } elsif ($role =~ m|^gr/|) {
6403: # Role of member in a group, defined within a course/community
6404: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6405: ($trole, $tend, $tstart) = split(/_/, $role);
6406: next if $tstart eq '-1';
6407: ($trole, $group_privs) = split(/\//, $trole);
6408: $group_privs = &unescape($group_privs);
6409: } else {
6410: # Just a normal role, defined in roles.tab
6411: ($trole, $tend, $tstart) = split(/_/,$role);
6412: }
6413:
6414: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6415: $username);
6416: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6417:
6418: # role expired or not available yet?
6419: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6420: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6421:
6422: next if $area eq '' or $trole eq '';
6423:
6424: my $spec = "$trole.$area";
6425: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6426:
6427: if ($trole =~ /^cr\//) {
6428: # Custom role, defined by a user
6429: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6430: } elsif ($trole eq 'gr') {
6431: # Role of a member in a group, defined within a course/community
6432: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6433: next;
6434: } else {
6435: # Normal role, defined in roles.tab
6436: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6437: }
6438:
6439: my $cid = $tdomain.'_'.$trest;
6440: unless ($firstaccchk{$cid}) {
6441: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6442: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6443: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6444: $coursetimerstarts{$cid}{$item};
6445: }
6446: }
6447: $firstaccchk{$cid} = 1;
6448: }
6449: unless ($timerintchk{$cid}) {
6450: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6451: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6452: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6453: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6454: }
1.12 www 6455: }
1.1169 droeschl 6456: $timerintchk{$cid} = 1;
1.191 harris41 6457: }
1.11 www 6458: }
1.1169 droeschl 6459:
1.1172.2.91 raeburn 6460: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6461: \%allroles, \%allgroups);
1.1169 droeschl 6462: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6463: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6464:
1.1162 raeburn 6465: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6466: }
6467:
1.567 raeburn 6468: sub set_arearole {
1.1172.2.19 raeburn 6469: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6470: unless ($nolog) {
1.567 raeburn 6471: # log the associated role with the area
1.1172.2.19 raeburn 6472: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6473: }
1.743 albertel 6474: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6475: }
6476:
6477: sub custom_roleprivs {
6478: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6479: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6480: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6481: if (&hostname($homsvr) ne '') {
1.567 raeburn 6482: my ($rdummy,$roledef)=
6483: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6484: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6485: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6486: if (defined($syspriv)) {
1.1043 raeburn 6487: if ($trest =~ /^$match_community$/) {
6488: $syspriv =~ s/bre\&S//;
6489: }
1.567 raeburn 6490: $$allroles{'cm./'}.=':'.$syspriv;
6491: $$allroles{$spec.'./'}.=':'.$syspriv;
6492: }
6493: if ($tdomain ne '') {
6494: if (defined($dompriv)) {
6495: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6496: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6497: }
6498: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6499: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6500: my $rolename = $1;
6501: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6502: }
1.567 raeburn 6503: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6504: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6505: }
6506: }
6507: }
6508: }
6509: }
6510:
1.1172.2.89 raeburn 6511: sub course_adhocrole_privs {
6512: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6513: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6514: if ($overrides{"internal.adhocpriv.$rolename"}) {
6515: my (%currprivs,%storeprivs);
6516: foreach my $item (split(/:/,$coursepriv)) {
6517: my ($priv,$restrict) = split(/\&/,$item);
6518: $currprivs{$priv} = $restrict;
6519: }
6520: my (%possadd,%possremove,%full);
6521: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6522: my ($priv,$restrict)=split(/\&/,$item);
6523: $full{$priv} = $restrict;
6524: }
6525: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6526: next if ($item eq '');
6527: my ($rule,$rest) = split(/=/,$item);
6528: next unless (($rule eq 'off') || ($rule eq 'on'));
6529: foreach my $priv (split(/:/,$rest)) {
6530: if ($priv ne '') {
6531: if ($rule eq 'off') {
6532: $possremove{$priv} = 1;
6533: } else {
6534: $possadd{$priv} = 1;
6535: }
6536: }
6537: }
6538: }
6539: foreach my $priv (sort(keys(%full))) {
6540: if (exists($currprivs{$priv})) {
6541: unless (exists($possremove{$priv})) {
6542: $storeprivs{$priv} = $currprivs{$priv};
6543: }
6544: } elsif (exists($possadd{$priv})) {
6545: $storeprivs{$priv} = $full{$priv};
6546: }
6547: }
6548: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6549: }
6550: return $coursepriv;
6551: }
6552:
1.678 raeburn 6553: sub group_roleprivs {
6554: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6555: my $access = 1;
6556: my $now = time;
6557: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6558: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6559: if ($access) {
1.811 albertel 6560: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6561: $$allgroups{$course}{$group} .=':'.$group_privs;
6562: }
6563: }
1.567 raeburn 6564:
6565: sub standard_roleprivs {
6566: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6567: if (defined($pr{$trole.':s'})) {
6568: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6569: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6570: }
6571: if ($tdomain ne '') {
6572: if (defined($pr{$trole.':d'})) {
6573: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6574: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6575: }
6576: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6577: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6578: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6579: }
6580: }
6581: }
6582:
6583: sub set_userprivs {
1.1064 raeburn 6584: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6585: my $author=0;
6586: my $adv=0;
1.1172.2.91 raeburn 6587: my $rar=0;
1.678 raeburn 6588: my %grouproles = ();
6589: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6590: my @groupkeys;
1.1000 raeburn 6591: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6592: push(@groupkeys,$role);
6593: }
6594: if (ref($groups_roles) eq 'HASH') {
6595: foreach my $key (keys(%{$groups_roles})) {
6596: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6597: push(@groupkeys,$key);
6598: }
6599: }
6600: }
6601: if (@groupkeys > 0) {
6602: foreach my $role (@groupkeys) {
6603: my ($trole,$area,$sec,$extendedarea);
6604: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6605: $trole = $1;
6606: $area = $2;
6607: $sec = $3;
6608: $extendedarea = $area.$sec;
6609: if (exists($$allgroups{$area})) {
6610: foreach my $group (keys(%{$$allgroups{$area}})) {
6611: my $spec = $trole.'.'.$extendedarea;
6612: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6613: $$allgroups{$area}{$group};
1.1064 raeburn 6614: }
1.678 raeburn 6615: }
6616: }
6617: }
6618: }
6619: }
1.800 albertel 6620: foreach my $group (keys(%grouproles)) {
6621: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6622: }
1.800 albertel 6623: foreach my $role (keys(%{$allroles})) {
6624: my %thesepriv;
1.941 raeburn 6625: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6626: foreach my $item (split(/:/,$$allroles{$role})) {
6627: if ($item ne '') {
6628: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6629: if ($restrictions eq '') {
6630: $thesepriv{$privilege}='F';
6631: } elsif ($thesepriv{$privilege} ne 'F') {
6632: $thesepriv{$privilege}.=$restrictions;
6633: }
6634: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6635: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6636: }
6637: }
6638: my $thesestr='';
1.1104 raeburn 6639: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6640: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6641: }
6642: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6643: }
1.1172.2.91 raeburn 6644: return ($author,$adv,$rar);
1.567 raeburn 6645: }
6646:
1.994 raeburn 6647: sub role_status {
1.1104 raeburn 6648: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6649: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6650: my ($one,$two) = split(m{\./},$rolekey,2);
6651: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6652: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6653: $$where = '/'.$two;
1.994 raeburn 6654: $$trolecode=$$role.'.'.$$where;
6655: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6656: $$tstatus='is';
1.1104 raeburn 6657: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6658: $$tstatus='future';
1.1034 raeburn 6659: if ($$tstart<$now) {
6660: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6661: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6662: my (%allroles,%allgroups,$group_privs,
6663: %groups_roles,@rolecodes);
1.1002 raeburn 6664: my %userroles = (
6665: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6666: );
1.1064 raeburn 6667: @rolecodes = ('cm');
1.1002 raeburn 6668: my $spec=$$role.'.'.$$where;
6669: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6670: if ($$role =~ /^cr\//) {
6671: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6672: push(@rolecodes,'cr');
1.1002 raeburn 6673: } elsif ($$role eq 'gr') {
1.1064 raeburn 6674: push(@rolecodes,$$role);
1.1002 raeburn 6675: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6676: $env{'user.name'});
1.1064 raeburn 6677: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6678: (undef,my $group_privs) = split(/\//,$trole);
6679: $group_privs = &unescape($group_privs);
6680: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6681: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104 raeburn 6682: &get_groups_roles($tdomain,$trest,
6683: \%course_roles,\@rolecodes,
6684: \%groups_roles);
1.1002 raeburn 6685: } else {
1.1064 raeburn 6686: push(@rolecodes,$$role);
1.1002 raeburn 6687: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6688: }
1.1172.2.91 raeburn 6689: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6690: \%groups_roles);
1.1064 raeburn 6691: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6692: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6693: }
6694: }
1.1034 raeburn 6695: $$tstatus = 'is';
1.1002 raeburn 6696: }
1.994 raeburn 6697: }
6698: if ($$tend) {
1.1104 raeburn 6699: if ($$tend<$update) {
1.994 raeburn 6700: $$tstatus='expired';
6701: } elsif ($$tend<$now) {
6702: $$tstatus='will_not';
6703: }
6704: }
6705: }
6706: }
6707: }
6708:
1.1104 raeburn 6709: sub get_groups_roles {
6710: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6711: return unless((ref($cdom_courseroles) eq 'HASH') &&
6712: (ref($rolecodes) eq 'ARRAY') &&
6713: (ref($groups_roles) eq 'HASH'));
6714: if (keys(%{$cdom_courseroles}) > 0) {
6715: my ($cnum) = ($rest =~ /^($match_courseid)/);
6716: if ($cdom ne '' && $cnum ne '') {
6717: foreach my $key (keys(%{$cdom_courseroles})) {
6718: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6719: my $crsrole = $1;
6720: my $crssec = $2;
6721: if ($crsrole =~ /^cr/) {
6722: unless (grep(/^cr$/,@{$rolecodes})) {
6723: push(@{$rolecodes},'cr');
6724: }
6725: } else {
6726: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6727: push(@{$rolecodes},$crsrole);
6728: }
6729: }
6730: my $rolekey = "$crsrole./$cdom/$cnum";
6731: if ($crssec ne '') {
6732: $rolekey .= "/$crssec";
6733: }
6734: $rolekey .= './';
6735: $groups_roles->{$rolekey} = $rolecodes;
6736: }
6737: }
6738: }
6739: }
6740: return;
6741: }
6742:
6743: sub delete_env_groupprivs {
6744: my ($where,$courseroles,$possroles) = @_;
6745: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6746: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6747: unless (ref($courseroles->{$udom}) eq 'HASH') {
6748: %{$courseroles->{$udom}} =
6749: &get_my_roles('','','userroles',['active'],
6750: $possroles,[$udom],1);
6751: }
6752: if (ref($courseroles->{$udom}) eq 'HASH') {
6753: foreach my $item (keys(%{$courseroles->{$udom}})) {
6754: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6755: my $area = '/'.$cdom.'/'.$cnum;
6756: my $privkey = "user.priv.$crsrole.$area";
6757: if ($crssec ne '') {
6758: $privkey .= '/'.$crssec;
6759: }
6760: $privkey .= ".$area/$group";
6761: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6762: }
6763: }
6764: return;
6765: }
6766:
1.994 raeburn 6767: sub check_adhoc_privs {
1.1172.2.86 raeburn 6768: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6769: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6770: if ($sec) {
6771: $cckey .= '/'.$sec;
6772: }
1.1172.2.9 raeburn 6773: my $setprivs;
1.994 raeburn 6774: if ($env{$cckey}) {
6775: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6776: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6777: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6778: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6779: $setprivs = 1;
1.994 raeburn 6780: }
6781: } else {
1.1172.2.87 raeburn 6782: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6783: $setprivs = 1;
1.994 raeburn 6784: }
1.1172.2.9 raeburn 6785: return $setprivs;
1.994 raeburn 6786: }
6787:
6788: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6789: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6790: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6791: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6792: if ($sec ne '') {
6793: $area .= '/'.$sec;
6794: }
1.994 raeburn 6795: my $spec = $role.'.'.$area;
6796: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6797: $env{'user.name'},1);
1.1172.2.84 raeburn 6798: my %rolehash = ();
1.1172.2.89 raeburn 6799: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6800: my $rolename = $1;
1.1172.2.84 raeburn 6801: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6802: my %domdef = &get_domain_defaults($dcdom);
6803: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6804: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6805: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6806: }
6807: }
1.1172.2.84 raeburn 6808: } else {
6809: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6810: }
1.1172.2.91 raeburn 6811: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6812: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6813: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6814: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6815: &appenv( {'request.role' => $spec,
6816: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6817: 'request.course.sec' => $sec,
1.1088 raeburn 6818: }
6819: );
6820: my $tadv=0;
6821: if (&allowed('adv') eq 'F') { $tadv=1; }
6822: &appenv({'request.role.adv' => $tadv});
6823: }
1.994 raeburn 6824: }
6825:
1.12 www 6826: # --------------------------------------------------------------- get interface
6827:
6828: sub get {
1.131 albertel 6829: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6830: my $items='';
1.800 albertel 6831: foreach my $item (@$storearr) {
6832: $items.=&escape($item).'&';
1.191 harris41 6833: }
1.12 www 6834: $items=~s/\&$//;
1.620 albertel 6835: if (!$udomain) { $udomain=$env{'user.domain'}; }
6836: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6837: my $uhome=&homeserver($uname,$udomain);
6838:
1.133 albertel 6839: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6840: my @pairs=split(/\&/,$rep);
1.273 albertel 6841: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6842: return @pairs;
6843: }
1.15 www 6844: my %returnhash=();
1.42 www 6845: my $i=0;
1.800 albertel 6846: foreach my $item (@$storearr) {
6847: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6848: $i++;
1.191 harris41 6849: }
1.15 www 6850: return %returnhash;
1.27 www 6851: }
6852:
6853: # --------------------------------------------------------------- del interface
6854:
6855: sub del {
1.133 albertel 6856: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6857: my $items='';
1.800 albertel 6858: foreach my $item (@$storearr) {
6859: $items.=&escape($item).'&';
1.191 harris41 6860: }
1.984 neumanie 6861:
1.27 www 6862: $items=~s/\&$//;
1.620 albertel 6863: if (!$udomain) { $udomain=$env{'user.domain'}; }
6864: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6865: my $uhome=&homeserver($uname,$udomain);
6866: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6867: }
6868:
6869: # -------------------------------------------------------------- dump interface
6870:
1.1172.2.22 raeburn 6871: sub unserialize {
6872: my ($rep, $escapedkeys) = @_;
6873:
6874: return {} if $rep =~ /^error/;
6875:
6876: my %returnhash=();
6877: foreach my $item (split(/\&/,$rep)) {
6878: my ($key, $value) = split(/=/, $item, 2);
6879: $key = unescape($key) unless $escapedkeys;
6880: next if $key =~ /^error: 2 /;
6881: $returnhash{$key} = &thaw_unescape($value);
6882: }
6883: return \%returnhash;
6884: }
6885:
6886: # see Lond::dump_with_regexp
6887: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6888: sub dump {
1.1172.2.22 raeburn 6889: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6890: if (!$udomain) { $udomain=$env{'user.domain'}; }
6891: if (!$uname) { $uname=$env{'user.name'}; }
6892: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6893:
1.1172.2.55 raeburn 6894: if ($regexp) {
6895: $regexp=&escape($regexp);
6896: } else {
6897: $regexp='.';
6898: }
1.1172.2.22 raeburn 6899: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6900: # user is hosted on this machine
1.1172.2.55 raeburn 6901: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6902: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6903: return %{&unserialize($reply, $escapedkeys)};
6904: }
1.1166 raeburn 6905: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6906: my @pairs=split(/\&/,$rep);
6907: my %returnhash=();
1.1098 foxr 6908: if (!($rep =~ /^error/ )) {
6909: foreach my $item (@pairs) {
6910: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6911: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6912: next if ($key =~ /^error: 2 /);
6913: $returnhash{$key}=&thaw_unescape($value);
6914: }
1.755 albertel 6915: }
6916: return %returnhash;
1.407 www 6917: }
6918:
1.1098 foxr 6919:
1.717 albertel 6920: # --------------------------------------------------------- dumpstore interface
6921:
6922: sub dumpstore {
6923: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6924: # same as dump but keys must be escaped. They may contain colon separated
6925: # lists of values that may themself contain colons (e.g. symbs).
6926: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6927: }
6928:
1.407 www 6929: # -------------------------------------------------------------- keys interface
6930:
6931: sub getkeys {
6932: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6933: if (!$udomain) { $udomain=$env{'user.domain'}; }
6934: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6935: my $uhome=&homeserver($uname,$udomain);
6936: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6937: my @keyarray=();
1.800 albertel 6938: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6939: next if ($key =~ /^error: 2 /);
1.800 albertel 6940: push(@keyarray,&unescape($key));
1.407 www 6941: }
6942: return @keyarray;
1.318 matthew 6943: }
6944:
1.319 matthew 6945: # --------------------------------------------------------------- currentdump
6946: sub currentdump {
1.328 matthew 6947: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6948: $courseid = $env{'request.course.id'} if (! defined($courseid));
6949: $sdom = $env{'user.domain'} if (! defined($sdom));
6950: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6951: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6952: my $rep;
6953:
6954: if (grep { $_ eq $uhome } current_machine_ids()) {
6955: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6956: $courseid)));
6957: } else {
6958: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6959: }
6960:
1.318 matthew 6961: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6962: #
1.318 matthew 6963: my %returnhash=();
1.319 matthew 6964: #
1.1172.2.118. .1(raebu 6965:20): if ($rep eq 'unknown_cmd') {
1.319 matthew 6966: # an old lond will not know currentdump
6967: # Do a dump and make it look like a currentdump
1.822 albertel 6968: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6969: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6970: my %hash = @tmp;
6971: @tmp=();
1.424 matthew 6972: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6973: } else {
6974: my @pairs=split(/\&/,$rep);
1.800 albertel 6975: foreach my $pair (@pairs) {
6976: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6977: my ($symb,$param) = split(/:/,$key);
6978: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6979: &thaw_unescape($value);
1.319 matthew 6980: }
1.191 harris41 6981: }
1.12 www 6982: return %returnhash;
1.424 matthew 6983: }
6984:
6985: sub convert_dump_to_currentdump{
6986: my %hash = %{shift()};
6987: my %returnhash;
6988: # Code ripped from lond, essentially. The only difference
6989: # here is the unescaping done by lonnet::dump(). Conceivably
6990: # we might run in to problems with parameter names =~ /^v\./
6991: while (my ($key,$value) = each(%hash)) {
6992: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6993: $symb = &unescape($symb);
6994: $param = &unescape($param);
1.424 matthew 6995: next if ($v eq 'version' || $symb eq 'keys');
6996: next if (exists($returnhash{$symb}) &&
6997: exists($returnhash{$symb}->{$param}) &&
6998: $returnhash{$symb}->{'v.'.$param} > $v);
6999: $returnhash{$symb}->{$param}=$value;
7000: $returnhash{$symb}->{'v.'.$param}=$v;
7001: }
7002: #
7003: # Remove all of the keys in the hashes which keep track of
7004: # the version of the parameter.
7005: while (my ($symb,$param_hash) = each(%returnhash)) {
7006: # use a foreach because we are going to delete from the hash.
7007: foreach my $key (keys(%$param_hash)) {
7008: delete($param_hash->{$key}) if ($key =~ /^v\./);
7009: }
7010: }
7011: return \%returnhash;
1.12 www 7012: }
7013:
1.627 albertel 7014: # ------------------------------------------------------ critical inc interface
7015:
7016: sub cinc {
7017: return &inc(@_,'critical');
7018: }
7019:
1.449 matthew 7020: # --------------------------------------------------------------- inc interface
7021:
7022: sub inc {
1.627 albertel 7023: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7024: if (!$udomain) { $udomain=$env{'user.domain'}; }
7025: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7026: my $uhome=&homeserver($uname,$udomain);
7027: my $items='';
7028: if (! ref($store)) {
7029: # got a single value, so use that instead
7030: $items = &escape($store).'=&';
7031: } elsif (ref($store) eq 'SCALAR') {
7032: $items = &escape($$store).'=&';
7033: } elsif (ref($store) eq 'ARRAY') {
7034: $items = join('=&',map {&escape($_);} @{$store});
7035: } elsif (ref($store) eq 'HASH') {
7036: while (my($key,$value) = each(%{$store})) {
7037: $items.= &escape($key).'='.&escape($value).'&';
7038: }
7039: }
7040: $items=~s/\&$//;
1.627 albertel 7041: if ($critical) {
7042: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7043: } else {
7044: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7045: }
1.449 matthew 7046: }
7047:
1.12 www 7048: # --------------------------------------------------------------- put interface
7049:
7050: sub put {
1.134 albertel 7051: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7052: if (!$udomain) { $udomain=$env{'user.domain'}; }
7053: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7054: my $uhome=&homeserver($uname,$udomain);
1.12 www 7055: my $items='';
1.800 albertel 7056: foreach my $item (keys(%$storehash)) {
7057: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7058: }
1.12 www 7059: $items=~s/\&$//;
1.134 albertel 7060: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7061: }
7062:
1.631 albertel 7063: # ------------------------------------------------------------ newput interface
7064:
7065: sub newput {
7066: my ($namespace,$storehash,$udomain,$uname)=@_;
7067: if (!$udomain) { $udomain=$env{'user.domain'}; }
7068: if (!$uname) { $uname=$env{'user.name'}; }
7069: my $uhome=&homeserver($uname,$udomain);
7070: my $items='';
7071: foreach my $key (keys(%$storehash)) {
7072: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7073: }
7074: $items=~s/\&$//;
7075: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7076: }
7077:
7078: # --------------------------------------------------------- putstore interface
7079:
1.524 raeburn 7080: sub putstore {
1.1172.2.59 raeburn 7081: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7082: if (!$udomain) { $udomain=$env{'user.domain'}; }
7083: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7084: my $uhome=&homeserver($uname,$udomain);
7085: my $items='';
1.715 albertel 7086: foreach my $key (keys(%$storehash)) {
7087: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7088: }
1.715 albertel 7089: $items=~s/\&$//;
1.716 albertel 7090: my $esc_symb=&escape($symb);
7091: my $esc_v=&escape($version);
1.715 albertel 7092: my $reply =
1.716 albertel 7093: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7094: $uhome);
1.1172.2.59 raeburn 7095: if (($tolog) && ($reply eq 'ok')) {
7096: my $namevalue='';
7097: foreach my $key (keys(%{$storehash})) {
7098: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7099: }
1.1172.2.118. .14(raeb 7100:-21): my $ip = &get_requestor_ip();
7101:-21): $namevalue .= 'ip='.&escape($ip).
1.1172.2.59 raeburn 7102: '&host='.&escape($perlvar{'lonHostID'}).
7103: '&version='.$esc_v.
7104: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7105: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7106: }
1.715 albertel 7107: if ($reply eq 'unknown_cmd') {
1.716 albertel 7108: # gfall back to way things use to be done
1.715 albertel 7109: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7110: $uname);
1.524 raeburn 7111: }
1.715 albertel 7112: return $reply;
7113: }
7114:
7115: sub old_putstore {
1.716 albertel 7116: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7117: if (!$udomain) { $udomain=$env{'user.domain'}; }
7118: if (!$uname) { $uname=$env{'user.name'}; }
7119: my $uhome=&homeserver($uname,$udomain);
7120: my %newstorehash;
1.800 albertel 7121: foreach my $item (keys(%$storehash)) {
7122: my $key = $version.':'.&escape($symb).':'.$item;
7123: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7124: }
7125: my $items='';
7126: my %allitems = ();
1.800 albertel 7127: foreach my $item (keys(%newstorehash)) {
7128: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7129: my $key = $1.':keys:'.$2;
7130: $allitems{$key} .= $3.':';
7131: }
1.800 albertel 7132: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7133: }
1.800 albertel 7134: foreach my $item (keys(%allitems)) {
7135: $allitems{$item} =~ s/\:$//;
7136: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7137: }
7138: $items=~s/\&$//;
7139: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7140: }
7141:
1.47 www 7142: # ------------------------------------------------------ critical put interface
7143:
7144: sub cput {
1.134 albertel 7145: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7146: if (!$udomain) { $udomain=$env{'user.domain'}; }
7147: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7148: my $uhome=&homeserver($uname,$udomain);
1.47 www 7149: my $items='';
1.800 albertel 7150: foreach my $item (keys(%$storehash)) {
7151: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7152: }
1.47 www 7153: $items=~s/\&$//;
1.134 albertel 7154: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7155: }
7156:
7157: # -------------------------------------------------------------- eget interface
7158:
7159: sub eget {
1.133 albertel 7160: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7161: my $items='';
1.800 albertel 7162: foreach my $item (@$storearr) {
7163: $items.=&escape($item).'&';
1.191 harris41 7164: }
1.12 www 7165: $items=~s/\&$//;
1.620 albertel 7166: if (!$udomain) { $udomain=$env{'user.domain'}; }
7167: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7168: my $uhome=&homeserver($uname,$udomain);
7169: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7170: my @pairs=split(/\&/,$rep);
7171: my %returnhash=();
1.42 www 7172: my $i=0;
1.800 albertel 7173: foreach my $item (@$storearr) {
7174: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7175: $i++;
1.191 harris41 7176: }
1.12 www 7177: return %returnhash;
7178: }
7179:
1.667 albertel 7180: # ------------------------------------------------------------ tmpput interface
7181: sub tmpput {
1.802 raeburn 7182: my ($storehash,$server,$context)=@_;
1.667 albertel 7183: my $items='';
1.800 albertel 7184: foreach my $item (keys(%$storehash)) {
7185: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7186: }
7187: $items=~s/\&$//;
1.802 raeburn 7188: if (defined($context)) {
7189: $items .= ':'.&escape($context);
7190: }
1.667 albertel 7191: return &reply("tmpput:$items",$server);
7192: }
7193:
7194: # ------------------------------------------------------------ tmpget interface
7195: sub tmpget {
1.688 albertel 7196: my ($token,$server)=@_;
7197: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7198: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7199: my %returnhash;
1.1172.2.85 raeburn 7200: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7201: return %returnhash;
7202: }
1.667 albertel 7203: foreach my $item (split(/\&/,$rep)) {
7204: my ($key,$value)=split(/=/,$item);
7205: $returnhash{&unescape($key)}=&thaw_unescape($value);
7206: }
7207: return %returnhash;
7208: }
7209:
1.1113 raeburn 7210: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7211: sub tmpdel {
7212: my ($token,$server)=@_;
7213: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7214: return &reply("tmpdel:$token",$server);
7215: }
7216:
1.1172.2.13 raeburn 7217: # ------------------------------------------------------------ get_timebased_id
7218:
7219: sub get_timebased_id {
7220: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7221: $maxtries) = @_;
7222: my ($newid,$error,$dellock);
7223: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7224: return ('','ok','invalid call to get suffix');
7225: }
7226:
7227: # set defaults for any optional args for which values were not supplied
7228: if ($who eq '') {
7229: $who = $env{'user.name'}.':'.$env{'user.domain'};
7230: }
7231: if (!$locktries) {
7232: $locktries = 3;
7233: }
7234: if (!$maxtries) {
7235: $maxtries = 10;
7236: }
7237:
7238: if (($cdom eq '') || ($cnum eq '')) {
7239: if ($env{'request.course.id'}) {
7240: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7241: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7242: }
7243: if (($cdom eq '') || ($cnum eq '')) {
7244: return ('','ok','call to get suffix not in course context');
7245: }
7246: }
7247:
7248: # construct locking item
7249: my $lockhash = {
7250: $prefix."\0".'locked_'.$keyid => $who,
7251: };
7252: my $tries = 0;
7253:
7254: # attempt to get lock on nohist_$namespace file
7255: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7256: while (($gotlock ne 'ok') && $tries <$locktries) {
7257: $tries ++;
7258: sleep 1;
7259: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7260: }
7261:
7262: # attempt to get unique identifier, based on current timestamp
7263: if ($gotlock eq 'ok') {
7264: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7265: my $id = time;
7266: $newid = $id;
1.1172.2.56 raeburn 7267: if ($idtype eq 'addcode') {
7268: $newid .= &sixnum_code();
7269: }
1.1172.2.13 raeburn 7270: my $idtries = 0;
7271: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7272: if ($idtype eq 'concat') {
7273: $newid = $id.$idtries;
1.1172.2.56 raeburn 7274: } elsif ($idtype eq 'addcode') {
7275: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7276: } else {
7277: $newid ++;
7278: }
7279: $idtries ++;
7280: }
7281: if (!exists($inuse{$prefix."\0".$newid})) {
7282: my %new_item = (
7283: $prefix."\0".$newid => $who,
7284: );
7285: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7286: $cdom,$cnum);
7287: if ($putresult ne 'ok') {
7288: undef($newid);
7289: $error = 'error saving new item: '.$putresult;
7290: }
7291: } else {
1.1172.2.56 raeburn 7292: undef($newid);
1.1172.2.13 raeburn 7293: $error = ('error: no unique suffix available for the new item ');
7294: }
7295: # remove lock
7296: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7297: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7298: } else {
7299: $error = "error: could not obtain lockfile\n";
7300: $dellock = 'ok';
1.1172.2.58 raeburn 7301: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7302: $dellock = 'nolock';
7303: }
1.1172.2.13 raeburn 7304: }
7305: return ($newid,$dellock,$error);
7306: }
7307:
1.1172.2.56 raeburn 7308: sub sixnum_code {
7309: my $code;
7310: for (0..6) {
7311: $code .= int( rand(9) );
7312: }
7313: return $code;
7314: }
7315:
1.765 albertel 7316: # -------------------------------------------------- portfolio access checking
7317:
7318: sub portfolio_access {
1.1172.2.77 raeburn 7319: my ($requrl,$clientip) = @_;
1.765 albertel 7320: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7321: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7322: if ($result) {
7323: my %setters;
7324: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7325: my ($startblock,$endblock) =
7326: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7327: if ($startblock && $endblock) {
7328: return 'B';
7329: }
7330: } else {
7331: my ($startblock,$endblock) =
7332: &Apache::loncommon::blockcheck(\%setters,'port');
7333: if ($startblock && $endblock) {
7334: return 'B';
7335: }
7336: }
7337: }
1.765 albertel 7338: if ($result eq 'ok') {
1.766 albertel 7339: return 'F';
1.765 albertel 7340: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7341: return 'A';
1.765 albertel 7342: }
1.766 albertel 7343: return '';
1.765 albertel 7344: }
7345:
7346: sub get_portfolio_access {
1.1172.2.77 raeburn 7347: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7348:
7349: if (!ref($access_hash)) {
7350: my $current_perms = &get_portfile_permissions($udom,$unum);
7351: my %access_controls = &get_access_controls($current_perms,$group,
7352: $file_name);
7353: $access_hash = $access_controls{$file_name};
7354: }
7355:
1.1172.2.77 raeburn 7356: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7357: my $now = time;
7358: if (ref($access_hash) eq 'HASH') {
7359: foreach my $key (keys(%{$access_hash})) {
7360: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7361: if ($start > $now) {
7362: next;
7363: }
7364: if ($end && $end<$now) {
7365: next;
7366: }
7367: if ($scope eq 'public') {
7368: $public = $key;
7369: last;
7370: } elsif ($scope eq 'guest') {
7371: $guest = $key;
7372: } elsif ($scope eq 'domains') {
7373: push(@domains,$key);
7374: } elsif ($scope eq 'users') {
7375: push(@users,$key);
7376: } elsif ($scope eq 'course') {
7377: push(@courses,$key);
7378: } elsif ($scope eq 'group') {
7379: push(@groups,$key);
1.1172.2.77 raeburn 7380: } elsif ($scope eq 'ip') {
7381: push(@ips,$key);
1.765 albertel 7382: }
7383: }
7384: if ($public) {
7385: return 'ok';
1.1172.2.77 raeburn 7386: } elsif (@ips > 0) {
7387: my $allowed;
7388: foreach my $ipkey (@ips) {
7389: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7390: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7391: $allowed = 1;
7392: last;
7393: }
7394: }
7395: }
7396: if ($allowed) {
7397: return 'ok';
7398: }
1.765 albertel 7399: }
7400: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7401: if ($guest) {
7402: return $guest;
7403: }
7404: } else {
7405: if (@domains > 0) {
7406: foreach my $domkey (@domains) {
7407: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7408: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7409: return 'ok';
7410: }
7411: }
7412: }
7413: }
7414: if (@users > 0) {
7415: foreach my $userkey (@users) {
1.865 raeburn 7416: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7417: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7418: if (ref($item) eq 'HASH') {
7419: if (($item->{'uname'} eq $env{'user.name'}) &&
7420: ($item->{'udom'} eq $env{'user.domain'})) {
7421: return 'ok';
7422: }
7423: }
7424: }
7425: }
1.765 albertel 7426: }
7427: }
7428: my %roleshash;
7429: my @courses_and_groups = @courses;
7430: push(@courses_and_groups,@groups);
7431: if (@courses_and_groups > 0) {
7432: my (%allgroups,%allroles);
7433: my ($start,$end,$role,$sec,$group);
7434: foreach my $envkey (%env) {
1.1060 raeburn 7435: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7436: my $cid = $2.'_'.$3;
7437: if ($1 eq 'gr') {
7438: $group = $4;
7439: $allgroups{$cid}{$group} = $env{$envkey};
7440: } else {
7441: if ($4 eq '') {
7442: $sec = 'none';
7443: } else {
7444: $sec = $4;
7445: }
7446: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7447: }
1.811 albertel 7448: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7449: my $cid = $2.'_'.$3;
7450: if ($4 eq '') {
7451: $sec = 'none';
7452: } else {
7453: $sec = $4;
7454: }
7455: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7456: }
7457: }
7458: if (keys(%allroles) == 0) {
7459: return;
7460: }
7461: foreach my $key (@courses_and_groups) {
7462: my %content = %{$$access_hash{$key}};
7463: my $cnum = $content{'number'};
7464: my $cdom = $content{'domain'};
7465: my $cid = $cdom.'_'.$cnum;
7466: if (!exists($allroles{$cid})) {
7467: next;
7468: }
7469: foreach my $role_id (keys(%{$content{'roles'}})) {
7470: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7471: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7472: my @status = @{$content{'roles'}{$role_id}{'access'}};
7473: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7474: foreach my $role (keys(%{$allroles{$cid}})) {
7475: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7476: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7477: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7478: if (grep/^all$/,@sections) {
7479: return 'ok';
7480: } else {
7481: if (grep/^$sec$/,@sections) {
7482: return 'ok';
7483: }
7484: }
7485: }
7486: }
7487: if (keys(%{$allgroups{$cid}}) == 0) {
7488: if (grep/^none$/,@groups) {
7489: return 'ok';
7490: }
7491: } else {
7492: if (grep/^all$/,@groups) {
7493: return 'ok';
7494: }
7495: foreach my $group (keys(%{$allgroups{$cid}})) {
7496: if (grep/^$group$/,@groups) {
7497: return 'ok';
7498: }
7499: }
7500: }
7501: }
7502: }
7503: }
7504: }
7505: }
7506: if ($guest) {
7507: return $guest;
7508: }
7509: }
7510: }
7511: return;
7512: }
7513:
7514: sub course_group_datechecker {
7515: my ($dates,$now,$status) = @_;
7516: my ($start,$end) = split(/\./,$dates);
7517: if (!$start && !$end) {
7518: return 'ok';
7519: }
7520: if (grep/^active$/,@{$status}) {
7521: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7522: return 'ok';
7523: }
7524: }
7525: if (grep/^previous$/,@{$status}) {
7526: if ($end > $now ) {
7527: return 'ok';
7528: }
7529: }
7530: if (grep/^future$/,@{$status}) {
7531: if ($start > $now) {
7532: return 'ok';
7533: }
7534: }
7535: return;
7536: }
7537:
7538: sub parse_portfolio_url {
7539: my ($url) = @_;
7540:
7541: my ($type,$udom,$unum,$group,$file_name);
7542:
1.823 albertel 7543: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7544: $type = 1;
7545: $udom = $1;
7546: $unum = $2;
7547: $file_name = $3;
1.823 albertel 7548: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7549: $type = 2;
7550: $udom = $1;
7551: $unum = $2;
7552: $group = $3;
7553: $file_name = $3.'/'.$4;
7554: }
7555: if (wantarray) {
7556: return ($type,$udom,$unum,$file_name,$group);
7557: }
7558: return $type;
7559: }
7560:
7561: sub is_portfolio_url {
7562: my ($url) = @_;
7563: return scalar(&parse_portfolio_url($url));
7564: }
7565:
1.798 raeburn 7566: sub is_portfolio_file {
7567: my ($file) = @_;
1.820 raeburn 7568: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7569: return 1;
7570: }
7571: return;
7572: }
7573:
1.976 raeburn 7574: sub usertools_access {
1.1084 raeburn 7575: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7576: my ($access,%tools);
7577: if ($context eq '') {
7578: $context = 'tools';
7579: }
7580: if ($context eq 'requestcourses') {
7581: %tools = (
7582: official => 1,
7583: unofficial => 1,
1.1006 raeburn 7584: community => 1,
1.1172.2.37 raeburn 7585: textbook => 1,
1.985 raeburn 7586: );
1.1172.2.9 raeburn 7587: } elsif ($context eq 'requestauthor') {
7588: %tools = (
7589: requestauthor => 1,
7590: );
1.985 raeburn 7591: } else {
7592: %tools = (
7593: aboutme => 1,
7594: blog => 1,
1.1172.2.6 raeburn 7595: webdav => 1,
1.985 raeburn 7596: portfolio => 1,
7597: );
7598: }
1.976 raeburn 7599: return if (!defined($tools{$tool}));
7600:
1.1172.2.35 raeburn 7601: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7602: $udom = $env{'user.domain'};
7603: $uname = $env{'user.name'};
7604: }
7605:
1.978 raeburn 7606: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7607: if ($action ne 'reload') {
1.985 raeburn 7608: if ($context eq 'requestcourses') {
7609: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7610: } elsif ($context eq 'requestauthor') {
7611: return $env{'environment.canrequest.author'};
1.985 raeburn 7612: } else {
7613: return $env{'environment.availabletools.'.$tool};
7614: }
7615: }
1.976 raeburn 7616: }
7617:
1.1172.2.9 raeburn 7618: my ($toolstatus,$inststatus,$envkey);
7619: if ($context eq 'requestauthor') {
7620: $envkey = $context;
7621: } else {
7622: $envkey = $context.'.'.$tool;
7623: }
1.976 raeburn 7624:
1.985 raeburn 7625: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7626: ($action ne 'reload')) {
1.1172.2.9 raeburn 7627: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7628: $inststatus = $env{'environment.inststatus'};
7629: } else {
1.1084 raeburn 7630: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7631: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7632: $inststatus = $userenvref->{'inststatus'};
7633: } else {
1.1172.2.9 raeburn 7634: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7635: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7636: $inststatus = $userenv{'inststatus'};
7637: }
1.976 raeburn 7638: }
7639:
7640: if ($toolstatus ne '') {
7641: if ($toolstatus) {
7642: $access = 1;
7643: } else {
7644: $access = 0;
7645: }
7646: return $access;
7647: }
7648:
1.1084 raeburn 7649: my ($is_adv,%domdef);
7650: if (ref($is_advref) eq 'HASH') {
7651: $is_adv = $is_advref->{'is_adv'};
7652: } else {
7653: $is_adv = &is_advanced_user($udom,$uname);
7654: }
7655: if (ref($domdefref) eq 'HASH') {
7656: %domdef = %{$domdefref};
7657: } else {
7658: %domdef = &get_domain_defaults($udom);
7659: }
1.976 raeburn 7660: if (ref($domdef{$tool}) eq 'HASH') {
7661: if ($is_adv) {
7662: if ($domdef{$tool}{'_LC_adv'} ne '') {
7663: if ($domdef{$tool}{'_LC_adv'}) {
7664: $access = 1;
7665: } else {
7666: $access = 0;
7667: }
7668: return $access;
7669: }
7670: }
7671: if ($inststatus ne '') {
7672: my ($hasaccess,$hasnoaccess);
7673: foreach my $affiliation (split(/:/,$inststatus)) {
7674: if ($domdef{$tool}{$affiliation} ne '') {
7675: if ($domdef{$tool}{$affiliation}) {
7676: $hasaccess = 1;
7677: } else {
7678: $hasnoaccess = 1;
7679: }
7680: }
7681: }
7682: if ($hasaccess || $hasnoaccess) {
7683: if ($hasaccess) {
7684: $access = 1;
7685: } elsif ($hasnoaccess) {
7686: $access = 0;
7687: }
7688: return $access;
7689: }
7690: } else {
7691: if ($domdef{$tool}{'default'} ne '') {
7692: if ($domdef{$tool}{'default'}) {
7693: $access = 1;
7694: } elsif ($domdef{$tool}{'default'} == 0) {
7695: $access = 0;
7696: }
7697: return $access;
7698: }
7699: }
7700: } else {
1.1172.2.6 raeburn 7701: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7702: $access = 1;
7703: } else {
7704: $access = 0;
7705: }
1.976 raeburn 7706: return $access;
7707: }
7708: }
7709:
1.1050 raeburn 7710: sub is_course_owner {
7711: my ($cdom,$cnum,$udom,$uname) = @_;
7712: if (($udom eq '') || ($uname eq '')) {
7713: $udom = $env{'user.domain'};
7714: $uname = $env{'user.name'};
7715: }
7716: unless (($udom eq '') || ($uname eq '')) {
7717: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7718: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7719: return 1;
7720: } else {
7721: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7722: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7723: return 1;
7724: }
7725: }
7726: }
7727: }
7728: return;
7729: }
7730:
1.976 raeburn 7731: sub is_advanced_user {
7732: my ($udom,$uname) = @_;
1.1085 raeburn 7733: if ($udom ne '' && $uname ne '') {
7734: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7735: if (wantarray) {
7736: return ($env{'user.adv'},$env{'user.author'});
7737: } else {
7738: return $env{'user.adv'};
7739: }
1.1085 raeburn 7740: }
7741: }
1.976 raeburn 7742: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7743: my %allroles;
1.1128 raeburn 7744: my ($is_adv,$is_author);
1.976 raeburn 7745: foreach my $role (keys(%roleshash)) {
7746: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7747: my $area = '/'.$tdomain.'/'.$trest;
7748: if ($sec ne '') {
7749: $area .= '/'.$sec;
7750: }
7751: if (($area ne '') && ($trole ne '')) {
7752: my $spec=$trole.'.'.$area;
7753: if ($trole =~ /^cr\//) {
7754: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7755: } elsif ($trole ne 'gr') {
7756: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7757: }
1.1128 raeburn 7758: if ($trole eq 'au') {
7759: $is_author = 1;
7760: }
1.976 raeburn 7761: }
7762: }
7763: foreach my $role (keys(%allroles)) {
7764: last if ($is_adv);
7765: foreach my $item (split(/:/,$allroles{$role})) {
7766: if ($item ne '') {
7767: my ($privilege,$restrictions)=split(/&/,$item);
7768: if ($privilege eq 'adv') {
7769: $is_adv = 1;
7770: last;
7771: }
7772: }
7773: }
7774: }
1.1128 raeburn 7775: if (wantarray) {
7776: return ($is_adv,$is_author);
7777: }
1.976 raeburn 7778: return $is_adv;
7779: }
1.798 raeburn 7780:
1.1035 raeburn 7781: sub check_can_request {
1.1036 raeburn 7782: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7783: my $canreq = 0;
7784: my ($types,$typename) = &Apache::loncommon::course_types();
7785: my @options = ('approval','validate','autolimit');
7786: my $optregex = join('|',@options);
7787: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7788: foreach my $type (@{$types}) {
7789: if (&usertools_access($env{'user.name'},
7790: $env{'user.domain'},
7791: $type,undef,'requestcourses')) {
7792: $canreq ++;
1.1036 raeburn 7793: if (ref($request_domains) eq 'HASH') {
7794: push(@{$request_domains->{$type}},$env{'user.domain'});
7795: }
1.1035 raeburn 7796: if ($dom eq $env{'user.domain'}) {
7797: $can_request->{$type} = 1;
7798: }
7799: }
7800: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7801: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7802: if (@curr > 0) {
1.1036 raeburn 7803: foreach my $item (@curr) {
7804: if (ref($request_domains) eq 'HASH') {
7805: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7806: if ($otherdom ne '') {
7807: if (ref($request_domains->{$type}) eq 'ARRAY') {
7808: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7809: push(@{$request_domains->{$type}},$otherdom);
7810: }
7811: } else {
7812: push(@{$request_domains->{$type}},$otherdom);
7813: }
7814: }
7815: }
7816: }
7817: unless($dom eq $env{'user.domain'}) {
7818: $canreq ++;
1.1035 raeburn 7819: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7820: $can_request->{$type} = 1;
7821: }
7822: }
7823: }
7824: }
7825: }
7826: }
7827: return $canreq;
7828: }
7829:
1.341 www 7830: # ---------------------------------------------- Custom access rule evaluation
7831:
7832: sub customaccess {
7833: my ($priv,$uri)=@_;
1.807 albertel 7834: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7835: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7836: $udom = &LONCAPA::clean_domain($udom);
7837: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7838: my $access=0;
1.800 albertel 7839: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7840: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7841: if ($type eq 'user') {
7842: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7843: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7844: if ($tdom) {
7845: if ($tdom ne $env{'user.domain'}) { next; }
7846: }
1.896 albertel 7847: if ($tuname) {
7848: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7849: }
7850: $access=($effect eq 'allow');
7851: last;
7852: }
7853: } else {
7854: if ($role) {
7855: if ($role ne $urole) { next; }
7856: }
7857: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7858: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7859: if ($tdom) {
7860: if ($tdom ne $udom) { next; }
7861: }
7862: if ($tcrs) {
7863: if ($tcrs ne $ucrs) { next; }
7864: }
7865: if ($tsec) {
7866: if ($tsec ne $usec) { next; }
7867: }
7868: $access=($effect eq 'allow');
7869: last;
7870: }
7871: if ($realm eq '' && $role eq '') {
7872: $access=($effect eq 'allow');
7873: }
1.402 bowersj2 7874: }
1.341 www 7875: }
7876: return $access;
7877: }
7878:
1.103 harris41 7879: # ------------------------------------------------- Check for a user privilege
1.12 www 7880:
7881: sub allowed {
1.1172.2.118. .8(raebu 7882:20): my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 7883: my $ver_orguri=$uri;
1.439 www 7884: $uri=&deversion($uri);
1.152 www 7885: my $orguri=$uri;
1.52 www 7886: $uri=&declutter($uri);
1.809 raeburn 7887:
1.810 raeburn 7888: if ($priv eq 'evb') {
7889: # Evade communication block restrictions for specified role in a course
7890: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7891: return $1;
7892: } else {
7893: return;
7894: }
7895: }
7896:
1.620 albertel 7897: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7898: # Free bre access to adm and meta resources
1.1172.2.118. .13(raeb 7899:-21): if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 7900: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7901: && ($priv eq 'bre')) {
1.14 www 7902: return 'F';
1.159 www 7903: }
7904:
1.545 banghart 7905: # Free bre access to user's own portfolio contents
1.714 raeburn 7906: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7907: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7908: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7909: my %setters;
7910: my ($startblock,$endblock) =
7911: &Apache::loncommon::blockcheck(\%setters,'port');
7912: if ($startblock && $endblock) {
7913: return 'B';
7914: } else {
7915: return 'F';
7916: }
1.545 banghart 7917: }
7918:
1.762 raeburn 7919: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7920: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7921: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7922: if (exists($env{'request.course.id'})) {
7923: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7924: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7925: if (($domain eq $cdom) && ($name eq $cnum)) {
7926: my $courseprivid=$env{'request.course.id'};
7927: $courseprivid=~s/\_/\//;
7928: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7929: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7930: return $1;
1.762 raeburn 7931: } else {
7932: if ($env{'request.course.sec'}) {
7933: $courseprivid.='/'.$env{'request.course.sec'};
7934: }
7935: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7936: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7937: return $2;
7938: }
1.714 raeburn 7939: }
7940: }
7941: }
7942: }
7943:
1.159 www 7944: # Free bre to public access
7945:
7946: if ($priv eq 'bre') {
1.238 www 7947: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7948: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7949: return 'F';
7950: }
1.238 www 7951: if ($copyright eq 'priv') {
7952: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7953: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7954: return '';
7955: }
7956: }
7957: if ($copyright eq 'domain') {
7958: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7959: unless (($env{'user.domain'} eq $1) ||
7960: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7961: return '';
7962: }
1.262 matthew 7963: }
1.620 albertel 7964: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7965: # Library role, so allow browsing of resources in this domain.
7966: return 'F';
1.238 www 7967: }
1.341 www 7968: if ($copyright eq 'custom') {
7969: unless (&customaccess($priv,$uri)) { return ''; }
7970: }
1.14 www 7971: }
1.264 matthew 7972: # Domain coordinator is trying to create a course
1.620 albertel 7973: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7974: # uri is the requested domain in this case.
7975: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7976: # a role of dc for the domain in question.
1.620 albertel 7977: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7978: }
1.29 www 7979:
1.52 www 7980: my $thisallowed='';
7981: my $statecond=0;
7982: my $courseprivid='';
7983:
1.1039 raeburn 7984: my $ownaccess;
1.1043 raeburn 7985: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7986: if (($priv eq 'bro') && ($env{'user.author'})) {
7987: if ($uri eq '') {
7988: $ownaccess = 1;
7989: } else {
7990: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7991: my $udom = $env{'user.domain'};
7992: my $uname = $env{'user.name'};
7993: if ($uri =~ m{^\Q$udom\E/?$}) {
7994: $ownaccess = 1;
1.1040 raeburn 7995: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7996: unless ($uri =~ m{\.\./}) {
7997: $ownaccess = 1;
7998: }
7999: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8000: my $now = time;
8001: if ($uri =~ m{^([^/]+)/?$}) {
8002: my $adom = $1;
8003: foreach my $key (keys(%env)) {
1.1042 raeburn 8004: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 8005: my ($start,$end) = split('.',$env{$key});
8006: if (($now >= $start) && (!$end || $end < $now)) {
8007: $ownaccess = 1;
8008: last;
8009: }
8010: }
8011: }
8012: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8013: my $adom = $1;
8014: my $aname = $2;
1.1042 raeburn 8015: foreach my $role ('ca','aa') {
8016: if ($env{"user.role.$role./$adom/$aname"}) {
8017: my ($start,$end) =
8018: split('.',$env{"user.role.$role./$adom/$aname"});
8019: if (($now >= $start) && (!$end || $end < $now)) {
8020: $ownaccess = 1;
8021: last;
8022: }
1.1039 raeburn 8023: }
8024: }
8025: }
8026: }
8027: }
8028: }
8029: }
8030:
1.52 www 8031: # Course
8032:
1.620 albertel 8033: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8034: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8035: $thisallowed.=$1;
8036: }
1.52 www 8037: }
1.29 www 8038:
1.52 www 8039: # Domain
8040:
1.620 albertel 8041: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8042: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8043: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8044: $thisallowed.=$1;
8045: }
1.12 www 8046: }
1.52 www 8047:
1.1141 raeburn 8048: # User who is not author or co-author might still be able to edit
8049: # resource of an author in the domain (e.g., if Domain Coordinator).
8050: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8051: (&allowed('mdc',$env{'request.course.id'}))) {
8052: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8053: $thisallowed.=$1;
8054: }
8055: }
8056:
1.52 www 8057: # Course: uri itself is a course
1.66 www 8058: my $courseuri=$uri;
8059: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8060: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8061:
1.620 albertel 8062: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8063: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 8064: if ($priv eq 'mip') {
8065: my $rem = $1;
8066: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8067: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8068: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8069: if ($cdom ne '') {
8070: my %passwdconf = &get_passwdconf($cdom);
8071: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8072: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8073: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8074: my @inststatuses = split(':',$env{'environment.inststatus'});
8075: unless (@inststatuses) {
8076: @inststatuses = ('default');
8077: }
8078: foreach my $status (@inststatuses) {
8079: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8080: $thisallowed.=$rem;
8081: }
8082: }
8083: }
8084: }
8085: }
8086: }
8087: }
8088: } else {
8089: unless (($priv eq 'bro') && (!$ownaccess)) {
8090: $thisallowed.=$1;
8091: }
1.1039 raeburn 8092: }
1.12 www 8093: }
1.29 www 8094:
1.665 albertel 8095: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8096: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8097: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8098: $thisallowed='';
1.671 raeburn 8099: my ($match)=&is_on_map($uri);
8100: if ($match) {
8101: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8102: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8103: my $value = $1;
8104: if ($noblockcheck) {
8105: $thisallowed.=$value;
1.1162 raeburn 8106: } else {
1.1172.2.118. .8(raebu 8107:20): my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8108: if (@blockers > 0) {
8109: $thisallowed = 'B';
8110: } else {
8111: $thisallowed.=$value;
8112: }
1.1162 raeburn 8113: }
1.671 raeburn 8114: }
8115: } else {
1.705 albertel 8116: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8117: if ($refuri) {
8118: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8119: $thisallowed='F';
1.671 raeburn 8120: } else {
8121: $refuri=&declutter($refuri);
8122: my ($match) = &is_on_map($refuri);
8123: if ($match) {
1.1172.2.65 raeburn 8124: if ($noblockcheck) {
1.1162 raeburn 8125: $thisallowed='F';
1.1172.2.65 raeburn 8126: } else {
1.1172.2.118. .8(raebu 8127:20): my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8128: if (@blockers > 0) {
8129: $thisallowed = 'B';
8130: } else {
8131: $thisallowed='F';
8132: }
1.1162 raeburn 8133: }
1.671 raeburn 8134: }
1.669 raeburn 8135: }
1.671 raeburn 8136: }
8137: }
1.314 www 8138: }
1.492 albertel 8139:
1.766 albertel 8140: if ($priv eq 'bre'
8141: && $thisallowed ne 'F'
8142: && $thisallowed ne '2'
8143: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8144: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8145: }
1.1172.2.118. .8(raebu 8146:20):
1.52 www 8147: # Full access at system, domain or course-wide level? Exit.
1.29 www 8148: if ($thisallowed=~/F/) {
8149: return 'F';
8150: }
8151:
1.52 www 8152: # If this is generating or modifying users, exit with special codes
1.29 www 8153:
1.643 www 8154: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8155: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8156: my ($audom,$auname)=split('/',$uri);
1.643 www 8157: # no author name given, so this just checks on the general right to make a co-author in this domain
8158: unless ($auname) { return $thisallowed; }
8159: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8160: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8161: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8162: ($audom ne $env{'request.role.domain'}))) { return ''; }
8163: }
1.52 www 8164: return $thisallowed;
8165: }
8166: #
1.103 harris41 8167: # Gathered so far: system, domain and course wide privileges
1.52 www 8168: #
8169: # Course: See if uri or referer is an individual resource that is part of
8170: # the course
8171:
1.620 albertel 8172: if ($env{'request.course.id'}) {
1.232 www 8173:
1.1172.2.115 raeburn 8174: # If this is modifying password (internal auth) domains must match for user and user's role.
8175:
8176: if ($priv eq 'mip') {
8177: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8178: return $thisallowed;
8179: } else {
8180: return '';
8181: }
8182: }
8183:
1.620 albertel 8184: $courseprivid=$env{'request.course.id'};
8185: if ($env{'request.course.sec'}) {
8186: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8187: }
8188: $courseprivid=~s/\_/\//;
8189: my $checkreferer=1;
1.232 www 8190: my ($match,$cond)=&is_on_map($uri);
8191: if ($match) {
8192: $statecond=$cond;
1.620 albertel 8193: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8194: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8195: my $value = $1;
8196: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8197: if ($noblockcheck) {
1.1162 raeburn 8198: $thisallowed.=$value;
1.1172.2.65 raeburn 8199: } else {
1.1172.2.118. .8(raebu 8200:20): my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8201: if (@blockers > 0) {
8202: $thisallowed = 'B';
8203: } else {
8204: $thisallowed.=$value;
8205: }
1.1162 raeburn 8206: }
8207: } else {
8208: $thisallowed.=$value;
8209: }
1.52 www 8210: $checkreferer=0;
8211: }
1.29 www 8212: }
1.1172.2.118. .8(raebu 8213:20):
1.148 www 8214: if ($checkreferer) {
1.620 albertel 8215: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8216: unless ($refuri) {
1.800 albertel 8217: foreach my $key (keys(%env)) {
8218: if ($key=~/^httpref\..*\*/) {
8219: my $pattern=$key;
1.156 www 8220: $pattern=~s/^httpref\.\/res\///;
1.148 www 8221: $pattern=~s/\*/\[\^\/\]\+/g;
8222: $pattern=~s/\//\\\//g;
1.152 www 8223: if ($orguri=~/$pattern/) {
1.800 albertel 8224: $refuri=$env{$key};
1.148 www 8225: }
8226: }
1.191 harris41 8227: }
1.148 www 8228: }
1.232 www 8229:
1.148 www 8230: if ($refuri) {
1.152 www 8231: $refuri=&declutter($refuri);
1.232 www 8232: my ($match,$cond)=&is_on_map($refuri);
8233: if ($match) {
8234: my $refstatecond=$cond;
1.620 albertel 8235: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8236: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8237: my $value = $1;
8238: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8239: if ($noblockcheck) {
1.1162 raeburn 8240: $thisallowed.=$value;
1.1172.2.65 raeburn 8241: } else {
1.1172.2.118. .8(raebu 8242:20): my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8243: if (@blockers > 0) {
8244: $thisallowed = 'B';
8245: } else {
8246: $thisallowed.=$value;
8247: }
1.1162 raeburn 8248: }
8249: } else {
8250: $thisallowed.=$value;
8251: }
1.53 www 8252: $uri=$refuri;
8253: $statecond=$refstatecond;
1.52 www 8254: }
8255: }
1.148 www 8256: }
1.29 www 8257: }
1.52 www 8258: }
1.29 www 8259:
1.52 www 8260: #
1.103 harris41 8261: # Gathered now: all privileges that could apply, and condition number
1.52 www 8262: #
8263: #
8264: # Full or no access?
8265: #
1.29 www 8266:
1.52 www 8267: if ($thisallowed=~/F/) {
8268: return 'F';
8269: }
1.29 www 8270:
1.52 www 8271: unless ($thisallowed) {
8272: return '';
8273: }
1.29 www 8274:
1.52 www 8275: # Restrictions exist, deal with them
8276: #
8277: # C:according to course preferences
8278: # R:according to resource settings
8279: # L:unless locked
8280: # X:according to user session state
8281: #
8282:
8283: # Possibly locked functionality, check all courses
1.54 www 8284: # Locks might take effect only after 10 minutes cache expiration for other
8285: # courses, and 2 minutes for current course
1.52 www 8286:
8287: my $envkey;
8288: if ($thisallowed=~/L/) {
1.1000 raeburn 8289: foreach $envkey (keys(%env)) {
1.54 www 8290: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8291: my $courseid=$2;
8292: my $roleid=$1.'.'.$2;
1.92 www 8293: $courseid=~s/^\///;
1.54 www 8294: my $expiretime=600;
1.620 albertel 8295: if ($env{'request.role'} eq $roleid) {
1.54 www 8296: $expiretime=120;
8297: }
8298: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8299: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8300: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8301: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8302: }
1.620 albertel 8303: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8304: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8305: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8306: &log($env{'user.domain'},$env{'user.name'},
8307: $env{'user.home'},
1.57 www 8308: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8309: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8310: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8311: return '';
8312: }
8313: }
1.620 albertel 8314: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8315: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8316: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8317: &log($env{'user.domain'},$env{'user.name'},
8318: $env{'user.home'},
1.57 www 8319: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8320: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8321: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8322: return '';
8323: }
8324: }
8325: }
1.29 www 8326: }
1.52 www 8327: }
1.1172.2.118. .8(raebu 8328:20):
1.52 www 8329: #
8330: # Rest of the restrictions depend on selected course
8331: #
8332:
1.620 albertel 8333: unless ($env{'request.course.id'}) {
1.766 albertel 8334: if ($thisallowed eq 'A') {
8335: return 'A';
1.814 raeburn 8336: } elsif ($thisallowed eq 'B') {
8337: return 'B';
1.766 albertel 8338: } else {
8339: return '1';
8340: }
1.52 www 8341: }
1.29 www 8342:
1.52 www 8343: #
8344: # Now user is definitely in a course
8345: #
1.53 www 8346:
8347:
8348: # Course preferences
8349:
8350: if ($thisallowed=~/C/) {
1.620 albertel 8351: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8352: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8353: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8354: =~/\Q$rolecode\E/) {
1.1103 raeburn 8355: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8356: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8357: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8358: $env{'request.course.id'});
8359: }
1.237 www 8360: return '';
8361: }
8362:
1.620 albertel 8363: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8364: =~/\Q$unamedom\E/) {
1.1103 raeburn 8365: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8366: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8367: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8368: $env{'request.course.id'});
8369: }
1.54 www 8370: return '';
8371: }
1.53 www 8372: }
8373:
8374: # Resource preferences
8375:
8376: if ($thisallowed=~/R/) {
1.620 albertel 8377: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8378: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8379: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8380: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8381: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8382: }
8383: return '';
1.54 www 8384: }
1.53 www 8385: }
1.30 www 8386:
1.246 www 8387: # Restricted by state or randomout?
1.30 www 8388:
1.52 www 8389: if ($thisallowed=~/X/) {
1.620 albertel 8390: if ($env{'acc.randomout'}) {
1.579 albertel 8391: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8392: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8393: return '';
8394: }
1.247 www 8395: }
8396: if (&condval($statecond)) {
1.52 www 8397: return '2';
8398: } else {
8399: return '';
8400: }
8401: }
1.30 www 8402:
1.766 albertel 8403: if ($thisallowed eq 'A') {
8404: return 'A';
1.814 raeburn 8405: } elsif ($thisallowed eq 'B') {
8406: return 'B';
1.766 albertel 8407: }
1.52 www 8408: return 'F';
1.232 www 8409: }
1.1162 raeburn 8410:
1.1172.2.13 raeburn 8411: # ------------------------------------------- Check construction space access
8412:
8413: sub constructaccess {
8414: my ($url,$setpriv)=@_;
8415:
8416: # We do not allow editing of previous versions of files
8417: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8418:
8419: # Get username and domain from URL
8420: my ($ownername,$ownerdomain,$ownerhome);
8421:
8422: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 8423: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8424:
8425: # The URL does not really point to any authorspace, forget it
8426: unless (($ownername) && ($ownerdomain)) { return ''; }
8427:
8428: # Now we need to see if the user has access to the authorspace of
8429: # $ownername at $ownerdomain
8430:
8431: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8432: # Real author for this?
8433: $ownerhome = $env{'user.home'};
8434: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8435: return ($ownername,$ownerdomain,$ownerhome);
8436: }
8437: } else {
8438: # Co-author for this?
8439: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8440: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8441: $ownerhome = &homeserver($ownername,$ownerdomain);
8442: return ($ownername,$ownerdomain,$ownerhome);
8443: }
8444: }
8445:
8446: # We don't have any access right now. If we are not possibly going to do anything about this,
8447: # we might as well leave
8448: unless ($setpriv) { return ''; }
8449:
8450: # Backdoor access?
8451: my $allowed=&allowed('eco',$ownerdomain);
8452: # Nope
8453: unless ($allowed) { return ''; }
8454: # Looks like we may have access, but could be locked by the owner of the construction space
8455: if ($allowed eq 'U') {
8456: my %blocked=&get('environment',['domcoord.author'],
8457: $ownerdomain,$ownername);
8458: # Is blocked by owner
8459: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8460: }
8461: if (($allowed eq 'F') || ($allowed eq 'U')) {
8462: # Grant temporary access
8463: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8464: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8465: if (!$update) { $update = $then; }
8466: my $refresh=$env{'user.refresh.time'};
8467: if (!$refresh) { $refresh = $update; }
8468: my $now = time;
8469: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8470: $now,'ca','constructaccess');
8471: $ownerhome = &homeserver($ownername,$ownerdomain);
8472: return($ownername,$ownerdomain,$ownerhome);
8473: }
8474: # No business here
8475: return '';
8476: }
8477:
1.1172.2.66 raeburn 8478: # ----------------------------------------------------------- Content Blocking
8479:
8480: {
8481: # Caches for faster Course Contents display where content blocking
8482: # is in operation (i.e., interval param set) for timed quiz.
8483: #
8484: # User for whom data are being temporarily cached.
8485: my $cacheduser='';
1.1172.2.118. .8(raebu 8486:20): # Course for which data are being temporarily cached.
8487:20): my $cachedcid='';
1.1172.2.66 raeburn 8488: # Cached blockers for this user (a hash of blocking items).
8489: my %cachedblockers=();
8490: # When the data were last cached.
8491: my $cachedlast='';
8492:
8493: sub load_all_blockers {
1.1172.2.118. .9(raebu 8494:20): my ($uname,$udom)=@_;
1.1172.2.66 raeburn 8495: if (($uname ne '') && ($udom ne '')) {
8496: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.118. .8(raebu 8497:20): ($cachedcid eq $env{'request.course.id'}) &&
.9(raebu 8498:20): (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 8499: return;
8500: }
8501: }
8502: $cachedlast=time;
8503: $cacheduser=$uname.':'.$udom;
1.1172.2.118. .8(raebu 8504:20): $cachedcid=$env{'request.course.id'};
.9(raebu 8505:20): %cachedblockers = &get_commblock_resources();
.8(raebu 8506:20): return;
1.1172.2.66 raeburn 8507: }
8508:
1.1162 raeburn 8509: sub get_comm_blocks {
8510: my ($cdom,$cnum) = @_;
8511: if ($cdom eq '' || $cnum eq '') {
8512: return unless ($env{'request.course.id'});
8513: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8514: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8515: }
8516: my %commblocks;
8517: my $hashid=$cdom.'_'.$cnum;
8518: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8519: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8520: %commblocks = %{$blocksref};
8521: } else {
8522: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8523: my $cachetime = 600;
8524: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8525: }
8526: return %commblocks;
8527: }
8528:
1.1172.2.66 raeburn 8529: sub get_commblock_resources {
8530: my ($blocks) = @_;
8531: my %blockers = ();
8532: return %blockers unless ($env{'request.course.id'});
8533: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8534: my %commblocks;
8535: if (ref($blocks) eq 'HASH') {
8536: %commblocks = %{$blocks};
8537: } else {
8538: %commblocks = &get_comm_blocks();
8539: }
1.1172.2.66 raeburn 8540: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8541: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8542: return %blockers unless (ref($navmap));
8543: my $now = time;
1.1162 raeburn 8544: foreach my $block (keys(%commblocks)) {
8545: if ($block =~ /^(\d+)____(\d+)$/) {
8546: my ($start,$end) = ($1,$2);
8547: if ($start <= $now && $end >= $now) {
8548: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8549: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8550: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8551: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8552: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8553: }
8554: }
8555: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8556: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8557: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8558: }
8559: }
8560: }
8561: }
8562: }
8563: } elsif ($block =~ /^firstaccess____(.+)$/) {
8564: my $item = $1;
1.1163 raeburn 8565: my @to_test;
1.1162 raeburn 8566: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8567: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 8568: my @interval;
8569: my $type = 'map';
8570: if ($item eq 'course') {
8571: $type = 'course';
8572: @interval=&EXT("resource.0.interval");
8573: } else {
8574: if ($item =~ /___\d+___/) {
8575: $type = 'resource';
8576: @interval=&EXT("resource.0.interval",$item);
8577: if (ref($navmap)) {
8578: my $res = $navmap->getBySymb($item);
8579: push(@to_test,$res);
8580: }
1.1162 raeburn 8581: } else {
1.1172.2.66 raeburn 8582: my $mapsymb = &symbread($item,1);
8583: if ($mapsymb) {
8584: if (ref($navmap)) {
8585: my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.118. .11(raeb 8586:-20): if (ref($mapres)) {
8587:-20): my $first = $mapres->map_start();
8588:-20): my $finish = $mapres->map_finish();
8589:-20): my $it = $navmap->getIterator($first,$finish,undef,0,0);
8590:-20): if (ref($it)) {
8591:-20): my $res;
8592:-20): while ($res = $it->next(undef,1)) {
8593:-20): next unless (ref($res));
8594:-20): my $symb = $res->symb();
8595:-20): next if (($symb eq $mapsymb) || ($symb eq ''));
8596:-20): @interval=&EXT("resource.0.interval",$symb);
8597:-20): if ($interval[1] eq 'map') {
8598:-20): if ($res->answerable()) {
8599:-20): push(@to_test,$res);
8600:-20): last;
8601:-20): }
8602:-20): }
1.1162 raeburn 8603: }
8604: }
8605: }
8606: }
8607: }
8608: }
1.1172.2.66 raeburn 8609: }
1.1172.2.118. .1(raebu 8610:20): if ($interval[0] =~ /^(\d+)/) {
8611:20): my $timelimit = $1;
1.1172.2.66 raeburn 8612: my $first_access;
8613: if ($type eq 'resource') {
8614: $first_access=&get_first_access($interval[1],$item);
8615: } elsif ($type eq 'map') {
8616: $first_access=&get_first_access($interval[1],undef,$item);
8617: } else {
8618: $first_access=&get_first_access($interval[1]);
8619: }
8620: if ($first_access) {
1.1172.2.118. .1(raebu 8621:20): my $timesup = $first_access+$timelimit;
1.1172.2.66 raeburn 8622: if ($timesup > $now) {
8623: my $activeblock;
8624: foreach my $res (@to_test) {
8625: if ($res->answerable()) {
8626: $activeblock = 1;
8627: last;
8628: }
8629: }
8630: if ($activeblock) {
8631: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8632: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8633: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8634: }
8635: }
8636: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8637: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8638: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8639: }
1.1162 raeburn 8640: }
8641: }
8642: }
8643: }
8644: }
8645: }
8646: }
8647: }
8648: }
1.1172.2.66 raeburn 8649: return %blockers;
1.1162 raeburn 8650: }
8651:
1.1172.2.66 raeburn 8652: sub has_comm_blocking {
1.1172.2.118. .9(raebu 8653:20): my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 8654: my @blockers;
8655: return unless ($env{'request.course.id'});
8656: return unless ($priv eq 'bre');
8657: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8658: return if ($env{'request.state'} eq 'construct');
1.1172.2.118. .9(raebu 8659:20): my %blockinfo;
8660:20): if (ref($blocks) eq 'HASH') {
8661:20): %blockinfo = &get_commblock_resources($blocks);
8662:20): } else {
8663:20): &load_all_blockers($env{'user.name'},$env{'user.domain'});
8664:20): %blockinfo = %cachedblockers;
8665:20): }
8666:20): return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 8667: my (%possibles,@symbs);
8668: if (!$symb) {
1.1172.2.118. .9(raebu 8669:20): $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8670: }
1.1172.2.66 raeburn 8671: if ($symb) {
8672: @symbs = ($symb);
8673: } elsif (keys(%possibles)) {
8674: @symbs = keys(%possibles);
8675: }
8676: my $noblock;
8677: foreach my $symb (@symbs) {
8678: last if ($noblock);
8679: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.118. .9(raebu 8680:20): foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 8681: if ($block =~ /^firstaccess____(.+)$/) {
8682: my $item = $1;
1.1172.2.118. .8(raebu 8683:20): unless ($blocked) {
8684:20): if (($item eq $map) || ($item eq $symb)) {
8685:20): $noblock = 1;
8686:20): last;
8687:20): }
1.1172.2.66 raeburn 8688: }
1.1162 raeburn 8689: }
1.1172.2.118. .9(raebu 8690:20): if (ref($blockinfo{$block}) eq 'HASH') {
8691:20): if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8692:20): if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 8693: unless (grep(/^\Q$block\E$/,@blockers)) {
8694: push(@blockers,$block);
8695: }
8696: }
8697: }
1.1172.2.118. .9(raebu 8698:20): if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8699:20): if ($blockinfo{$block}{'maps'}{$map}) {
.8(raebu 8700:20): unless (grep(/^\Q$block\E$/,@blockers)) {
8701:20): push(@blockers,$block);
8702:20): }
1.1172.2.66 raeburn 8703: }
8704: }
1.1162 raeburn 8705: }
8706: }
8707: }
1.1172.2.118. .8(raebu 8708:20): unless ($noblock) {
8709:20): return @blockers;
8710:20): }
8711:20): return;
1.1172.2.66 raeburn 8712: }
1.1162 raeburn 8713: }
8714:
1.1172.2.66 raeburn 8715: # -------------------------------- Deversion and split uri into path an filename
8716:
1.1133 foxr 8717: #
1.1172.2.66 raeburn 8718: # Removes the version from a URI and
1.1133 foxr 8719: # splits it in to its filename and path to the filename.
8720: # Seems like File::Basename could have done this more clearly.
8721: # Parameters:
8722: # $uri - input URI
8723: # Returns:
8724: # Two element list consisting of
8725: # $pathname - the URI up to and excluding the trailing /
8726: # $filename - The part of the URI following the last /
8727: # NOTE:
8728: # Another realization of this is simply:
8729: # use File::Basename;
8730: # ...
8731: # $uri = shift;
8732: # $filename = basename($uri);
8733: # $path = dirname($uri);
8734: # return ($filename, $path);
8735: #
8736: # The implementation below is probably faster however.
8737: #
1.710 albertel 8738: sub split_uri_for_cond {
8739: my $uri=&deversion(&declutter(shift));
8740: my @uriparts=split(/\//,$uri);
8741: my $filename=pop(@uriparts);
8742: my $pathname=join('/',@uriparts);
8743: return ($pathname,$filename);
8744: }
1.232 www 8745: # --------------------------------------------------- Is a resource on the map?
8746:
8747: sub is_on_map {
1.710 albertel 8748: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8749: #Trying to find the conditional for the file
1.620 albertel 8750: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8751: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8752: if ($match) {
1.289 bowersj2 8753: return (1,$1);
8754: } else {
1.434 www 8755: return (0,0);
1.289 bowersj2 8756: }
1.12 www 8757: }
8758:
1.427 www 8759: # --------------------------------------------------------- Get symb from alias
8760:
8761: sub get_symb_from_alias {
8762: my $symb=shift;
8763: my ($map,$resid,$url)=&decode_symb($symb);
8764: # Already is a symb
8765: if ($url) { return $symb; }
8766: # Must be an alias
8767: my $aliassymb='';
8768: my %bighash;
1.620 albertel 8769: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8770: &GDBM_READER(),0640)) {
8771: my $rid=$bighash{'mapalias_'.$symb};
8772: if ($rid) {
8773: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8774: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8775: $resid,$bighash{'src_'.$rid});
1.427 www 8776: }
8777: untie %bighash;
8778: }
8779: return $aliassymb;
8780: }
8781:
1.12 www 8782: # ----------------------------------------------------------------- Define Role
8783:
8784: sub definerole {
8785: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8786: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8787: foreach my $role (split(':',$sysrole)) {
8788: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8789: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8790: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8791: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8792: return "refused:s:$crole&$cqual";
8793: }
8794: }
1.191 harris41 8795: }
1.800 albertel 8796: foreach my $role (split(':',$domrole)) {
8797: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8798: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8799: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8800: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8801: return "refused:d:$crole&$cqual";
8802: }
8803: }
1.191 harris41 8804: }
1.800 albertel 8805: foreach my $role (split(':',$courole)) {
8806: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8807: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8808: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8809: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8810: return "refused:c:$crole&$cqual";
8811: }
8812: }
1.191 harris41 8813: }
1.1172.2.84 raeburn 8814: my $uhome;
8815: if (($uname ne '') && ($udom ne '')) {
8816: $uhome = &homeserver($uname,$udom);
8817: return $uhome if ($uhome eq 'no_host');
8818: } else {
8819: $uname = $env{'user.name'};
8820: $udom = $env{'user.domain'};
8821: $uhome = $env{'user.home'};
8822: }
1.620 albertel 8823: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8824: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8825: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8826: return reply($command,$uhome);
1.12 www 8827: } else {
8828: return 'refused';
8829: }
1.105 harris41 8830: }
8831:
8832: # ---------------- Make a metadata query against the network of library servers
8833:
8834: sub metadata_query {
1.1172.2.33 raeburn 8835: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8836: my %rhash;
1.845 albertel 8837: my %libserv = &all_library();
1.244 matthew 8838: my @server_list = (defined($server_array) ? @$server_array
8839: : keys(%libserv) );
8840: for my $server (@server_list) {
1.1172.2.33 raeburn 8841: my $domains = '';
8842: if (ref($domains_hash) eq 'HASH') {
8843: $domains = $domains_hash->{$server};
8844: }
1.118 harris41 8845: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8846: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8847: $rhash{$server}=$reply;
8848: }
8849: else {
8850: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8851: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8852: $server);
8853: $rhash{$server}=$reply;
8854: }
1.112 harris41 8855: }
1.118 harris41 8856: return \%rhash;
1.240 www 8857: }
8858:
8859: # ----------------------------------------- Send log queries and wait for reply
8860:
8861: sub log_query {
8862: my ($uname,$udom,$query,%filters)=@_;
8863: my $uhome=&homeserver($uname,$udom);
8864: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8865: my $uhost=&hostname($uhome);
1.800 albertel 8866: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8867: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8868: $uhome);
1.479 albertel 8869: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8870: return get_query_reply($queryid);
8871: }
8872:
1.818 raeburn 8873: # -------------------------- Update MySQL table for portfolio file
8874:
8875: sub update_portfolio_table {
1.821 raeburn 8876: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8877: if ($group ne '') {
8878: $file_name =~s /^\Q$group\E//;
8879: }
1.818 raeburn 8880: my $homeserver = &homeserver($uname,$udom);
8881: my $queryid=
1.821 raeburn 8882: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8883: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8884: my $reply = &get_query_reply($queryid);
8885: return $reply;
8886: }
8887:
1.899 raeburn 8888: # -------------------------- Update MySQL allusers table
8889:
8890: sub update_allusers_table {
8891: my ($uname,$udom,$names) = @_;
8892: my $homeserver = &homeserver($uname,$udom);
8893: my $queryid=
8894: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8895: 'lastname='.&escape($names->{'lastname'}).'%%'.
8896: 'firstname='.&escape($names->{'firstname'}).'%%'.
8897: 'middlename='.&escape($names->{'middlename'}).'%%'.
8898: 'generation='.&escape($names->{'generation'}).'%%'.
8899: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8900: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8901: return;
1.899 raeburn 8902: }
8903:
1.508 raeburn 8904: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8905:
8906: sub fetch_enrollment_query {
1.511 raeburn 8907: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8908: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8909: my $maxtries = 1;
1.508 raeburn 8910: if ($context eq 'automated') {
8911: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8912: $sleep = 2;
8913: $loopmax = 100;
1.547 raeburn 8914: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8915: } else {
8916: $homeserver = &homeserver($cnum,$dom);
8917: }
1.838 albertel 8918: my $host=&hostname($homeserver);
1.506 raeburn 8919: my $cmd = '';
1.1000 raeburn 8920: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8921: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8922: }
8923: $cmd =~ s/%%$//;
8924: $cmd = &escape($cmd);
8925: my $query = 'fetchenrollment';
1.620 albertel 8926: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8927: unless ($queryid=~/^\Q$host\E\_/) {
8928: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8929: return 'error: '.$queryid;
8930: }
1.1172.2.93 raeburn 8931: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8932: my $tries = 1;
8933: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8934: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8935: $tries ++;
8936: }
1.526 raeburn 8937: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8938: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8939: } else {
1.901 albertel 8940: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8941: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8942: foreach my $line (@responses) {
8943: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8944: $$replyref{$key} = $value;
8945: }
8946: } else {
1.1117 foxr 8947: my $pathname = LONCAPA::tempdir();
1.800 albertel 8948: foreach my $line (@responses) {
8949: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8950: $$replyref{$key} = $value;
8951: if ($value > 0) {
1.800 albertel 8952: foreach my $item (@{$$affiliatesref{$key}}) {
8953: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8954: my $destname = $pathname.'/'.$filename;
8955: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8956: if ($xml_classlist =~ /^error/) {
8957: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8958: } else {
1.1172.2.96 raeburn 8959: if ( open(FILE,">",$destname) ) {
1.506 raeburn 8960: print FILE &unescape($xml_classlist);
8961: close(FILE);
1.526 raeburn 8962: } else {
8963: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8964: }
8965: }
8966: }
8967: }
8968: }
8969: }
8970: return 'ok';
8971: }
8972: return 'error';
8973: }
8974:
1.242 www 8975: sub get_query_reply {
1.1172.2.79 raeburn 8976: my ($queryid,$sleep,$loopmax) = @_;
8977: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8978: $sleep = 0.2;
8979: }
8980: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8981: $loopmax = 100;
8982: }
1.1117 foxr 8983: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8984: my $reply='';
1.1172.2.79 raeburn 8985: for (1..$loopmax) {
8986: sleep($sleep);
1.240 www 8987: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 8988: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 8989: $reply = join('',<$fh>);
8990: close($fh);
1.240 www 8991: } else { return 'error: reply_file_error'; }
1.242 www 8992: return &unescape($reply);
8993: }
1.240 www 8994: }
1.242 www 8995: return 'timeout:'.$queryid;
1.240 www 8996: }
8997:
8998: sub courselog_query {
1.241 www 8999: #
9000: # possible filters:
9001: # url: url or symb
9002: # username
9003: # domain
9004: # action: view, submit, grade
9005: # start: timestamp
9006: # end: timestamp
9007: #
1.240 www 9008: my (%filters)=@_;
1.620 albertel 9009: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9010: if ($filters{'url'}) {
9011: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9012: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9013: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9014: }
1.620 albertel 9015: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9016: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9017: return &log_query($cname,$cdom,'courselog',%filters);
9018: }
9019:
9020: sub userlog_query {
1.858 raeburn 9021: #
9022: # possible filters:
9023: # action: log check role
9024: # start: timestamp
9025: # end: timestamp
9026: #
1.240 www 9027: my ($uname,$udom,%filters)=@_;
9028: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9029: }
9030:
1.506 raeburn 9031: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9032:
9033: sub auto_run {
1.508 raeburn 9034: my ($cnum,$cdom) = @_;
1.876 raeburn 9035: my $response = 0;
9036: my $settings;
9037: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9038: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9039: $settings = $domconfig{'autoenroll'};
9040: if ($settings->{'run'} eq '1') {
9041: $response = 1;
9042: }
9043: } else {
1.934 raeburn 9044: my $homeserver;
9045: if (&is_course($cdom,$cnum)) {
9046: $homeserver = &homeserver($cnum,$cdom);
9047: } else {
9048: $homeserver = &domain($cdom,'primary');
9049: }
9050: if ($homeserver ne 'no_host') {
9051: $response = &reply('autorun:'.$cdom,$homeserver);
9052: }
1.876 raeburn 9053: }
1.506 raeburn 9054: return $response;
9055: }
1.776 albertel 9056:
1.506 raeburn 9057: sub auto_get_sections {
1.508 raeburn 9058: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9059: my $homeserver;
9060: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9061: $homeserver = &homeserver($cnum,$cdom);
9062: }
9063: if (!defined($homeserver)) {
9064: if ($cdom =~ /^$match_domain$/) {
9065: $homeserver = &domain($cdom,'primary');
9066: }
9067: }
9068: my @secs;
9069: if (defined($homeserver)) {
9070: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9071: unless ($response eq 'refused') {
9072: @secs = split(/:/,$response);
9073: }
1.506 raeburn 9074: }
9075: return @secs;
9076: }
1.776 albertel 9077:
1.506 raeburn 9078: sub auto_new_course {
1.1099 raeburn 9079: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9080: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9081: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9082: return $response;
9083: }
1.776 albertel 9084:
1.506 raeburn 9085: sub auto_validate_courseID {
1.508 raeburn 9086: my ($cnum,$cdom,$inst_course_id) = @_;
9087: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9088: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9089: return $response;
9090: }
1.776 albertel 9091:
1.1007 raeburn 9092: sub auto_validate_instcode {
1.1020 raeburn 9093: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9094: my ($homeserver,$response);
9095: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9096: $homeserver = &homeserver($cnum,$cdom);
9097: }
9098: if (!defined($homeserver)) {
9099: if ($cdom =~ /^$match_domain$/) {
9100: $homeserver = &domain($cdom,'primary');
9101: }
9102: }
1.1065 raeburn 9103: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9104: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9105: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9106: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9107: }
9108:
1.1172.2.118. .20(raeb 9109:-21): sub auto_validate_inst_crosslist {
9110:-21): my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9111:-21): my ($homeserver,$response);
9112:-21): if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9113:-21): $homeserver = &homeserver($cnum,$cdom);
9114:-21): }
9115:-21): if (!defined($homeserver)) {
9116:-21): if ($cdom =~ /^$match_domain$/) {
9117:-21): $homeserver = &domain($cdom,'primary');
9118:-21): }
9119:-21): }
9120:-21): unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9121:-21): $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9122:-21): &escape($instcode).':'.&escape($inst_xlist).':'.
9123:-21): &escape($coowner),$homeserver);
9124:-21): }
9125:-21): return $response;
9126:-21): }
9127:-21):
1.506 raeburn 9128: sub auto_create_password {
1.873 raeburn 9129: my ($cnum,$cdom,$authparam,$udom) = @_;
9130: my ($homeserver,$response);
1.506 raeburn 9131: my $create_passwd = 0;
9132: my $authchk = '';
1.873 raeburn 9133: if ($udom =~ /^$match_domain$/) {
9134: $homeserver = &domain($udom,'primary');
9135: }
9136: if ($homeserver eq '') {
9137: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9138: $homeserver = &homeserver($cnum,$cdom);
9139: }
9140: }
9141: if ($homeserver eq '') {
9142: $authchk = 'nodomain';
1.506 raeburn 9143: } else {
1.873 raeburn 9144: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9145: if ($response eq 'refused') {
9146: $authchk = 'refused';
9147: } else {
1.901 albertel 9148: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9149: }
1.506 raeburn 9150: }
9151: return ($authparam,$create_passwd,$authchk);
9152: }
9153:
1.706 raeburn 9154: sub auto_photo_permission {
9155: my ($cnum,$cdom,$students) = @_;
9156: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9157: my ($outcome,$perm_reqd,$conditions) =
9158: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9159: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9160: return (undef,undef);
9161: }
1.706 raeburn 9162: return ($outcome,$perm_reqd,$conditions);
9163: }
9164:
9165: sub auto_checkphotos {
9166: my ($uname,$udom,$pid) = @_;
9167: my $homeserver = &homeserver($uname,$udom);
9168: my ($result,$resulttype);
9169: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9170: &escape($uname).':'.&escape($pid),
9171: $homeserver));
1.709 albertel 9172: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9173: return (undef,undef);
9174: }
1.706 raeburn 9175: if ($outcome) {
9176: ($result,$resulttype) = split(/:/,$outcome);
9177: }
9178: return ($result,$resulttype);
9179: }
9180:
9181: sub auto_photochoice {
9182: my ($cnum,$cdom) = @_;
9183: my $homeserver = &homeserver($cnum,$cdom);
9184: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9185: &escape($cdom),
9186: $homeserver)));
1.709 albertel 9187: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9188: return (undef,undef);
9189: }
1.706 raeburn 9190: return ($update,$comment);
9191: }
9192:
9193: sub auto_photoupdate {
9194: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9195: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9196: my $host=&hostname($homeserver);
1.706 raeburn 9197: my $cmd = '';
9198: my $maxtries = 1;
1.800 albertel 9199: foreach my $affiliate (keys(%{$affiliatesref})) {
9200: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9201: }
9202: $cmd =~ s/%%$//;
9203: $cmd = &escape($cmd);
9204: my $query = 'institutionalphotos';
9205: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9206: unless ($queryid=~/^\Q$host\E\_/) {
9207: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9208: return 'error: '.$queryid;
9209: }
9210: my $reply = &get_query_reply($queryid);
9211: my $tries = 1;
9212: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9213: $reply = &get_query_reply($queryid);
9214: $tries ++;
9215: }
9216: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9217: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9218: } else {
9219: my @responses = split(/:/,$reply);
9220: my $outcome = shift(@responses);
9221: foreach my $item (@responses) {
9222: my ($key,$value) = split(/=/,$item);
9223: $$photo{$key} = $value;
9224: }
9225: return $outcome;
9226: }
9227: return 'error';
9228: }
9229:
1.521 raeburn 9230: sub auto_instcode_format {
1.793 albertel 9231: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9232: $cat_order) = @_;
1.521 raeburn 9233: my $courses = '';
1.772 raeburn 9234: my @homeservers;
1.521 raeburn 9235: if ($caller eq 'global') {
1.841 albertel 9236: my %servers = &get_servers($codedom,'library');
9237: foreach my $tryserver (keys(%servers)) {
9238: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9239: push(@homeservers,$tryserver);
9240: }
1.584 raeburn 9241: }
1.1022 raeburn 9242: } elsif ($caller eq 'requests') {
9243: if ($codedom =~ /^$match_domain$/) {
9244: my $chome = &domain($codedom,'primary');
9245: unless ($chome eq 'no_host') {
9246: push(@homeservers,$chome);
9247: }
9248: }
1.521 raeburn 9249: } else {
1.772 raeburn 9250: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9251: }
1.793 albertel 9252: foreach my $code (keys(%{$instcodes})) {
9253: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9254: }
9255: chop($courses);
1.772 raeburn 9256: my $ok_response = 0;
9257: my $response;
9258: while (@homeservers > 0 && $ok_response == 0) {
9259: my $server = shift(@homeservers);
9260: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9261: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9262: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9263: split(/:/,$response);
1.772 raeburn 9264: %{$codes} = (%{$codes},&str2hash($codes_str));
9265: push(@{$codetitles},&str2array($codetitles_str));
9266: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9267: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9268: $ok_response = 1;
9269: }
9270: }
9271: if ($ok_response) {
1.521 raeburn 9272: return 'ok';
1.772 raeburn 9273: } else {
9274: return $response;
1.521 raeburn 9275: }
9276: }
9277:
1.792 raeburn 9278: sub auto_instcode_defaults {
9279: my ($domain,$returnhash,$code_order) = @_;
9280: my @homeservers;
1.841 albertel 9281:
9282: my %servers = &get_servers($domain,'library');
9283: foreach my $tryserver (keys(%servers)) {
9284: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9285: push(@homeservers,$tryserver);
9286: }
1.792 raeburn 9287: }
1.841 albertel 9288:
1.792 raeburn 9289: my $response;
1.841 albertel 9290: foreach my $server (@homeservers) {
1.792 raeburn 9291: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9292: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9293:
9294: foreach my $pair (split(/\&/,$response)) {
9295: my ($name,$value)=split(/\=/,$pair);
9296: if ($name eq 'code_order') {
9297: @{$code_order} = split(/\&/,&unescape($value));
9298: } else {
9299: $returnhash->{&unescape($name)}=&unescape($value);
9300: }
9301: }
9302: return 'ok';
1.792 raeburn 9303: }
1.841 albertel 9304:
9305: return $response;
1.1003 raeburn 9306: }
9307:
9308: sub auto_possible_instcodes {
1.1007 raeburn 9309: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9310: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9311: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9312: return;
9313: }
1.1003 raeburn 9314: my (@homeservers,$uhome);
9315: if (defined(&domain($domain,'primary'))) {
9316: $uhome=&domain($domain,'primary');
9317: push(@homeservers,&domain($domain,'primary'));
9318: } else {
9319: my %servers = &get_servers($domain,'library');
9320: foreach my $tryserver (keys(%servers)) {
9321: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9322: push(@homeservers,$tryserver);
9323: }
9324: }
9325: }
9326: my $response;
9327: foreach my $server (@homeservers) {
9328: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9329: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9330: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9331: split(':',$response);
9332: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9333: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9334: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9335: my ($name,$value)=split('=',$item);
9336: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9337: }
9338: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9339: my ($name,$value)=split('=',$item);
9340: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9341: }
9342: return 'ok';
9343: }
9344: return $response;
9345: }
1.792 raeburn 9346:
1.1010 raeburn 9347: sub auto_courserequest_checks {
9348: my ($dom) = @_;
1.1020 raeburn 9349: my ($homeserver,%validations);
9350: if ($dom =~ /^$match_domain$/) {
9351: $homeserver = &domain($dom,'primary');
9352: }
9353: unless ($homeserver eq 'no_host') {
9354: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9355: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9356: my @items = split(/&/,$response);
9357: foreach my $item (@items) {
9358: my ($key,$value) = split('=',$item);
9359: $validations{&unescape($key)} = &thaw_unescape($value);
9360: }
9361: }
9362: }
1.1010 raeburn 9363: return %validations;
9364: }
9365:
1.1020 raeburn 9366: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9367: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9368: my ($homeserver,$response);
9369: if ($dom =~ /^$match_domain$/) {
9370: $homeserver = &domain($dom,'primary');
9371: }
1.1172.2.43 raeburn 9372: unless ($homeserver eq 'no_host') {
9373: my $customdata;
9374: if (ref($custominfo) eq 'HASH') {
9375: $customdata = &freeze_escape($custominfo);
9376: }
1.1020 raeburn 9377: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9378: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9379: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9380: $customdata,$homeserver));
1.1020 raeburn 9381: }
9382: return $response;
9383: }
9384:
1.777 albertel 9385: sub auto_validate_class_sec {
1.918 raeburn 9386: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9387: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9388: my $ownerlist;
9389: if (ref($owners) eq 'ARRAY') {
9390: $ownerlist = join(',',@{$owners});
9391: } else {
9392: $ownerlist = $owners;
9393: }
1.773 raeburn 9394: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9395: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9396: return $response;
9397: }
9398:
1.1172.2.118. .20(raeb 9399:-21): sub auto_instsec_reformat {
9400:-21): my ($cdom,$action,$instsecref) = @_;
9401:-21): return unless(($action eq 'clutter') || ($action eq 'declutter'));
9402:-21): my @homeservers;
9403:-21): if (defined(&domain($cdom,'primary'))) {
9404:-21): push(@homeservers,&domain($cdom,'primary'));
9405:-21): } else {
9406:-21): my %servers = &get_servers($cdom,'library');
9407:-21): foreach my $tryserver (keys(%servers)) {
9408:-21): if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9409:-21): push(@homeservers,$tryserver);
9410:-21): }
9411:-21): }
9412:-21): }
9413:-21): my $response;
9414:-21): my %reformatted = %{$instsecref};
9415:-21): foreach my $server (@homeservers) {
9416:-21): if (ref($instsecref) eq 'HASH') {
9417:-21): my $info = &freeze_escape($instsecref);
9418:-21): my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9419:-21): $action.':'.$info,$server);
9420:-21): next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9421:-21): my @items = split(/&/,$response);
9422:-21): foreach my $item (@items) {
9423:-21): my ($key,$value) = split(/=/,$item);
9424:-21): $reformatted{&unescape($key)} = &thaw_unescape($value);
9425:-21): }
9426:-21): }
9427:-21): }
9428:-21): return %reformatted;
9429:-21): }
9430:-21):
1.1172.2.94 raeburn 9431: sub auto_validate_instclasses {
9432: my ($cdom,$cnum,$owners,$classesref) = @_;
9433: my ($homeserver,%validations);
9434: $homeserver = &homeserver($cnum,$cdom);
9435: unless ($homeserver eq 'no_host') {
9436: my $ownerlist;
9437: if (ref($owners) eq 'ARRAY') {
9438: $ownerlist = join(',',@{$owners});
9439: } else {
9440: $ownerlist = $owners;
9441: }
9442: if (ref($classesref) eq 'HASH') {
9443: my $classes = &freeze_escape($classesref);
9444: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9445: ':'.$cdom.':'.$classes,$homeserver);
9446: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9447: my @items = split(/&/,$response);
9448: foreach my $item (@items) {
9449: my ($key,$value) = split('=',$item);
9450: $validations{&unescape($key)} = &thaw_unescape($value);
9451: }
9452: }
9453: }
9454: }
9455: return %validations;
9456: }
9457:
1.1172.2.38 raeburn 9458: sub auto_crsreq_update {
9459: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9460: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9461: my ($homeserver,%crsreqresponse);
9462: if ($cdom =~ /^$match_domain$/) {
9463: $homeserver = &domain($cdom,'primary');
9464: }
9465: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9466: my $info;
9467: if (ref($inbound) eq 'HASH') {
9468: $info = &freeze_escape($inbound);
9469: }
9470: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9471: ':'.&escape($action).':'.&escape($ownername).':'.
9472: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9473: &escape($title).':'.&escape($code).':'.
9474: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9475: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9476: my @items = split(/&/,$response);
9477: foreach my $item (@items) {
9478: my ($key,$value) = split('=',$item);
9479: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9480: }
9481: }
9482: }
9483: return \%crsreqresponse;
9484: }
9485:
1.1172.2.78 raeburn 9486: sub auto_export_grades {
9487: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9488: my ($homeserver,%exportresponse);
9489: if ($cdom =~ /^$match_domain$/) {
9490: $homeserver = &domain($cdom,'primary');
9491: }
9492: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9493: my $info;
9494: if (ref($inforef) eq 'HASH') {
9495: $info = &freeze_escape($inforef);
9496: }
9497: if (ref($gradesref) eq 'HASH') {
9498: my $grades = &freeze_escape($gradesref);
9499: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9500: $info.':'.$grades,$homeserver);
9501: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9502: my @items = split(/&/,$response);
9503: foreach my $item (@items) {
9504: my ($key,$value) = split('=',$item);
9505: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9506: }
9507: }
9508: }
9509: }
9510: return \%exportresponse;
9511: }
9512:
1.1172.2.68 raeburn 9513: sub check_instcode_cloning {
9514: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9515: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9516: return;
9517: }
9518: my $canclone;
9519: if (@{$code_order} > 0) {
9520: my $instcoderegexp ='^';
9521: my @clonecodes = split(/\&/,$cloner);
9522: foreach my $item (@{$code_order}) {
9523: if (grep(/^\Q$item\E=/,@clonecodes)) {
9524: foreach my $pair (@clonecodes) {
9525: my ($key,$val) = split(/\=/,$pair,2);
9526: $val = &unescape($val);
9527: if ($key eq $item) {
9528: $instcoderegexp .= '('.$val.')';
9529: last;
9530: }
9531: }
9532: } else {
9533: $instcoderegexp .= $codedefaults->{$item};
9534: }
9535: }
9536: $instcoderegexp .= '$';
9537: my (@from,@to);
9538: eval {
9539: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9540: (@to) = ($clonetocode =~ /$instcoderegexp/);
9541: };
9542: if ((@from > 0) && (@to > 0)) {
9543: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9544: if (!@diffs) {
9545: $canclone = 1;
9546: }
9547: }
9548: }
9549: return $canclone;
9550: }
9551:
9552: sub default_instcode_cloning {
9553: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9554: my (%codedefaults,@code_order,$canclone);
9555: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9556: %codedefaults = %{$codedefaultsref};
9557: @code_order = @{$codeorderref};
9558: } elsif ($clonedom) {
9559: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9560: }
9561: if (($domdefclone) && (@code_order)) {
9562: my @clonecodes = split(/\+/,$domdefclone);
9563: my $instcoderegexp ='^';
9564: foreach my $item (@code_order) {
9565: if (grep(/^\Q$item\E$/,@clonecodes)) {
9566: $instcoderegexp .= '('.$codedefaults{$item}.')';
9567: } else {
9568: $instcoderegexp .= $codedefaults{$item};
9569: }
9570: }
9571: $instcoderegexp .= '$';
9572: my (@from,@to);
9573: eval {
9574: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9575: (@to) = ($clonetocode =~ /$instcoderegexp/);
9576: };
9577: if ((@from > 0) && (@to > 0)) {
9578: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9579: if (!@diffs) {
9580: $canclone = 1;
9581: }
9582: }
9583: }
9584: return $canclone;
9585: }
9586:
1.679 raeburn 9587: # ------------------------------------------------------- Course Group routines
9588:
9589: sub get_coursegroups {
1.809 raeburn 9590: my ($cdom,$cnum,$group,$namespace) = @_;
9591: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9592: }
9593:
1.679 raeburn 9594: sub modify_coursegroup {
9595: my ($cdom,$cnum,$groupsettings) = @_;
9596: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9597: }
9598:
1.809 raeburn 9599: sub toggle_coursegroup_status {
9600: my ($cdom,$cnum,$group,$action) = @_;
9601: my ($from_namespace,$to_namespace);
9602: if ($action eq 'delete') {
9603: $from_namespace = 'coursegroups';
9604: $to_namespace = 'deleted_groups';
9605: } else {
9606: $from_namespace = 'deleted_groups';
9607: $to_namespace = 'coursegroups';
9608: }
9609: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9610: if (my $tmp = &error(%curr_group)) {
9611: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9612: return ('read error',$tmp);
9613: } else {
9614: my %savedsettings = %curr_group;
1.809 raeburn 9615: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9616: my $deloutcome;
9617: if ($result eq 'ok') {
1.809 raeburn 9618: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9619: } else {
9620: return ('write error',$result);
9621: }
9622: if ($deloutcome eq 'ok') {
9623: return 'ok';
9624: } else {
9625: return ('delete error',$deloutcome);
9626: }
9627: }
9628: }
9629:
1.679 raeburn 9630: sub modify_group_roles {
1.957 raeburn 9631: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9632: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9633: my $role = 'gr/'.&escape($userprivs);
9634: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9635: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9636: if ($result eq 'ok') {
9637: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9638: }
1.679 raeburn 9639: return $result;
9640: }
9641:
9642: sub modify_coursegroup_membership {
9643: my ($cdom,$cnum,$membership) = @_;
9644: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9645: return $result;
9646: }
9647:
1.682 raeburn 9648: sub get_active_groups {
9649: my ($udom,$uname,$cdom,$cnum) = @_;
9650: my $now = time;
9651: my %groups = ();
9652: foreach my $key (keys(%env)) {
1.811 albertel 9653: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9654: my ($start,$end) = split(/\./,$env{$key});
9655: if (($end!=0) && ($end<$now)) { next; }
9656: if (($start!=0) && ($start>$now)) { next; }
9657: if ($1 eq $cdom && $2 eq $cnum) {
9658: $groups{$3} = $env{$key} ;
9659: }
9660: }
9661: }
9662: return %groups;
9663: }
9664:
1.683 raeburn 9665: sub get_group_membership {
9666: my ($cdom,$cnum,$group) = @_;
9667: return(&dump('groupmembership',$cdom,$cnum,$group));
9668: }
9669:
9670: sub get_users_groups {
9671: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9672: my @usersgroups;
1.683 raeburn 9673: my $cachetime=1800;
9674:
9675: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9676: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9677: if (defined($cached)) {
1.734 albertel 9678: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9679: } else {
9680: $grouplist = '';
1.816 raeburn 9681: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9682: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9683: my $access_end = $env{'course.'.$courseid.
9684: '.default_enrollment_end_date'};
9685: my $now = time;
9686: foreach my $key (keys(%roleshash)) {
9687: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9688: my $group = $1;
9689: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9690: my $start = $2;
9691: my $end = $1;
9692: if ($start == -1) { next; } # deleted from group
9693: if (($start!=0) && ($start>$now)) { next; }
9694: if (($end!=0) && ($end<$now)) {
9695: if ($access_end && $access_end < $now) {
9696: if ($access_end - $end < 86400) {
9697: push(@usersgroups,$group);
1.733 raeburn 9698: }
9699: }
1.817 raeburn 9700: next;
1.733 raeburn 9701: }
1.817 raeburn 9702: push(@usersgroups,$group);
1.683 raeburn 9703: }
9704: }
9705: }
1.817 raeburn 9706: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9707: $grouplist = join(':',@usersgroups);
9708: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9709: }
1.733 raeburn 9710: return @usersgroups;
1.683 raeburn 9711: }
9712:
9713: sub devalidate_getgroups_cache {
9714: my ($udom,$uname,$cdom,$cnum)=@_;
9715: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9716:
1.683 raeburn 9717: my $hashid="$udom:$uname:$courseid";
9718: &devalidate_cache_new('getgroups',$hashid);
9719: }
9720:
1.12 www 9721: # ------------------------------------------------------------------ Plain Text
9722:
9723: sub plaintext {
1.988 raeburn 9724: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9725: if ($short =~ m{^cr/}) {
1.758 albertel 9726: return (split('/',$short))[-1];
9727: }
1.742 raeburn 9728: if (!defined($cid)) {
9729: $cid = $env{'request.course.id'};
9730: }
9731: my %rolenames = (
1.1008 raeburn 9732: Course => 'std',
9733: Community => 'alt1',
1.742 raeburn 9734: );
1.1037 raeburn 9735: if ($cid ne '') {
9736: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9737: unless ($forcedefault) {
9738: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9739: &Apache::lonlocal::mt_escape(\$roletext);
9740: return &Apache::lonlocal::mt($roletext);
9741: }
9742: }
9743: }
9744: if ((defined($type)) && (defined($rolenames{$type})) &&
9745: (defined($rolenames{$type})) &&
9746: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9747: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9748: } elsif ($cid ne '') {
9749: my $crstype = $env{'course.'.$cid.'.type'};
9750: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9751: (defined($prp{$short}{$rolenames{$crstype}}))) {
9752: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9753: }
1.742 raeburn 9754: }
1.1037 raeburn 9755: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9756: }
9757:
9758: # ----------------------------------------------------------------- Assign Role
9759:
9760: sub assignrole {
1.957 raeburn 9761: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9762: $context)=@_;
1.21 www 9763: my $mrole;
9764: if ($role =~ /^cr\//) {
1.393 www 9765: my $cwosec=$url;
1.811 albertel 9766: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9767: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9768: my $refused = 1;
9769: if ($context eq 'requestcourses') {
9770: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9771: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9772: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9773: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9774: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9775: if ($crsenv{'internal.courseowner'} eq
9776: $env{'user.name'}.':'.$env{'user.domain'}) {
9777: $refused = '';
9778: }
9779: }
9780: }
9781: }
9782: }
9783: if ($refused) {
9784: &logthis('Refused custom assignrole: '.
9785: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9786: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9787: return 'refused';
9788: }
1.104 www 9789: }
1.21 www 9790: $mrole='cr';
1.678 raeburn 9791: } elsif ($role =~ /^gr\//) {
9792: my $cwogrp=$url;
1.811 albertel 9793: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9794: unless (&allowed('mdg',$cwogrp)) {
9795: &logthis('Refused group assignrole: '.
9796: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9797: $env{'user.name'}.' at '.$env{'user.domain'});
9798: return 'refused';
9799: }
9800: $mrole='gr';
1.21 www 9801: } else {
1.82 www 9802: my $cwosec=$url;
1.811 albertel 9803: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9804: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9805: my $refused;
9806: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9807: if (!(&allowed('c'.$role,$url))) {
9808: $refused = 1;
9809: }
9810: } else {
9811: $refused = 1;
9812: }
1.947 raeburn 9813: if ($refused) {
1.1045 raeburn 9814: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9815: if (!$selfenroll && $context eq 'course') {
9816: my %crsenv;
9817: if ($role eq 'cc' || $role eq 'co') {
9818: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9819: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9820: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9821: if ($crsenv{'internal.courseowner'} eq
9822: $env{'user.name'}.':'.$env{'user.domain'}) {
9823: $refused = '';
9824: }
9825: }
9826: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9827: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9828: if ($crsenv{'internal.courseowner'} eq
9829: $env{'user.name'}.':'.$env{'user.domain'}) {
9830: $refused = '';
9831: }
9832: }
9833: }
9834: }
9835: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9836: $refused = '';
1.1017 raeburn 9837: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9838: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9839: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9840: my $wrongcc;
9841: if ($cnum =~ /^$match_community$/) {
9842: $wrongcc = 1 if ($role eq 'cc');
9843: } else {
9844: $wrongcc = 1 if ($role eq 'co');
9845: }
9846: unless ($wrongcc) {
9847: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9848: if ($crsenv{'internal.courseowner'} eq
9849: $env{'user.name'}.':'.$env{'user.domain'}) {
9850: $refused = '';
9851: }
1.1017 raeburn 9852: }
9853: }
1.1172.2.9 raeburn 9854: } elsif ($context eq 'requestauthor') {
9855: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9856: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9857: if ($env{'environment.requestauthor'} eq 'automatic') {
9858: $refused = '';
9859: } else {
9860: my %domdefaults = &get_domain_defaults($udom);
9861: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9862: my $checkbystatus;
9863: if ($env{'user.adv'}) {
9864: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9865: if ($disposition eq 'automatic') {
9866: $refused = '';
9867: } elsif ($disposition eq '') {
9868: $checkbystatus = 1;
9869: }
9870: } else {
9871: $checkbystatus = 1;
9872: }
9873: if ($checkbystatus) {
9874: if ($env{'environment.inststatus'}) {
9875: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9876: foreach my $type (@inststatuses) {
9877: if (($type ne '') &&
9878: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9879: $refused = '';
9880: }
9881: }
9882: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9883: $refused = '';
9884: }
9885: }
9886: }
9887: }
9888: }
1.1017 raeburn 9889: }
9890: if ($refused) {
1.947 raeburn 9891: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9892: ' '.$role.' '.$end.' '.$start.' by '.
9893: $env{'user.name'}.' at '.$env{'user.domain'});
9894: return 'refused';
9895: }
1.932 raeburn 9896: }
1.1131 raeburn 9897: } elsif ($role eq 'au') {
9898: if ($url ne '/'.$udom.'/') {
9899: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9900: ' to assign author role for '.$uname.':'.$udom.
9901: ' in domain: '.$url.' refused (wrong domain).');
9902: return 'refused';
9903: }
1.104 www 9904: }
1.21 www 9905: $mrole=$role;
9906: }
1.620 albertel 9907: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9908: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9909: if ($end) { $command.='_'.$end; }
1.21 www 9910: if ($start) {
9911: if ($end) {
1.81 www 9912: $command.='_'.$start;
1.21 www 9913: } else {
1.81 www 9914: $command.='_0_'.$start;
1.21 www 9915: }
9916: }
1.739 raeburn 9917: my $origstart = $start;
9918: my $origend = $end;
1.957 raeburn 9919: my $delflag;
1.357 www 9920: # actually delete
9921: if ($deleteflag) {
1.373 www 9922: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9923: # modify command to delete the role
1.620 albertel 9924: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9925: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9926: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9927: # set start and finish to negative values for userrolelog
9928: $start=-1;
9929: $end=-1;
1.957 raeburn 9930: $delflag = 1;
1.357 www 9931: }
9932: }
9933: # send command
1.349 www 9934: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9935: # log new user role if status is ok
1.349 www 9936: if ($answer eq 'ok') {
1.663 raeburn 9937: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9938: if (($role eq 'cc') || ($role eq 'in') ||
9939: ($role eq 'ep') || ($role eq 'ad') ||
9940: ($role eq 'ta') || ($role eq 'st') ||
9941: ($role=~/^cr/) || ($role eq 'gr') ||
9942: ($role eq 'co')) {
1.1172.2.13 raeburn 9943: # for course roles, perform group memberships changes triggered by role change.
9944: unless ($role =~ /^gr/) {
9945: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9946: $origstart,$selfenroll,$context);
9947: }
1.1172.2.9 raeburn 9948: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9949: $selfenroll,$context);
9950: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9951: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9952: ($role eq 'da')) {
1.1172.2.9 raeburn 9953: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9954: $context);
9955: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9956: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9957: $context);
9958: }
1.1053 raeburn 9959: if ($role eq 'cc') {
9960: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9961: }
1.349 www 9962: }
9963: return $answer;
1.169 harris41 9964: }
9965:
1.1053 raeburn 9966: sub autoupdate_coowners {
9967: my ($url,$end,$start,$uname,$udom) = @_;
9968: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9969: if (($cdom ne '') && ($cnum ne '')) {
9970: my $now = time;
9971: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9972: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9973: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9974: my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.118. .20(raeb 9975:-21): my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 9976: if ($instcode ne '') {
1.1056 raeburn 9977: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9978: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9979: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9980: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.118. .20(raeb 9981:-21): unless ($result eq 'valid') {
9982:-21): if ($xlists ne '') {
9983:-21): foreach my $xlist (split(',',$xlists)) {
9984:-21): my ($inst_crosslist,$lcsec) = split(':',$xlist);
9985:-21): $result =
9986:-21): &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
9987:-21): $inst_crosslist,$uname.':'.$udom);
9988:-21): last if ($result eq 'valid');
9989:-21): }
9990:-21): }
9991:-21): }
1.1056 raeburn 9992: if ($result eq 'valid') {
9993: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9994: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9995: push(@newcoowners,$coowner);
9996: }
9997: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9998: push(@newcoowners,$uname.':'.$udom);
9999: }
10000: @newcoowners = sort(@newcoowners);
10001: } else {
10002: push(@newcoowners,$uname.':'.$udom);
10003: }
1.1172.2.118. .20(raeb 10004:-21): } elsif ($coursehash{'internal.co-owners'}) {
10005:-21): foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10006:-21): unless ($coowner eq $uname.':'.$udom) {
10007:-21): push(@newcoowners,$coowner);
1.1053 raeburn 10008: }
10009: }
1.1172.2.118. .20(raeb 10010:-21): unless (@newcoowners > 0) {
10011:-21): $delcoowners = 1;
10012:-21): $coowners = '';
10013:-21): }
1.1053 raeburn 10014: }
10015: if (@newcoowners || $delcoowners) {
10016: &store_coowners($cdom,$cnum,$coursehash{'home'},
10017: $delcoowners,@newcoowners);
10018: }
10019: }
10020: }
10021: }
10022: }
10023: }
10024: }
10025:
10026: sub store_coowners {
10027: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10028: my $cid = $cdom.'_'.$cnum;
10029: my ($coowners,$delresult,$putresult);
10030: if (@newcoowners) {
10031: $coowners = join(',',@newcoowners);
10032: my %coownershash = (
10033: 'internal.co-owners' => $coowners,
10034: );
10035: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10036: if ($putresult eq 'ok') {
10037: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10038: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10039: }
10040: }
10041: }
10042: if ($delcoowners) {
10043: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10044: if ($delresult eq 'ok') {
10045: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10046: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10047: }
10048: }
10049: }
10050: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10051: my %crsinfo =
10052: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10053: if (ref($crsinfo{$cid}) eq 'HASH') {
10054: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10055: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10056: }
10057: }
10058: }
10059:
1.169 harris41 10060: # -------------------------------------------------- Modify user authentication
1.197 www 10061: # Overrides without validation
10062:
1.169 harris41 10063: sub modifyuserauth {
10064: my ($udom,$uname,$umode,$upass)=@_;
10065: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 10066: my $allowed;
10067: if (&allowed('mau',$udom)) {
10068: $allowed = 1;
10069: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10070: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10071: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10072: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10073: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10074: if (($cdom ne '') && ($cnum ne '')) {
10075: my $is_owner = &is_course_owner($cdom,$cnum);
10076: if ($is_owner) {
10077: $allowed = 1;
10078: }
10079: }
10080: }
10081: unless ($allowed) { return 'refused'; }
1.197 www 10082: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10083: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10084: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10085: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10086: &escape($upass),$uhome);
1.1172.2.118. .14(raeb 10087:-21): my $ip = &get_requestor_ip();
1.620 albertel 10088: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10089: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.118. .14(raeb 10090:-21): '(Remote '.$ip.'): '.$reply);
1.197 www 10091: &log($udom,,$uname,$uhome,
1.620 albertel 10092: 'Authentication changed by '.$env{'user.domain'}.', '.
10093: $env{'user.name'}.', '.$umode.
1.1172.2.118. .14(raeb 10094:-21): '(Remote '.$ip.'): '.$reply);
1.169 harris41 10095: unless ($reply eq 'ok') {
1.197 www 10096: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10097: return 'error: '.$reply;
10098: }
1.170 harris41 10099: return 'ok';
1.80 www 10100: }
10101:
1.81 www 10102: # --------------------------------------------------------------- Modify a user
1.80 www 10103:
1.81 www 10104: sub modifyuser {
1.206 matthew 10105: my ($udom, $uname, $uid,
10106: $umode, $upass, $first,
10107: $middle, $last, $gene,
1.1058 raeburn 10108: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10109: $udom= &LONCAPA::clean_domain($udom);
10110: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10111: my $showcandelete = 'none';
10112: if (ref($candelete) eq 'ARRAY') {
10113: if (@{$candelete} > 0) {
10114: $showcandelete = join(', ',@{$candelete});
10115: }
10116: }
1.81 www 10117: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10118: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10119: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10120: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10121: ' desiredhome not specified').
1.620 albertel 10122: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10123: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10124: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10125: my $newuser;
10126: if ($uhome eq 'no_host') {
10127: $newuser = 1;
10128: }
1.80 www 10129: # ----------------------------------------------------------------- Create User
1.406 albertel 10130: if (($uhome eq 'no_host') &&
10131: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 10132: my $unhome='';
1.844 albertel 10133: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10134: $unhome = $desiredhome;
1.620 albertel 10135: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10136: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10137: } else { # load balancing routine for determining $unhome
1.81 www 10138: my $loadm=10000000;
1.841 albertel 10139: my %servers = &get_servers($udom,'library');
10140: foreach my $tryserver (keys(%servers)) {
10141: my $answer=reply('load',$tryserver);
10142: if (($answer=~/\d+/) && ($answer<$loadm)) {
10143: $loadm=$answer;
10144: $unhome=$tryserver;
10145: }
1.80 www 10146: }
10147: }
10148: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10149: return 'error: unable to find a home server for '.$uname.
10150: ' in domain '.$udom;
1.80 www 10151: }
10152: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10153: &escape($upass),$unhome);
10154: unless ($reply eq 'ok') {
10155: return 'error: '.$reply;
10156: }
1.230 stredwic 10157: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10158: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10159: return 'error: unable verify users home machine.';
1.80 www 10160: }
1.209 matthew 10161: } # End of creation of new user
1.80 www 10162: # ---------------------------------------------------------------------- Add ID
10163: if ($uid) {
10164: $uid=~tr/A-Z/a-z/;
10165: my %uidhash=&idrget($udom,$uname);
1.196 www 10166: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10167: && (!$forceid)) {
1.80 www 10168: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10169: return 'error: user id "'.$uid.'" does not match '.
10170: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10171: }
10172: } else {
10173: &idput($udom,($uname => $uid));
10174: }
10175: }
10176: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10177: my @tmp=&get('environment',
1.899 raeburn 10178: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10179: 'permanentemail','inststatus'],
1.134 albertel 10180: $udom,$uname);
1.1075 raeburn 10181: my (%names,%oldnames);
1.313 matthew 10182: if ($tmp[0] =~ m/^error:.*/) {
10183: %names=();
10184: } else {
10185: %names = @tmp;
1.1075 raeburn 10186: %oldnames = %names;
1.313 matthew 10187: }
1.388 www 10188: #
1.1058 raeburn 10189: # If name, email and/or uid are blank (e.g., because an uploaded file
10190: # of users did not contain them), do not overwrite existing values
10191: # unless field is in $candelete array ref.
10192: #
10193:
10194: my @fields = ('firstname','middlename','lastname','generation',
10195: 'permanentemail','id');
10196: my %newvalues;
10197: if (ref($candelete) eq 'ARRAY') {
10198: foreach my $field (@fields) {
10199: if (grep(/^\Q$field\E$/,@{$candelete})) {
10200: if ($field eq 'firstname') {
10201: $names{$field} = $first;
10202: } elsif ($field eq 'middlename') {
10203: $names{$field} = $middle;
10204: } elsif ($field eq 'lastname') {
10205: $names{$field} = $last;
10206: } elsif ($field eq 'generation') {
10207: $names{$field} = $gene;
10208: } elsif ($field eq 'permanentemail') {
10209: $names{$field} = $email;
10210: } elsif ($field eq 'id') {
10211: $names{$field} = $uid;
10212: }
10213: }
10214: }
10215: }
1.388 www 10216: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10217: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10218: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10219: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10220: if ($email) {
10221: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10222: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10223: }
1.899 raeburn 10224: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10225: if (defined($inststatus)) {
10226: $names{'inststatus'} = '';
10227: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10228: if (ref($usertypes) eq 'HASH') {
10229: my @okstatuses;
10230: foreach my $item (split(/:/,$inststatus)) {
10231: if (defined($usertypes->{$item})) {
10232: push(@okstatuses,$item);
10233: }
10234: }
10235: if (@okstatuses) {
10236: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10237: }
10238: }
10239: }
1.1075 raeburn 10240: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10241: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10242: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10243: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10244: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10245: } else {
10246: $logmsg .= ' during self creation';
10247: }
1.1075 raeburn 10248: my $changed;
10249: if ($newuser) {
10250: $changed = 1;
10251: } else {
10252: foreach my $field (@fields) {
10253: if ($names{$field} ne $oldnames{$field}) {
10254: $changed = 1;
10255: last;
10256: }
10257: }
10258: }
10259: unless ($changed) {
10260: $logmsg = 'No changes in user information needed for: '.$logmsg;
10261: &logthis($logmsg);
10262: return 'ok';
10263: }
10264: my $reply = &put('environment', \%names, $udom,$uname);
10265: if ($reply ne 'ok') {
10266: return 'error: '.$reply;
10267: }
1.1087 raeburn 10268: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10269: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10270: }
1.1075 raeburn 10271: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10272: &devalidate_cache_new('namescache',$uname.':'.$udom);
10273: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10274: &logthis($logmsg);
1.134 albertel 10275: return 'ok';
1.80 www 10276: }
10277:
1.81 www 10278: # -------------------------------------------------------------- Modify student
1.80 www 10279:
1.81 www 10280: sub modifystudent {
10281: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10282: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10283: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10284: if (!$cid) {
1.620 albertel 10285: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10286: return 'not_in_class';
10287: }
1.80 www 10288: }
10289: # --------------------------------------------------------------- Make the user
1.81 www 10290: my $reply=&modifyuser
1.209 matthew 10291: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10292: $desiredhome,$email,$inststatus);
1.80 www 10293: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10294: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10295: # student's environment
1.297 matthew 10296: $uid = undef if (!$forceid);
1.455 albertel 10297: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10298: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10299: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10300: return $reply;
10301: }
10302:
10303: sub modify_student_enrollment {
1.1172.2.23 raeburn 10304: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10305: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10306: my ($cdom,$cnum,$chome);
10307: if (!$cid) {
1.620 albertel 10308: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10309: return 'not_in_class';
10310: }
1.620 albertel 10311: $cdom=$env{'course.'.$cid.'.domain'};
10312: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10313: } else {
10314: ($cdom,$cnum)=split(/_/,$cid);
10315: }
1.620 albertel 10316: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10317: if (!$chome) {
1.457 raeburn 10318: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10319: }
1.455 albertel 10320: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10321: # Make sure the user exists
1.81 www 10322: my $uhome=&homeserver($uname,$udom);
10323: if (($uhome eq '') || ($uhome eq 'no_host')) {
10324: return 'error: no such user';
10325: }
1.297 matthew 10326: # Get student data if we were not given enough information
10327: if (!defined($first) || $first eq '' ||
10328: !defined($last) || $last eq '' ||
10329: !defined($uid) || $uid eq '' ||
10330: !defined($middle) || $middle eq '' ||
10331: !defined($gene) || $gene eq '') {
1.294 matthew 10332: # They did not supply us with enough data to enroll the student, so
10333: # we need to pick up more information.
1.297 matthew 10334: my %tmp = &get('environment',
1.294 matthew 10335: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10336: ,$udom,$uname);
10337:
1.800 albertel 10338: #foreach my $key (keys(%tmp)) {
10339: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10340: #}
1.294 matthew 10341: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10342: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10343: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10344: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10345: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10346: }
1.556 albertel 10347: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10348: my $user = "$uname:$udom";
10349: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10350: my $reply=cput('classlist',
1.1148 raeburn 10351: {$user =>
1.1172.2.76 raeburn 10352: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10353: $cdom,$cnum);
1.1148 raeburn 10354: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10355: &devalidate_getsection_cache($udom,$uname,$cid);
10356: } else {
1.81 www 10357: return 'error: '.$reply;
10358: }
1.297 matthew 10359: # Add student role to user
1.83 www 10360: my $uurl='/'.$cid;
1.81 www 10361: $uurl=~s/\_/\//g;
10362: if ($usec) {
10363: $uurl.='/'.$usec;
10364: }
1.1148 raeburn 10365: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10366: $selfenroll,$context);
10367: if ($result ne 'ok') {
10368: if ($old_entry{$user} ne '') {
10369: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10370: } else {
10371: $reply = &del('classlist',[$user],$cdom,$cnum);
10372: }
10373: }
10374: return $result;
1.21 www 10375: }
10376:
1.556 albertel 10377: sub format_name {
10378: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10379: my $name;
10380: if ($first ne 'lastname') {
10381: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10382: } else {
10383: if ($lastname=~/\S/) {
10384: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10385: $name=~s/\s+,/,/;
10386: } else {
10387: $name.= $firstname.' '.$middlename.' '.$generation;
10388: }
10389: }
10390: $name=~s/^\s+//;
10391: $name=~s/\s+$//;
10392: $name=~s/\s+/ /g;
10393: return $name;
10394: }
10395:
1.84 www 10396: # ------------------------------------------------- Write to course preferences
10397:
10398: sub writecoursepref {
10399: my ($courseid,%prefs)=@_;
10400: $courseid=~s/^\///;
10401: $courseid=~s/\_/\//g;
10402: my ($cdomain,$cnum)=split(/\//,$courseid);
10403: my $chome=homeserver($cnum,$cdomain);
10404: if (($chome eq '') || ($chome eq 'no_host')) {
10405: return 'error: no such course';
10406: }
10407: my $cstring='';
1.800 albertel 10408: foreach my $pref (keys(%prefs)) {
10409: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10410: }
1.84 www 10411: $cstring=~s/\&$//;
10412: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10413: }
10414:
10415: # ---------------------------------------------------------- Make/modify course
10416:
10417: sub createcourse {
1.741 raeburn 10418: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.118. .6(raebu 10419:20): $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 10420: $url=&declutter($url);
10421: my $cid='';
1.1028 raeburn 10422: if ($context eq 'requestcourses') {
10423: my $can_create = 0;
10424: my ($ownername,$ownerdom) = split(':',$course_owner);
10425: if ($udom eq $ownerdom) {
1.1172.2.118. .6(raebu 10426:20): my $reload;
10427:20): if (($callercontext eq 'auto') &&
10428:20): ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10429:20): $reload = 'reload';
10430:20): }
10431:20): if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 10432: $context)) {
10433: $can_create = 1;
10434: }
10435: } else {
10436: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10437: $category);
10438: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10439: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10440: if (@curr > 0) {
10441: my @options = qw(approval validate autolimit);
10442: my $optregex = join('|',@options);
10443: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10444: $can_create = 1;
10445: }
10446: }
10447: }
10448: }
10449: if ($can_create) {
10450: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10451: unless (&allowed('ccc',$udom)) {
10452: return 'refused';
10453: }
1.1017 raeburn 10454: }
10455: } else {
10456: return 'refused';
10457: }
1.1028 raeburn 10458: } elsif (!&allowed('ccc',$udom)) {
10459: return 'refused';
1.84 www 10460: }
1.1011 raeburn 10461: # --------------------------------------------------------------- Get Unique ID
10462: my $uname;
10463: if ($cnum =~ /^$match_courseid$/) {
10464: my $chome=&homeserver($cnum,$udom,'true');
10465: if (($chome eq '') || ($chome eq 'no_host')) {
10466: $uname = $cnum;
10467: } else {
1.1038 raeburn 10468: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10469: }
10470: } else {
1.1038 raeburn 10471: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10472: }
10473: return $uname if ($uname =~ /^error/);
10474: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10475: if (!defined($course_server)) {
10476: if (defined(&domain($udom,'primary'))) {
10477: $course_server = &domain($udom,'primary');
10478: } else {
10479: $course_server = $env{'user.home'};
10480: }
10481: }
10482: my %host_servers =
10483: &Apache::lonnet::get_servers($udom,'library');
10484: unless ($host_servers{$course_server}) {
10485: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10486: }
1.84 www 10487: # ------------------------------------------------------------- Make the course
10488: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10489: $course_server);
1.84 www 10490: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10491: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10492: if (($uhome eq '') || ($uhome eq 'no_host')) {
10493: return 'error: no such course';
10494: }
1.271 www 10495: # ----------------------------------------------------------------- Course made
1.516 raeburn 10496: # log existence
1.1029 raeburn 10497: my $now = time;
1.918 raeburn 10498: my $newcourse = {
10499: $udom.'_'.$uname => {
1.921 raeburn 10500: description => $description,
10501: inst_code => $inst_code,
10502: owner => $course_owner,
10503: type => $crstype,
1.1029 raeburn 10504: creator => $env{'user.name'}.':'.
10505: $env{'user.domain'},
10506: created => $now,
10507: context => $context,
1.918 raeburn 10508: },
10509: };
1.921 raeburn 10510: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10511: # set toplevel url
1.271 www 10512: my $topurl=$url;
10513: unless ($nonstandard) {
10514: # ------------------------------------------ For standard courses, make top url
10515: my $mapurl=&clutter($url);
1.278 www 10516: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10517: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10518: <map>
10519: <resource id="1" type="start"></resource>
10520: <resource id="2" src="$mapurl"></resource>
10521: <resource id="3" type="finish"></resource>
10522: <link index="1" from="1" to="2"></link>
10523: <link index="2" from="2" to="3"></link>
10524: </map>
10525: ENDINITMAP
10526: $topurl=&declutter(
1.638 albertel 10527: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10528: );
10529: }
10530: # ----------------------------------------------------------- Write preferences
1.84 www 10531: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10532: ('description' => $description,
10533: 'url' => $topurl,
10534: 'internal.creator' => $env{'user.name'}.':'.
10535: $env{'user.domain'},
10536: 'internal.created' => $now,
10537: 'internal.creationcontext' => $context)
10538: );
1.84 www 10539: return '/'.$udom.'/'.$uname;
10540: }
10541:
1.1011 raeburn 10542: # ------------------------------------------------------------------- Create ID
10543: sub generate_coursenum {
1.1038 raeburn 10544: my ($udom,$crstype) = @_;
1.1011 raeburn 10545: my $domdesc = &domain($udom);
10546: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10547: my $first;
10548: if ($crstype eq 'Community') {
10549: $first = '0';
10550: } else {
10551: $first = int(1+rand(9));
10552: }
10553: my $uname=$first.
1.1011 raeburn 10554: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10555: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10556: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10557: # ----------------------------------------------- Make sure that does not exist
10558: my $uhome=&homeserver($uname,$udom,'true');
10559: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10560: if ($crstype eq 'Community') {
10561: $first = '0';
10562: } else {
10563: $first = int(1+rand(9));
10564: }
10565: $uname=$first.
1.1011 raeburn 10566: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10567: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10568: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10569: $uhome=&homeserver($uname,$udom,'true');
10570: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10571: return 'error: unable to generate unique course-ID';
10572: }
10573: }
10574: return $uname;
10575: }
10576:
1.813 albertel 10577: sub is_course {
1.1167 droeschl 10578: my ($cdom, $cnum) = scalar(@_) == 1 ?
10579: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10580: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10581: my $uhome=&homeserver($cnum,$cdom);
10582: my $iscourse;
10583: if (grep { $_ eq $uhome } current_machine_ids()) {
10584: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10585: } else {
10586: my $hashid = $cdom.':'.$cnum;
10587: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10588: unless (defined($cached)) {
10589: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10590: $cnum,undef,undef,'.');
10591: $iscourse = 0;
10592: if (exists($courses{$cdom.'_'.$cnum})) {
10593: $iscourse = 1;
10594: }
10595: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10596: }
10597: }
10598: return unless($iscourse);
1.1167 droeschl 10599: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10600: }
10601:
1.1015 raeburn 10602: sub store_userdata {
10603: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10604: my $result;
1.1016 raeburn 10605: if ($datakey ne '') {
1.1013 raeburn 10606: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10607: if ($udom eq '' || $uname eq '') {
10608: $udom = $env{'user.domain'};
10609: $uname = $env{'user.name'};
10610: }
10611: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10612: if (($uhome eq '') || ($uhome eq 'no_host')) {
10613: $result = 'error: no_host';
10614: } else {
1.1172.2.118. .14(raeb 10615:-21): $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 10616: $storehash->{'host'} = $perlvar{'lonHostID'};
10617:
10618: my $namevalue='';
10619: foreach my $key (keys(%{$storehash})) {
10620: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10621: }
10622: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10623: unless ($namespace eq 'courserequests') {
10624: $datakey = &escape($datakey);
10625: }
1.1105 raeburn 10626: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10627: $namevalue,$uhome);
1.1013 raeburn 10628: }
10629: } else {
10630: $result = 'error: data to store was not a hash reference';
10631: }
10632: } else {
10633: $result= 'error: invalid requestkey';
10634: }
10635: return $result;
10636: }
10637:
1.21 www 10638: # ---------------------------------------------------------- Assign Custom Role
10639:
10640: sub assigncustomrole {
1.957 raeburn 10641: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10642: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10643: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10644: }
10645:
10646: # ----------------------------------------------------------------- Revoke Role
10647:
10648: sub revokerole {
1.957 raeburn 10649: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10650: my $now=time;
1.965 raeburn 10651: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10652: }
10653:
10654: # ---------------------------------------------------------- Revoke Custom Role
10655:
10656: sub revokecustomrole {
1.957 raeburn 10657: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10658: my $now=time;
1.357 www 10659: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10660: $deleteflag,$selfenroll,$context);
1.17 www 10661: }
10662:
1.533 banghart 10663: # ------------------------------------------------------------ Disk usage
1.535 albertel 10664: sub diskusage {
1.955 raeburn 10665: my ($udom,$uname,$directorypath,$getpropath)=@_;
10666: $directorypath =~ s/\/$//;
10667: my $listing=&reply('du2:'.&escape($directorypath).':'
10668: .&escape($getpropath).':'.&escape($uname).':'
10669: .&escape($udom),homeserver($uname,$udom));
10670: if ($listing eq 'unknown_cmd') {
10671: if ($getpropath) {
10672: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10673: }
10674: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10675: }
1.514 albertel 10676: return $listing;
1.512 banghart 10677: }
10678:
1.566 banghart 10679: sub is_locked {
1.1096 raeburn 10680: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10681: my @check;
10682: my $is_locked;
1.1093 raeburn 10683: push (@check,$file_name);
1.613 albertel 10684: my %locked = &get('file_permissions',\@check,
1.620 albertel 10685: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10686: my ($tmp)=keys(%locked);
10687: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10688:
1.566 banghart 10689: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10690: $is_locked = 'false';
10691: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10692: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10693: $is_locked = 'true';
1.1096 raeburn 10694: if (ref($which) eq 'ARRAY') {
10695: push(@{$which},$entry);
10696: } else {
10697: last;
10698: }
1.745 raeburn 10699: }
10700: }
1.566 banghart 10701: } else {
10702: $is_locked = 'false';
10703: }
1.1093 raeburn 10704: return $is_locked;
1.566 banghart 10705: }
10706:
1.759 albertel 10707: sub declutter_portfile {
10708: my ($file) = @_;
1.833 albertel 10709: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10710: return $file;
10711: }
10712:
1.559 banghart 10713: # ------------------------------------------------------------- Mark as Read Only
10714:
10715: sub mark_as_readonly {
10716: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10717: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10718: my ($tmp)=keys(%current_permissions);
10719: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10720: foreach my $file (@{$files}) {
1.759 albertel 10721: $file = &declutter_portfile($file);
1.561 banghart 10722: push(@{$current_permissions{$file}},$what);
1.559 banghart 10723: }
1.613 albertel 10724: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10725: return;
10726: }
10727:
1.572 banghart 10728: # ------------------------------------------------------------Save Selected Files
10729:
10730: sub save_selected_files {
10731: my ($user, $path, @files) = @_;
10732: my $filename = $user."savedfiles";
1.573 banghart 10733: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10734: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10735: foreach my $file (@files) {
1.620 albertel 10736: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10737: }
10738: foreach my $file (@other_files) {
1.574 banghart 10739: print (OUT $file."\n");
1.572 banghart 10740: }
1.574 banghart 10741: close (OUT);
1.572 banghart 10742: return 'ok';
10743: }
10744:
1.574 banghart 10745: sub clear_selected_files {
10746: my ($user) = @_;
10747: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10748: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10749: print (OUT undef);
10750: close (OUT);
10751: return ("ok");
10752: }
10753:
1.572 banghart 10754: sub files_in_path {
10755: my ($user, $path) = @_;
10756: my $filename = $user."savedfiles";
10757: my %return_files;
1.1172.2.96 raeburn 10758: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10759: while (my $line_in = <IN>) {
1.574 banghart 10760: chomp ($line_in);
10761: my @paths_and_file = split (m!/!, $line_in);
10762: my $file_part = pop (@paths_and_file);
10763: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10764: $path_part.='/';
10765: my $path_and_file = $path_part.$file_part;
10766: if ($path_part eq $path) {
10767: $return_files{$file_part}= 'selected';
10768: }
10769: }
1.574 banghart 10770: close (IN);
10771: return (\%return_files);
1.572 banghart 10772: }
10773:
10774: # called in portfolio select mode, to show files selected NOT in current directory
10775: sub files_not_in_path {
10776: my ($user, $path) = @_;
10777: my $filename = $user."savedfiles";
10778: my @return_files;
10779: my $path_part;
1.1172.2.96 raeburn 10780: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10781: while (my $line = <IN>) {
1.572 banghart 10782: #ok, I know it's clunky, but I want it to work
1.800 albertel 10783: my @paths_and_file = split(m|/|, $line);
10784: my $file_part = pop(@paths_and_file);
10785: chomp($file_part);
10786: my $path_part = join('/', @paths_and_file);
1.572 banghart 10787: $path_part .= '/';
10788: my $path_and_file = $path_part.$file_part;
10789: if ($path_part ne $path) {
1.800 albertel 10790: push(@return_files, ($path_and_file));
1.572 banghart 10791: }
10792: }
1.800 albertel 10793: close(OUT);
1.574 banghart 10794: return (@return_files);
1.572 banghart 10795: }
10796:
1.745 raeburn 10797: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10798:
1.745 raeburn 10799: sub get_portfile_permissions {
10800: my ($domain,$user) = @_;
1.613 albertel 10801: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10802: my ($tmp)=keys(%current_permissions);
10803: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10804: return \%current_permissions;
10805: }
10806:
10807: #---------------------------------------------Get portfolio file access controls
10808:
1.749 raeburn 10809: sub get_access_controls {
1.745 raeburn 10810: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10811: my %access;
10812: my $real_file = $file;
10813: $file =~ s/\.meta$//;
1.745 raeburn 10814: if (defined($file)) {
1.749 raeburn 10815: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10816: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10817: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10818: }
10819: }
1.745 raeburn 10820: } else {
1.749 raeburn 10821: foreach my $key (keys(%{$current_permissions})) {
10822: if ($key =~ /\0accesscontrol$/) {
10823: if (defined($group)) {
10824: if ($key !~ m-^\Q$group\E/-) {
10825: next;
10826: }
10827: }
10828: my ($fullpath) = split(/\0/,$key);
10829: if (ref($$current_permissions{$key}) eq 'HASH') {
10830: foreach my $control (keys(%{$$current_permissions{$key}})) {
10831: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10832: }
10833: }
10834: }
10835: }
10836: }
10837: return %access;
10838: }
10839:
10840: sub modify_access_controls {
10841: my ($file_name,$changes,$domain,$user)=@_;
10842: my ($outcome,$deloutcome);
10843: my %store_permissions;
10844: my %new_values;
10845: my %new_control;
10846: my %translation;
10847: my @deletions = ();
10848: my $now = time;
10849: if (exists($$changes{'activate'})) {
10850: if (ref($$changes{'activate'}) eq 'HASH') {
10851: my @newitems = sort(keys(%{$$changes{'activate'}}));
10852: my $numnew = scalar(@newitems);
10853: for (my $i=0; $i<$numnew; $i++) {
10854: my $newkey = $newitems[$i];
10855: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10856: if ($newkey =~ /^\d+:/) {
10857: $newkey =~ s/^(\d+)/$newid/;
10858: $translation{$1} = $newid;
10859: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10860: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10861: $translation{$1} = $newid;
10862: }
1.749 raeburn 10863: $new_values{$file_name."\0".$newkey} =
10864: $$changes{'activate'}{$newitems[$i]};
10865: $new_control{$newkey} = $now;
10866: }
10867: }
10868: }
10869: my %todelete;
10870: my %changed_items;
10871: foreach my $action ('delete','update') {
10872: if (exists($$changes{$action})) {
10873: if (ref($$changes{$action}) eq 'HASH') {
10874: foreach my $key (keys(%{$$changes{$action}})) {
10875: my ($itemnum) = ($key =~ /^([^:]+):/);
10876: if ($action eq 'delete') {
10877: $todelete{$itemnum} = 1;
10878: } else {
10879: $changed_items{$itemnum} = $key;
10880: }
10881: }
1.745 raeburn 10882: }
10883: }
1.749 raeburn 10884: }
10885: # get lock on access controls for file.
10886: my $lockhash = {
10887: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10888: ':'.$env{'user.domain'},
10889: };
10890: my $tries = 0;
10891: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10892:
1.1172.2.79 raeburn 10893: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10894: $tries ++;
1.1172.2.79 raeburn 10895: sleep(0.1);
1.749 raeburn 10896: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10897: }
10898: if ($gotlock eq 'ok') {
10899: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10900: my ($tmp)=keys(%curr_permissions);
10901: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10902: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10903: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10904: if (ref($curr_controls) eq 'HASH') {
10905: foreach my $control_item (keys(%{$curr_controls})) {
10906: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10907: if (defined($todelete{$itemnum})) {
10908: push(@deletions,$file_name."\0".$control_item);
10909: } else {
10910: if (defined($changed_items{$itemnum})) {
10911: $new_control{$changed_items{$itemnum}} = $now;
10912: push(@deletions,$file_name."\0".$control_item);
10913: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10914: } else {
10915: $new_control{$control_item} = $$curr_controls{$control_item};
10916: }
10917: }
1.745 raeburn 10918: }
10919: }
10920: }
1.970 raeburn 10921: my ($group);
10922: if (&is_course($domain,$user)) {
10923: ($group,my $file) = split(/\//,$file_name,2);
10924: }
1.749 raeburn 10925: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10926: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10927: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10928: # remove lock
10929: my @del_lock = ($file_name."\0".'locked_access_records');
10930: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10931: my $sqlresult =
1.970 raeburn 10932: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10933: $group);
1.749 raeburn 10934: } else {
10935: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10936: }
1.749 raeburn 10937: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10938: }
10939:
1.827 raeburn 10940: sub make_public_indefinitely {
10941: my ($requrl) = @_;
10942: my $now = time;
10943: my $action = 'activate';
10944: my $aclnum = 0;
10945: if (&is_portfolio_url($requrl)) {
10946: my (undef,$udom,$unum,$file_name,$group) =
10947: &parse_portfolio_url($requrl);
10948: my $current_perms = &get_portfile_permissions($udom,$unum);
10949: my %access_controls = &get_access_controls($current_perms,
10950: $group,$file_name);
10951: foreach my $key (keys(%{$access_controls{$file_name}})) {
10952: my ($num,$scope,$end,$start) =
10953: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10954: if ($scope eq 'public') {
10955: if ($start <= $now && $end == 0) {
10956: $action = 'none';
10957: } else {
10958: $action = 'update';
10959: $aclnum = $num;
10960: }
10961: last;
10962: }
10963: }
10964: if ($action eq 'none') {
10965: return 'ok';
10966: } else {
10967: my %changes;
10968: my $newend = 0;
10969: my $newstart = $now;
10970: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10971: $changes{$action}{$newkey} = {
10972: type => 'public',
10973: time => {
10974: start => $newstart,
10975: end => $newend,
10976: },
10977: };
10978: my ($outcome,$deloutcome,$new_values,$translation) =
10979: &modify_access_controls($file_name,\%changes,$udom,$unum);
10980: return $outcome;
10981: }
10982: } else {
10983: return 'invalid';
10984: }
10985: }
10986:
1.745 raeburn 10987: #------------------------------------------------------Get Marked as Read Only
10988:
10989: sub get_marked_as_readonly {
10990: my ($domain,$user,$what,$group) = @_;
10991: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10992: my @readonly_files;
1.629 banghart 10993: my $cmp1=$what;
10994: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10995: while (my ($file_name,$value) = each(%{$current_permissions})) {
10996: if (defined($group)) {
10997: if ($file_name !~ m-^\Q$group\E/-) {
10998: next;
10999: }
11000: }
1.561 banghart 11001: if (ref($value) eq "ARRAY"){
11002: foreach my $stored_what (@{$value}) {
1.629 banghart 11003: my $cmp2=$stored_what;
1.759 albertel 11004: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11005: $cmp2=join('',@{$stored_what});
1.745 raeburn 11006: }
1.629 banghart 11007: if ($cmp1 eq $cmp2) {
1.561 banghart 11008: push(@readonly_files, $file_name);
1.745 raeburn 11009: last;
1.563 banghart 11010: } elsif (!defined($what)) {
11011: push(@readonly_files, $file_name);
1.745 raeburn 11012: last;
1.561 banghart 11013: }
11014: }
1.745 raeburn 11015: }
1.561 banghart 11016: }
11017: return @readonly_files;
11018: }
1.577 banghart 11019: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11020:
1.577 banghart 11021: sub get_marked_as_readonly_hash {
1.745 raeburn 11022: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11023: my %readonly_files;
1.745 raeburn 11024: while (my ($file_name,$value) = each(%{$current_permissions})) {
11025: if (defined($group)) {
11026: if ($file_name !~ m-^\Q$group\E/-) {
11027: next;
11028: }
11029: }
1.577 banghart 11030: if (ref($value) eq "ARRAY"){
11031: foreach my $stored_what (@{$value}) {
1.745 raeburn 11032: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11033: foreach my $lock_descriptor(@{$stored_what}) {
11034: if ($lock_descriptor eq 'graded') {
11035: $readonly_files{$file_name} = 'graded';
11036: } elsif ($lock_descriptor eq 'handback') {
11037: $readonly_files{$file_name} = 'handback';
11038: } else {
11039: if (!exists($readonly_files{$file_name})) {
11040: $readonly_files{$file_name} = 'locked';
11041: }
11042: }
1.745 raeburn 11043: }
1.750 banghart 11044: }
1.577 banghart 11045: }
11046: }
11047: }
11048: return %readonly_files;
11049: }
1.559 banghart 11050: # ------------------------------------------------------------ Unmark as Read Only
11051:
11052: sub unmark_as_readonly {
1.629 banghart 11053: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11054: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11055: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11056: $file_name = &declutter_portfile($file_name);
1.634 albertel 11057: my $symb_crs = $what;
11058: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11059: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11060: my ($tmp)=keys(%current_permissions);
11061: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11062: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11063: foreach my $file (@readonly_files) {
1.759 albertel 11064: my $clean_file = &declutter_portfile($file);
11065: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11066: my $current_locks = $current_permissions{$file};
1.563 banghart 11067: my @new_locks;
11068: my @del_keys;
11069: if (ref($current_locks) eq "ARRAY"){
11070: foreach my $locker (@{$current_locks}) {
1.632 albertel 11071: my $compare=$locker;
1.749 raeburn 11072: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11073: $compare=join('',@{$locker});
1.746 raeburn 11074: if ($compare ne $symb_crs) {
11075: push(@new_locks, $locker);
11076: }
1.563 banghart 11077: }
11078: }
1.650 albertel 11079: if (scalar(@new_locks) > 0) {
1.563 banghart 11080: $current_permissions{$file} = \@new_locks;
11081: } else {
11082: push(@del_keys, $file);
1.613 albertel 11083: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11084: delete($current_permissions{$file});
1.563 banghart 11085: }
11086: }
1.561 banghart 11087: }
1.613 albertel 11088: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11089: return;
11090: }
1.512 banghart 11091:
1.17 www 11092: # ------------------------------------------------------------ Directory lister
11093:
11094: sub dirlist {
1.955 raeburn 11095: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11096: $uri=~s/^\///;
11097: $uri=~s/\/$//;
1.253 stredwic 11098: my ($udom, $uname);
1.955 raeburn 11099: if ($getuserdir) {
1.253 stredwic 11100: $udom = $userdomain;
11101: $uname = $username;
1.955 raeburn 11102: } else {
11103: (undef,$udom,$uname)=split(/\//,$uri);
11104: if(defined($userdomain)) {
11105: $udom = $userdomain;
11106: }
11107: if(defined($username)) {
11108: $uname = $username;
11109: }
1.253 stredwic 11110: }
1.955 raeburn 11111: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11112:
1.955 raeburn 11113: $dirRoot = $perlvar{'lonDocRoot'};
11114: if (defined($getpropath)) {
11115: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11116: $dirRoot =~ s/\/$//;
1.955 raeburn 11117: } elsif (defined($getuserdir)) {
11118: my $subdir=$uname.'__';
11119: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11120: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11121: ."/$udom/$subdir/$uname";
11122: } elsif (defined($alternateRoot)) {
11123: $dirRoot = $alternateRoot;
1.751 banghart 11124: }
1.253 stredwic 11125:
11126: if($udom) {
11127: if($uname) {
1.1135 raeburn 11128: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11129: if ($uhome eq 'no_host') {
11130: return ([],'no_host');
11131: }
1.955 raeburn 11132: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11133: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11134: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11135: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11136: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11137: } else {
11138: @listing_results = map { &unescape($_); } split(/:/,$listing);
11139: }
1.605 matthew 11140: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11141: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11142: @listing_results = split(/:/,$listing);
11143: } else {
11144: @listing_results = map { &unescape($_); } split(/:/,$listing);
11145: }
1.1135 raeburn 11146: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11147: ($listing eq 'rejected') || ($listing eq 'refused') ||
11148: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11149: return ([],$listing);
11150: } else {
11151: return (\@listing_results);
1.1135 raeburn 11152: }
1.955 raeburn 11153: } elsif(!$alternateRoot) {
1.1136 raeburn 11154: my (%allusers,%listerror);
1.841 albertel 11155: my %servers = &get_servers($udom,'library');
1.955 raeburn 11156: foreach my $tryserver (keys(%servers)) {
11157: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11158: &escape($udom),$tryserver);
11159: if ($listing eq 'unknown_cmd') {
11160: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11161: $udom, $tryserver);
11162: } else {
11163: @listing_results = map { &unescape($_); } split(/:/,$listing);
11164: }
1.841 albertel 11165: if ($listing eq 'unknown_cmd') {
11166: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11167: $udom, $tryserver);
11168: @listing_results = split(/:/,$listing);
11169: } else {
11170: @listing_results =
11171: map { &unescape($_); } split(/:/,$listing);
11172: }
1.1136 raeburn 11173: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11174: ($listing eq 'rejected') || ($listing eq 'refused') ||
11175: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11176: $listerror{$tryserver} = $listing;
11177: } else {
1.841 albertel 11178: foreach my $line (@listing_results) {
11179: my ($entry) = split(/&/,$line,2);
11180: $allusers{$entry} = 1;
11181: }
11182: }
1.253 stredwic 11183: }
1.1136 raeburn 11184: my @alluserslist=();
1.800 albertel 11185: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11186: push(@alluserslist,$user.'&user');
1.253 stredwic 11187: }
1.1172.2.80 raeburn 11188: if (!%listerror) {
11189: # no errors
11190: return (\@alluserslist);
11191: } elsif (scalar(keys(%servers)) == 1) {
11192: # one library server, one error
11193: my ($key) = keys(%listerror);
11194: return (\@alluserslist, $listerror{$key});
11195: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11196: # con_lost indicates that we might miss data from at least one
11197: # library server
11198: return (\@alluserslist, 'con_lost');
11199: } else {
11200: # multiple library servers and no con_lost -> data should be
11201: # complete.
11202: return (\@alluserslist);
11203: }
11204:
1.253 stredwic 11205: } else {
1.1136 raeburn 11206: return ([],'missing username');
1.253 stredwic 11207: }
1.955 raeburn 11208: } elsif(!defined($getpropath)) {
1.1136 raeburn 11209: my $path = $perlvar{'lonDocRoot'}.'/res/';
11210: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11211: return (\@all_domains);
1.955 raeburn 11212: } else {
1.1136 raeburn 11213: return ([],'missing domain');
1.275 stredwic 11214: }
11215: }
11216:
11217: # --------------------------------------------- GetFileTimestamp
11218: # This function utilizes dirlist and returns the date stamp for
11219: # when it was last modified. It will also return an error of -1
11220: # if an error occurs
11221:
11222: sub GetFileTimestamp {
1.955 raeburn 11223: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11224: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11225: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11226: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11227: undef,$getuserdir);
11228: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11229: return -1;
11230: }
11231: if (ref($fileref) eq 'ARRAY') {
11232: my @stats = split('&',$fileref->[0]);
1.375 matthew 11233: # @stats contains first the filename, then the stat output
11234: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11235: } else {
11236: return -1;
1.253 stredwic 11237: }
1.26 www 11238: }
11239:
1.712 albertel 11240: sub stat_file {
11241: my ($uri) = @_;
1.787 albertel 11242: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11243:
1.955 raeburn 11244: my ($udom,$uname,$file);
1.712 albertel 11245: if ($uri =~ m-^/(uploaded|editupload)/-) {
11246: ($udom,$uname,$file) =
1.811 albertel 11247: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11248: $file = 'userfiles/'.$file;
11249: }
11250: if ($uri =~ m-^/res/-) {
11251: ($udom,$uname) =
1.807 albertel 11252: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11253: $file = $uri;
11254: }
11255:
11256: if (!$udom || !$uname || !$file) {
11257: # unable to handle the uri
11258: return ();
11259: }
1.956 raeburn 11260: my $getpropath;
11261: if ($file =~ /^userfiles\//) {
11262: $getpropath = 1;
11263: }
1.1136 raeburn 11264: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11265: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11266: return ();
11267: } else {
11268: if (ref($listref) eq 'ARRAY') {
11269: my @stats = split('&',$listref->[0]);
11270: shift(@stats); #filename is first
11271: return @stats;
11272: }
1.712 albertel 11273: }
11274: return ();
11275: }
11276:
1.26 www 11277: # -------------------------------------------------------- Value of a Condition
11278:
1.713 albertel 11279: # gets the value of a specific preevaluated condition
11280: # stored in the string $env{user.state.<cid>}
11281: # or looks up a condition reference in the bighash and if if hasn't
11282: # already been evaluated recurses into docondval to get the value of
11283: # the condition, then memoizing it to
11284: # $env{user.state.<cid>.<condition>}
1.40 www 11285: sub directcondval {
11286: my $number=shift;
1.620 albertel 11287: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11288: &Apache::lonuserstate::evalstate();
11289: }
1.713 albertel 11290: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11291: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11292: } elsif ($number =~ /^_/) {
11293: my $sub_condition;
11294: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11295: &GDBM_READER(),0640)) {
11296: $sub_condition=$bighash{'conditions'.$number};
11297: untie(%bighash);
11298: }
11299: my $value = &docondval($sub_condition);
1.949 raeburn 11300: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11301: return $value;
11302: }
1.620 albertel 11303: if ($env{'user.state.'.$env{'request.course.id'}}) {
11304: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11305: } else {
11306: return 2;
11307: }
11308: }
11309:
1.713 albertel 11310: # get the collection of conditions for this resource
1.26 www 11311: sub condval {
11312: my $condidx=shift;
1.54 www 11313: my $allpathcond='';
1.713 albertel 11314: foreach my $cond (split(/\|/,$condidx)) {
11315: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11316: $allpathcond.=
11317: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11318: }
1.191 harris41 11319: }
1.54 www 11320: $allpathcond=~s/\|$//;
1.713 albertel 11321: return &docondval($allpathcond);
11322: }
11323:
11324: #evaluates an expression of conditions
11325: sub docondval {
11326: my ($allpathcond) = @_;
11327: my $result=0;
11328: if ($env{'request.course.id'}
11329: && defined($allpathcond)) {
11330: my $operand='|';
11331: my @stack;
11332: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11333: if ($chunk eq '(') {
11334: push @stack,($operand,$result);
11335: } elsif ($chunk eq ')') {
11336: my $before=pop @stack;
11337: if (pop @stack eq '&') {
11338: $result=$result>$before?$before:$result;
11339: } else {
11340: $result=$result>$before?$result:$before;
11341: }
11342: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11343: $operand=$chunk;
11344: } else {
11345: my $new=directcondval($chunk);
11346: if ($operand eq '&') {
11347: $result=$result>$new?$new:$result;
11348: } else {
11349: $result=$result>$new?$result:$new;
11350: }
11351: }
11352: }
1.26 www 11353: }
11354: return $result;
1.421 albertel 11355: }
11356:
11357: # ---------------------------------------------------- Devalidate courseresdata
11358:
11359: sub devalidatecourseresdata {
11360: my ($coursenum,$coursedomain)=@_;
11361: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11362: &devalidate_cache_new('courseres',$hashid);
1.28 www 11363: }
11364:
1.763 www 11365:
1.200 www 11366: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11367: #
11368: # Parameters:
11369: # $coursenum - Number of the course.
11370: # $coursedomain - Domain at which the course was created.
11371: # Returns:
11372: # A hash of the course parameters along (I think) with timestamps
11373: # and version info.
1.877 foxr 11374:
1.624 albertel 11375: sub get_courseresdata {
11376: my ($coursenum,$coursedomain)=@_;
1.200 www 11377: my $coursehom=&homeserver($coursenum,$coursedomain);
11378: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11379: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11380: my %dumpreply;
1.417 albertel 11381: unless (defined($cached)) {
1.624 albertel 11382: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11383: $result=\%dumpreply;
1.251 albertel 11384: my ($tmp) = keys(%dumpreply);
11385: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11386: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11387: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11388: return $tmp;
1.416 albertel 11389: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11390: $result=undef;
1.599 albertel 11391: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11392: }
11393: }
1.624 albertel 11394: return $result;
11395: }
11396:
1.633 albertel 11397: sub devalidateuserresdata {
11398: my ($uname,$udom)=@_;
11399: my $hashid="$udom:$uname";
11400: &devalidate_cache_new('userres',$hashid);
11401: }
11402:
1.624 albertel 11403: sub get_userresdata {
11404: my ($uname,$udom)=@_;
11405: #most student don\'t have any data set, check if there is some data
11406: if (&EXT_cache_status($udom,$uname)) { return undef; }
11407:
11408: my $hashid="$udom:$uname";
11409: my ($result,$cached)=&is_cached_new('userres',$hashid);
11410: if (!defined($cached)) {
11411: my %resourcedata=&dump('resourcedata',$udom,$uname);
11412: $result=\%resourcedata;
11413: &do_cache_new('userres',$hashid,$result,600);
11414: }
11415: my ($tmp)=keys(%$result);
11416: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11417: return $result;
11418: }
11419: #error 2 occurs when the .db doesn't exist
11420: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11421: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11422: &logthis("<font color=\"blue\">WARNING:".
11423: " Trying to get resource data for ".
11424: $uname." at ".$udom.": ".
11425: $tmp."</font>");
11426: }
1.624 albertel 11427: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11428: #&EXT_cache_set($udom,$uname);
11429: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11430: undef($tmp); # not really an error so don't send it back
1.624 albertel 11431: }
11432: return $tmp;
11433: }
1.879 foxr 11434: #----------------------------------------------- resdata - return resource data
11435: # Purpose:
11436: # Return resource data for either users or for a course.
11437: # Parameters:
11438: # $name - Course/user name.
11439: # $domain - Name of the domain the user/course is registered on.
1.1172.2.118. .1(raebu 11440:20): # $type - Type of thing $name is (must be 'course' or 'user')
1.879 foxr 11441: # @which - Array of names of resources desired.
11442: # Returns:
11443: # The value of the first reasource in @which that is found in the
11444: # resource hash.
11445: # Exceptional Conditions:
11446: # If the $type passed in is not valid (not the string 'course' or
11447: # 'user', an undefined reference is returned.
11448: # If none of the resources are found, an undef is returned
1.624 albertel 11449: sub resdata {
11450: my ($name,$domain,$type,@which)=@_;
11451: my $result;
11452: if ($type eq 'course') {
11453: $result=&get_courseresdata($name,$domain);
11454: } elsif ($type eq 'user') {
11455: $result=&get_userresdata($name,$domain);
11456: }
11457: if (!ref($result)) { return $result; }
1.251 albertel 11458: foreach my $item (@which) {
1.1172.2.118. .8(raebu 11459:20): if (defined($result->{$item->[0]})) {
11460:20): return [$result->{$item->[0]},$item->[1]];
.1(raebu 11461:20): }
1.250 albertel 11462: }
1.291 albertel 11463: return undef;
1.200 www 11464: }
11465:
1.1172.2.118. .10(raeb 11466:-20): sub get_domain_lti {
11467:-20): my ($cdom,$context) = @_;
11468:-20): my ($name,%lti);
11469:-20): if ($context eq 'consumer') {
11470:-20): $name = 'ltitools';
11471:-20): } elsif ($context eq 'provider') {
11472:-20): $name = 'lti';
11473:-20): } else {
11474:-20): return %lti;
11475:-20): }
11476:-20): my ($result,$cached)=&is_cached_new($name,$cdom);
.1(raebu 11477:20): if (defined($cached)) {
11478:20): if (ref($result) eq 'HASH') {
.10(raeb 11479:-20): %lti = %{$result};
.1(raebu 11480:20): }
11481:20): } else {
.10(raeb 11482:-20): my %domconfig = &get_dom('configuration',[$name],$cdom);
11483:-20): if (ref($domconfig{$name}) eq 'HASH') {
11484:-20): %lti = %{$domconfig{$name}};
11485:-20): my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11486:-20): if (ref($encdomconfig{$name}) eq 'HASH') {
11487:-20): foreach my $id (keys(%lti)) {
11488:-20): if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
.1(raebu 11489:20): foreach my $item ('key','secret') {
.10(raeb 11490:-20): $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
.1(raebu 11491:20): }
11492:20): }
11493:20): }
11494:20): }
11495:20): }
11496:20): my $cachetime = 24*60*60;
.10(raeb 11497:-20): &do_cache_new($name,$cdom,\%lti,$cachetime);
.1(raebu 11498:20): }
.10(raeb 11499:-20): return %lti;
.1(raebu 11500:20): }
11501:20):
1.1172.2.31 raeburn 11502: sub get_numsuppfiles {
11503: my ($cnum,$cdom,$ignorecache)=@_;
11504: my $hashid=$cnum.':'.$cdom;
11505: my ($suppcount,$cached);
11506: unless ($ignorecache) {
11507: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11508: }
11509: unless (defined($cached)) {
11510: my $chome=&homeserver($cnum,$cdom);
11511: unless ($chome eq 'no_host') {
11512: ($suppcount,my $errors) = (0,0);
11513: my $suppmap = 'supplemental.sequence';
11514: ($suppcount,$errors) =
11515: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11516: }
11517: &do_cache_new('suppcount',$hashid,$suppcount,600);
11518: }
11519: return $suppcount;
11520: }
11521:
1.379 matthew 11522: #
11523: # EXT resource caching routines
11524: #
11525:
11526: sub clear_EXT_cache_status {
1.383 albertel 11527: &delenv('cache.EXT.');
1.379 matthew 11528: }
11529:
11530: sub EXT_cache_status {
11531: my ($target_domain,$target_user) = @_;
1.383 albertel 11532: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11533: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11534: # We know already the user has no data
11535: return 1;
11536: } else {
11537: return 0;
11538: }
11539: }
11540:
11541: sub EXT_cache_set {
11542: my ($target_domain,$target_user) = @_;
1.383 albertel 11543: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11544: #&appenv({$cachename => time});
1.379 matthew 11545: }
11546:
1.28 www 11547: # --------------------------------------------------------- Value of a Variable
1.58 www 11548: sub EXT {
1.715 albertel 11549:
1.1172.2.28 raeburn 11550: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11551: unless ($varname) { return ''; }
1.218 albertel 11552: #get real user name/domain, courseid and symb
11553: my $courseid;
1.359 albertel 11554: my $publicuser;
1.427 www 11555: if ($symbparm) {
11556: $symbparm=&get_symb_from_alias($symbparm);
11557: }
1.218 albertel 11558: if (!($uname && $udom)) {
1.790 albertel 11559: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11560: if (!$symbparm) { $symbparm=$cursymb; }
11561: } else {
1.620 albertel 11562: $courseid=$env{'request.course.id'};
1.218 albertel 11563: }
1.48 www 11564: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11565: my $rest;
1.320 albertel 11566: if (defined($therest[0])) {
1.48 www 11567: $rest=join('.',@therest);
11568: } else {
11569: $rest='';
11570: }
1.320 albertel 11571:
1.57 www 11572: my $qualifierrest=$qualifier;
11573: if ($rest) { $qualifierrest.='.'.$rest; }
11574: my $spacequalifierrest=$space;
11575: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11576: if ($realm eq 'user') {
1.48 www 11577: # --------------------------------------------------------------- user.resource
11578: if ($space eq 'resource') {
1.651 albertel 11579: if ( (defined($Apache::lonhomework::parsing_a_problem)
11580: || defined($Apache::lonhomework::parsing_a_task))
11581: &&
1.744 albertel 11582: ($symbparm eq &symbread()) ) {
11583: # if we are in the middle of processing the resource the
11584: # get the value we are planning on committing
11585: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11586: return $Apache::lonhomework::results{$qualifierrest};
11587: } else {
11588: return $Apache::lonhomework::history{$qualifierrest};
11589: }
1.335 albertel 11590: } else {
1.359 albertel 11591: my %restored;
1.620 albertel 11592: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11593: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11594: } else {
11595: %restored=&restore($symbparm,$courseid,$udom,$uname);
11596: }
1.335 albertel 11597: return $restored{$qualifierrest};
11598: }
1.48 www 11599: # ----------------------------------------------------------------- user.access
11600: } elsif ($space eq 'access') {
1.218 albertel 11601: # FIXME - not supporting calls for a specific user
1.48 www 11602: return &allowed($qualifier,$rest);
11603: # ------------------------------------------ user.preferences, user.environment
11604: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11605: if (($uname eq $env{'user.name'}) &&
11606: ($udom eq $env{'user.domain'})) {
11607: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11608: } else {
1.359 albertel 11609: my %returnhash;
11610: if (!$publicuser) {
11611: %returnhash=&userenvironment($udom,$uname,
11612: $qualifierrest);
11613: }
1.218 albertel 11614: return $returnhash{$qualifierrest};
11615: }
1.48 www 11616: # ----------------------------------------------------------------- user.course
11617: } elsif ($space eq 'course') {
1.218 albertel 11618: # FIXME - not supporting calls for a specific user
1.620 albertel 11619: return $env{join('.',('request.course',$qualifier))};
1.48 www 11620: # ------------------------------------------------------------------- user.role
11621: } elsif ($space eq 'role') {
1.218 albertel 11622: # FIXME - not supporting calls for a specific user
1.620 albertel 11623: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11624: if ($qualifier eq 'value') {
11625: return $role;
11626: } elsif ($qualifier eq 'extent') {
11627: return $where;
11628: }
11629: # ----------------------------------------------------------------- user.domain
11630: } elsif ($space eq 'domain') {
1.218 albertel 11631: return $udom;
1.48 www 11632: # ------------------------------------------------------------------- user.name
11633: } elsif ($space eq 'name') {
1.218 albertel 11634: return $uname;
1.48 www 11635: # ---------------------------------------------------- Any other user namespace
1.29 www 11636: } else {
1.359 albertel 11637: my %reply;
11638: if (!$publicuser) {
11639: %reply=&get($space,[$qualifierrest],$udom,$uname);
11640: }
11641: return $reply{$qualifierrest};
1.48 www 11642: }
1.236 www 11643: } elsif ($realm eq 'query') {
11644: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11645: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11646: [$spacequalifierrest]);
1.620 albertel 11647: return $env{'form.'.$spacequalifierrest};
1.236 www 11648: } elsif ($realm eq 'request') {
1.48 www 11649: # ------------------------------------------------------------- request.browser
11650: if ($space eq 'browser') {
1.1145 bisitz 11651: return $env{'browser.'.$qualifier};
1.57 www 11652: # ------------------------------------------------------------ request.filename
11653: } else {
1.620 albertel 11654: return $env{'request.'.$spacequalifierrest};
1.29 www 11655: }
1.28 www 11656: } elsif ($realm eq 'course') {
1.48 www 11657: # ---------------------------------------------------------- course.description
1.620 albertel 11658: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11659: } elsif ($realm eq 'resource') {
1.165 www 11660:
1.620 albertel 11661: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11662: if (!$symbparm) { $symbparm=&symbread(); }
11663: }
1.693 albertel 11664:
1.1172.2.30 raeburn 11665: if ($qualifier eq '') {
11666: if ($space eq 'title') {
11667: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11668: return &gettitle($symbparm);
11669: }
1.693 albertel 11670:
1.1172.2.30 raeburn 11671: if ($space eq 'map') {
11672: my ($map) = &decode_symb($symbparm);
11673: return &symbread($map);
11674: }
11675: if ($space eq 'maptitle') {
11676: my ($map) = &decode_symb($symbparm);
11677: return &gettitle($map);
11678: }
11679: if ($space eq 'filename') {
11680: if ($symbparm) {
11681: return &clutter((&decode_symb($symbparm))[2]);
11682: }
11683: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11684: }
1.1172.2.30 raeburn 11685:
11686: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11687: if ($space eq 'visibleparts') {
11688: my $navmap = Apache::lonnavmaps::navmap->new();
11689: my $item;
11690: if (ref($navmap)) {
11691: my $res = $navmap->getBySymb($symbparm);
11692: my $parts = $res->parts();
11693: if (ref($parts) eq 'ARRAY') {
11694: $item = join(',',@{$parts});
11695: }
11696: undef($navmap);
11697: }
11698: return $item;
11699: }
11700: }
11701: }
1.693 albertel 11702:
11703: my ($section, $group, @groups);
1.593 albertel 11704: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11705: if (($courseid eq '') && ($cid)) {
11706: $courseid = $cid;
11707: }
11708: if (($symbparm && $courseid) &&
11709: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11710:
1.218 albertel 11711: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11712:
1.60 www 11713: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11714: my $symbp=$symbparm;
1.735 albertel 11715: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11716:
11717: my $symbparm=$symbp.'.'.$spacequalifierrest;
11718: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11719:
1.620 albertel 11720: if (($env{'user.name'} eq $uname) &&
11721: ($env{'user.domain'} eq $udom)) {
11722: $section=$env{'request.course.sec'};
1.733 raeburn 11723: @groups = split(/:/,$env{'request.course.groups'});
11724: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11725: } else {
1.539 albertel 11726: if (! defined($usection)) {
1.551 albertel 11727: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11728: } else {
11729: $section = $usection;
11730: }
1.733 raeburn 11731: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11732: }
11733:
11734: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11735: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11736: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11737:
1.593 albertel 11738: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11739: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11740: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11741:
1.60 www 11742: # ----------------------------------------------------------- first, check user
1.624 albertel 11743:
11744: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11745: ([$courselevelr,'resource'],
11746: [$courselevelm,'map' ],
11747: [$courselevel, 'course' ]));
1.931 albertel 11748: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11749:
1.594 albertel 11750: # ------------------------------------------------ second, check some of course
1.684 raeburn 11751: my $coursereply;
1.691 raeburn 11752: if (@groups > 0) {
11753: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11754: $mapparm,$spacequalifierrest);
1.927 albertel 11755: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11756: }
1.96 www 11757:
1.684 raeburn 11758: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11759: $env{'course.'.$courseid.'.domain'},
11760: 'course',
11761: ([$seclevelr, 'resource'],
11762: [$seclevelm, 'map' ],
11763: [$seclevel, 'course' ],
11764: [$courselevelr,'resource']));
11765: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11766:
1.60 www 11767: # ------------------------------------------------------ third, check map parms
1.218 albertel 11768: my %parmhash=();
11769: my $thisparm='';
11770: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11771: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11772: &GDBM_READER(),0640)) {
1.218 albertel 11773: $thisparm=$parmhash{$symbparm};
11774: untie(%parmhash);
11775: }
1.927 albertel 11776: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11777: }
1.594 albertel 11778: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11779:
1.218 albertel 11780: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11781: my $filename;
11782: if (!$symbparm) { $symbparm=&symbread(); }
11783: if ($symbparm) {
1.409 www 11784: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11785: } else {
1.620 albertel 11786: $filename=$env{'request.filename'};
1.282 albertel 11787: }
11788: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11789: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11790: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11791: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11792:
1.927 albertel 11793: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11794: if ($symbparm && defined($courseid) &&
1.620 albertel 11795: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11796: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11797: $env{'course.'.$courseid.'.domain'},
11798: 'course',
1.927 albertel 11799: ([$courselevelm,'map' ],
11800: [$courselevel, 'course']));
11801: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11802: }
1.145 www 11803: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11804: unless ($space eq '0') {
1.336 albertel 11805: my @parts=split(/_/,$space);
11806: my $id=pop(@parts);
11807: my $part=join('_',@parts);
11808: if ($part eq '') { $part='0'; }
1.927 albertel 11809: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11810: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11811: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11812: }
1.395 albertel 11813: if ($recurse) { return undef; }
11814: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11815: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11816: # ---------------------------------------------------- Any other user namespace
11817: } elsif ($realm eq 'environment') {
11818: # ----------------------------------------------------------------- environment
1.620 albertel 11819: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11820: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11821: } else {
1.770 albertel 11822: if ($uname eq 'anonymous' && $udom eq '') {
11823: return '';
11824: }
1.219 albertel 11825: my %returnhash=&userenvironment($udom,$uname,
11826: $spacequalifierrest);
11827: return $returnhash{$spacequalifierrest};
11828: }
1.28 www 11829: } elsif ($realm eq 'system') {
1.48 www 11830: # ----------------------------------------------------------------- system.time
11831: if ($space eq 'time') {
11832: return time;
11833: }
1.696 albertel 11834: } elsif ($realm eq 'server') {
11835: # ----------------------------------------------------------------- system.time
11836: if ($space eq 'name') {
11837: return $ENV{'SERVER_NAME'};
11838: }
1.28 www 11839: }
1.48 www 11840: return '';
1.61 www 11841: }
11842:
1.927 albertel 11843: sub get_reply {
11844: my ($reply_value) = @_;
1.940 raeburn 11845: if (ref($reply_value) eq 'ARRAY') {
11846: if (wantarray) {
11847: return @$reply_value;
11848: }
11849: return $reply_value->[0];
11850: } else {
11851: return $reply_value;
1.927 albertel 11852: }
11853: }
11854:
1.691 raeburn 11855: sub check_group_parms {
11856: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11857: my @groupitems = ();
11858: my $resultitem;
1.927 albertel 11859: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11860: foreach my $group (@{$groups}) {
11861: foreach my $level (@levels) {
1.927 albertel 11862: my $item = $courseid.'.['.$group.'].'.$level->[0];
11863: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11864: }
11865: }
11866: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11867: $env{'course.'.$courseid.'.domain'},
11868: 'course',@groupitems);
11869: return $coursereply;
11870: }
11871:
11872: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11873: my ($courseid,@groups) = @_;
11874: @groups = sort(@groups);
1.691 raeburn 11875: return @groups;
11876: }
11877:
1.395 albertel 11878: sub packages_tab_default {
11879: my ($uri,$varname)=@_;
11880: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11881:
11882: my (@extension,@specifics,$do_default);
11883: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11884: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11885: if ($pack_type eq 'default') {
11886: $do_default=1;
11887: } elsif ($pack_type eq 'extension') {
11888: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11889: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11890: # only look at packages defaults for packages that this id is
1.738 albertel 11891: push(@specifics,[$package,$pack_type,$pack_part]);
11892: }
11893: }
11894: # first look for a package that matches the requested part id
11895: foreach my $package (@specifics) {
11896: my (undef,$pack_type,$pack_part)=@{$package};
11897: next if ($pack_part ne $part);
11898: if (defined($packagetab{"$pack_type&$name&default"})) {
11899: return $packagetab{"$pack_type&$name&default"};
11900: }
11901: }
11902: # look for any possible matching non extension_ package
11903: foreach my $package (@specifics) {
11904: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11905: if (defined($packagetab{"$pack_type&$name&default"})) {
11906: return $packagetab{"$pack_type&$name&default"};
11907: }
1.585 albertel 11908: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11909: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11910: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11911: }
11912: }
1.738 albertel 11913: # look for any posible extension_ match
11914: foreach my $package (@extension) {
11915: my ($package,$pack_type)=@{$package};
11916: if (defined($packagetab{"$pack_type&$name&default"})) {
11917: return $packagetab{"$pack_type&$name&default"};
11918: }
11919: if (defined($packagetab{$package."&$name&default"})) {
11920: return $packagetab{$package."&$name&default"};
11921: }
11922: }
11923: # look for a global default setting
11924: if ($do_default && defined($packagetab{"default&$name&default"})) {
11925: return $packagetab{"default&$name&default"};
11926: }
1.395 albertel 11927: return undef;
11928: }
11929:
1.334 albertel 11930: sub add_prefix_and_part {
11931: my ($prefix,$part)=@_;
11932: my $keyroot;
11933: if (defined($prefix) && $prefix !~ /^__/) {
11934: # prefix that has a part already
11935: $keyroot=$prefix;
11936: } elsif (defined($prefix)) {
11937: # prefix that is missing a part
11938: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11939: } else {
11940: # no prefix at all
11941: if (defined($part)) { $keyroot='_'.$part; }
11942: }
11943: return $keyroot;
11944: }
11945:
1.71 www 11946: # ---------------------------------------------------------------- Get metadata
11947:
1.599 albertel 11948: my %metaentry;
1.1070 www 11949: my %importedpartids;
1.1172.2.99 raeburn 11950: my %importedrespids;
1.71 www 11951: sub metadata {
1.176 www 11952: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11953: $uri=&declutter($uri);
1.288 albertel 11954: # if it is a non metadata possible uri return quickly
1.529 albertel 11955: if (($uri eq '') ||
11956: (($uri =~ m|^/*adm/|) &&
1.1172.2.118. .1(raebu 11957:20): ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 11958: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11959: return undef;
11960: }
1.1172.2.49 raeburn 11961: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11962: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11963: return undef;
1.288 albertel 11964: }
1.73 www 11965: my $filename=$uri;
11966: $uri=~s/\.meta$//;
1.172 www 11967: #
11968: # Is the metadata already cached?
1.177 www 11969: # Look at timestamp of caching
1.172 www 11970: # Everything is cached by the main uri, libraries are never directly cached
11971: #
1.428 albertel 11972: if (!defined($liburi)) {
1.599 albertel 11973: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11974: if (defined($cached)) { return $result->{':'.$what}; }
11975: }
11976: {
1.1069 www 11977: # Imported parts would go here
1.1172.2.99 raeburn 11978: my @origfiletagids=();
1.1069 www 11979: my $importedparts=0;
1.1172.2.99 raeburn 11980:
11981: # Imported responseids would go here
11982: my $importedresponses=0;
1.172 www 11983: #
11984: # Is this a recursive call for a library?
11985: #
1.599 albertel 11986: # if (! exists($metacache{$uri})) {
11987: # $metacache{$uri}={};
11988: # }
1.924 albertel 11989: my $cachetime = 60*60;
1.171 www 11990: if ($liburi) {
11991: $liburi=&declutter($liburi);
11992: $filename=$liburi;
1.401 bowersj2 11993: } else {
1.599 albertel 11994: &devalidate_cache_new('meta',$uri);
11995: undef(%metaentry);
1.401 bowersj2 11996: }
1.140 www 11997: my %metathesekeys=();
1.73 www 11998: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11999: my $metastring;
1.1140 www 12000: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12001: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12002: $metastring =
1.929 albertel 12003: &Apache::lonnet::ssi_body($which,
1.924 albertel 12004: ('grade_target' => 'meta'));
12005: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12006: } elsif (($uri !~ m -^(editupload)/-) &&
12007: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12008: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12009: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12010: $metastring=&getfile($file);
1.489 albertel 12011: }
1.208 albertel 12012: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12013: my $token;
1.140 www 12014: undef %metathesekeys;
1.71 www 12015: while ($token=$parser->get_token) {
1.339 albertel 12016: if ($token->[0] eq 'S') {
12017: if (defined($token->[2]->{'package'})) {
1.172 www 12018: #
12019: # This is a package - get package info
12020: #
1.339 albertel 12021: my $package=$token->[2]->{'package'};
12022: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12023: if (defined($token->[2]->{'id'})) {
12024: $keyroot.='_'.$token->[2]->{'id'};
12025: }
1.599 albertel 12026: if ($metaentry{':packages'}) {
12027: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12028: } else {
1.599 albertel 12029: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12030: }
1.736 albertel 12031: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12032: my $part=$keyroot;
12033: $part=~s/^\_//;
1.736 albertel 12034: if ($pack_entry=~/^\Q$package\E\&/ ||
12035: $pack_entry=~/^\Q$package\E_0\&/) {
12036: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12037: # ignore package.tab specified default values
12038: # here &package_tab_default() will fetch those
12039: if ($subp eq 'default') { next; }
1.736 albertel 12040: my $value=$packagetab{$pack_entry};
1.432 albertel 12041: my $unikey;
12042: if ($pack =~ /_0$/) {
12043: $unikey='parameter_0_'.$name;
12044: $part=0;
12045: } else {
12046: $unikey='parameter'.$keyroot.'_'.$name;
12047: }
1.339 albertel 12048: if ($subp eq 'display') {
12049: $value.=' [Part: '.$part.']';
12050: }
1.599 albertel 12051: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12052: $metathesekeys{$unikey}=1;
1.599 albertel 12053: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12054: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12055: }
1.599 albertel 12056: if (defined($metaentry{':'.$unikey.'.default'})) {
12057: $metaentry{':'.$unikey}=
12058: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12059: }
1.339 albertel 12060: }
12061: }
12062: } else {
1.172 www 12063: #
12064: # This is not a package - some other kind of start tag
1.339 albertel 12065: #
12066: my $entry=$token->[1];
1.1068 www 12067: my $unikey='';
1.175 www 12068:
1.339 albertel 12069: if ($entry eq 'import') {
1.175 www 12070: #
12071: # Importing a library here
1.339 albertel 12072: #
1.1067 www 12073: my $location=$parser->get_text('/import');
12074: my $dir=$filename;
12075: $dir=~s|[^/]*$||;
12076: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 12077:
12078: my $importid=$token->[2]->{'id'};
1.1068 www 12079: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 12080: #
12081: # Check metadata for imported file to
12082: # see if it contained response items
12083: #
12084: my %currmetaentry = %metaentry;
12085: my $libresponseorder = &metadata($location,'responseorder');
12086: my $origfile;
12087: if ($libresponseorder ne '') {
12088: if ($#origfiletagids<0) {
12089: undef(%importedrespids);
12090: undef(%importedpartids);
12091: }
12092: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12093: if (@{$importedrespids{$importid}} > 0) {
12094: $importedresponses = 1;
12095: # We need to get the original file and the imported file to get the response order correct
12096: # Load and inspect original file
12097: if ($#origfiletagids<0) {
12098: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12099: $origfile=&getfile($origfilelocation);
12100: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12101: }
12102: }
12103: }
12104: # Do not overwrite contents of %metaentry hash for resource itself with
12105: # hash populated for imported library file
12106: %metaentry = %currmetaentry;
12107: undef(%currmetaentry);
1.1068 www 12108: if ($importmode eq 'problem') {
1.1069 www 12109: # Import as problem/response
1.1068 www 12110: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12111: } elsif ($importmode eq 'part') {
12112: # Import as part(s)
1.1069 www 12113: $importedparts=1;
12114: # We need to get the original file and the imported file to get the part order correct
12115: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 12116: # Load and inspect original file if we didn't do that already
12117: if ($#origfiletagids<0) {
12118: undef(%importedrespids);
12119: undef(%importedpartids);
12120: if ($origfile eq '') {
12121: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12122: $origfile=&getfile($origfilelocation);
12123: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12124: }
1.1070 www 12125: }
12126:
1.1069 www 12127: # Load and inspect imported file
12128: my $impfile=&getfile($location);
12129: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12130: if ($#impfilepartids>=0) {
12131: # This problem had parts
1.1070 www 12132: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12133: } else {
12134: # Importing by turning a single problem into a problem part
12135: # It gets the import-tags ID as part-ID
12136: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12137: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12138: }
1.1068 www 12139: } else {
12140: # Normal import
12141: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12142: if (defined($token->[2]->{'id'})) {
12143: $unikey.='_'.$token->[2]->{'id'};
12144: }
1.1067 www 12145: }
12146:
1.339 albertel 12147: if ($depthcount<20) {
1.736 albertel 12148: my $metadata =
12149: &metadata($uri,'keys', $location,$unikey,
12150: $depthcount+1);
12151: foreach my $meta (split(',',$metadata)) {
12152: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12153: $metathesekeys{$meta}=1;
1.339 albertel 12154: }
1.1068 www 12155:
12156: }
1.1067 www 12157: } else {
12158: #
12159: # Not importing, some other kind of non-package, non-library start tag
12160: #
12161: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12162: if (defined($token->[2]->{'id'})) {
12163: $unikey.='_'.$token->[2]->{'id'};
12164: }
1.339 albertel 12165: if (defined($token->[2]->{'name'})) {
12166: $unikey.='_'.$token->[2]->{'name'};
12167: }
12168: $metathesekeys{$unikey}=1;
1.736 albertel 12169: foreach my $param (@{$token->[3]}) {
12170: $metaentry{':'.$unikey.'.'.$param} =
12171: $token->[2]->{$param};
1.339 albertel 12172: }
12173: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12174: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12175: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12176: # only ws inside the tag, and not in default, so use default
12177: # as value
1.599 albertel 12178: $metaentry{':'.$unikey}=$default;
1.908 albertel 12179: } elsif ( $internaltext =~ /\S/ ) {
12180: # something interesting inside the tag
12181: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12182: } else {
1.908 albertel 12183: # no interesting values, don't set a default
1.339 albertel 12184: }
1.172 www 12185: # end of not-a-package not-a-library import
1.339 albertel 12186: }
1.172 www 12187: # end of not-a-package start tag
1.339 albertel 12188: }
1.172 www 12189: # the next is the end of "start tag"
1.339 albertel 12190: }
12191: }
1.483 albertel 12192: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12193: $extension = lc($extension);
12194: if ($extension eq 'htm') { $extension='html'; }
12195:
1.737 albertel 12196: foreach my $key (keys(%packagetab)) {
1.483 albertel 12197: #no specific packages #how's our extension
12198: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12199: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12200: \%metathesekeys);
12201: }
1.883 albertel 12202:
12203: if (!exists($metaentry{':packages'})
12204: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12205: foreach my $key (keys(%packagetab)) {
1.483 albertel 12206: #no specific packages well let's get default then
12207: if ($key!~/^default&/) { next; }
1.488 albertel 12208: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12209: \%metathesekeys);
12210: }
12211: }
1.338 www 12212: # are there custom rights to evaluate
1.599 albertel 12213: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12214:
1.338 www 12215: #
12216: # Importing a rights file here
1.339 albertel 12217: #
12218: unless ($depthcount) {
1.599 albertel 12219: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12220: my $dir=$filename;
12221: $dir=~s|[^/]*$||;
12222: $location=&filelocation($dir,$location);
1.736 albertel 12223: my $rights_metadata =
12224: &metadata($uri,'keys',$location,'_rights',
12225: $depthcount+1);
12226: foreach my $rights (split(',',$rights_metadata)) {
12227: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12228: $metathesekeys{$rights}=1;
1.339 albertel 12229: }
12230: }
12231: }
1.737 albertel 12232: # uniqifiy package listing
12233: my %seen;
12234: my @uniq_packages =
12235: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12236: $metaentry{':packages'} = join(',',@uniq_packages);
12237:
1.1172.2.99 raeburn 12238: if (($importedresponses) || ($importedparts)) {
12239: if ($importedparts) {
1.1070 www 12240: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 12241: $metaentry{':partorder'}='';
12242: $metathesekeys{'partorder'}=1;
12243: }
12244: if ($importedresponses) {
12245: # We had imported responses and need to rebuild responseorder
12246: $metaentry{':responseorder'}='';
12247: $metathesekeys{'responseorder'}=1;
12248: }
12249: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12250: my $origid = $origfiletagids[$index+1];
12251: if ($origfiletagids[$index] eq 'part') {
12252: # Original part, part of the problem
12253: if ($importedparts) {
12254: $metaentry{':partorder'}.=','.$origid;
12255: }
12256: } elsif ($origfiletagids[$index] eq 'import') {
12257: if ($importedparts) {
12258: # We have imported parts at this position
12259: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12260: }
12261: if ($importedresponses) {
12262: # We have imported responses at this position
12263: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12264: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12265: }
12266: }
12267: } else {
12268: # Original response item, part of the problem
12269: if ($importedresponses) {
12270: $metaentry{':responseorder'}.=','.$origid;
12271: }
12272: }
12273: }
12274: if ($importedparts) {
12275: $metaentry{':partorder'}=~s/^\,//;
12276: }
12277: if ($importedresponses) {
12278: $metaentry{':responseorder'}=~s/^\,//;
12279: }
1.1070 www 12280: }
12281:
1.737 albertel 12282: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12283: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12284: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12285: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12286: # this is the end of "was not already recently cached
1.71 www 12287: }
1.599 albertel 12288: return $metaentry{':'.$what};
1.261 albertel 12289: }
12290:
1.488 albertel 12291: sub metadata_create_package_def {
1.483 albertel 12292: my ($uri,$key,$package,$metathesekeys)=@_;
12293: my ($pack,$name,$subp)=split(/\&/,$key);
12294: if ($subp eq 'default') { next; }
12295:
1.599 albertel 12296: if (defined($metaentry{':packages'})) {
12297: $metaentry{':packages'}.=','.$package;
1.483 albertel 12298: } else {
1.599 albertel 12299: $metaentry{':packages'}=$package;
1.483 albertel 12300: }
12301: my $value=$packagetab{$key};
12302: my $unikey;
12303: $unikey='parameter_0_'.$name;
1.599 albertel 12304: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12305: $$metathesekeys{$unikey}=1;
1.599 albertel 12306: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12307: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12308: }
1.599 albertel 12309: if (defined($metaentry{':'.$unikey.'.default'})) {
12310: $metaentry{':'.$unikey}=
12311: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12312: }
12313: }
12314:
1.261 albertel 12315: sub metadata_generate_part0 {
12316: my ($metadata,$metacache,$uri) = @_;
12317: my %allnames;
1.737 albertel 12318: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12319: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12320: my $part=$$metacache{':'.$metakey.'.part'};
12321: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12322: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12323: $allnames{$name}=$part;
12324: }
12325: }
12326: }
12327: foreach my $name (keys(%allnames)) {
12328: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12329: my $key=":parameter_0_$name";
1.261 albertel 12330: $$metacache{"$key.part"}='0';
12331: $$metacache{"$key.name"}=$name;
1.428 albertel 12332: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12333: $allnames{$name}.'_'.$name.
12334: '.type'};
1.428 albertel 12335: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12336: '.display'};
1.644 www 12337: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12338: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12339: $$metacache{"$key.display"}=$olddis;
12340: }
1.71 www 12341: }
12342:
1.764 albertel 12343: # ------------------------------------------------------ Devalidate title cache
12344:
12345: sub devalidate_title_cache {
12346: my ($url)=@_;
12347: if (!$env{'request.course.id'}) { return; }
12348: my $symb=&symbread($url);
12349: if (!$symb) { return; }
12350: my $key=$env{'request.course.id'}."\0".$symb;
12351: &devalidate_cache_new('title',$key);
12352: }
12353:
1.1014 droeschl 12354: # ------------------------------------------------- Get the title of a course
12355:
12356: sub current_course_title {
12357: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12358: }
1.301 www 12359: # ------------------------------------------------- Get the title of a resource
12360:
12361: sub gettitle {
12362: my $urlsymb=shift;
12363: my $symb=&symbread($urlsymb);
1.534 albertel 12364: if ($symb) {
1.620 albertel 12365: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12366: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12367: if (defined($cached)) {
12368: return $result;
12369: }
1.534 albertel 12370: my ($map,$resid,$url)=&decode_symb($symb);
12371: my $title='';
1.907 albertel 12372: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12373: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12374: } else {
12375: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12376: &GDBM_READER(),0640)) {
12377: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12378: $title=$bighash{'title_'.$mapid.'.'.$resid};
12379: untie(%bighash);
12380: }
1.534 albertel 12381: }
12382: $title=~s/\&colon\;/\:/gs;
12383: if ($title) {
1.1159 www 12384: # Remember both $symb and $title for dynamic metadata
12385: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12386: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12387: # Cache this title and then return it
1.599 albertel 12388: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12389: }
12390: $urlsymb=$url;
12391: }
12392: my $title=&metadata($urlsymb,'title');
12393: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12394: return $title;
1.301 www 12395: }
1.613 albertel 12396:
1.614 albertel 12397: sub get_slot {
12398: my ($which,$cnum,$cdom)=@_;
12399: if (!$cnum || !$cdom) {
1.790 albertel 12400: (undef,my $courseid)=&whichuser();
1.620 albertel 12401: $cdom=$env{'course.'.$courseid.'.domain'};
12402: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12403: }
1.703 albertel 12404: my $key=join("\0",'slots',$cdom,$cnum,$which);
12405: my %slotinfo;
12406: if (exists($remembered{$key})) {
12407: $slotinfo{$which} = $remembered{$key};
12408: } else {
12409: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12410: &Apache::lonhomework::showhash(%slotinfo);
12411: my ($tmp)=keys(%slotinfo);
12412: if ($tmp=~/^error:/) { return (); }
12413: $remembered{$key} = $slotinfo{$which};
12414: }
1.616 albertel 12415: if (ref($slotinfo{$which}) eq 'HASH') {
12416: return %{$slotinfo{$which}};
12417: }
12418: return $slotinfo{$which};
1.614 albertel 12419: }
1.1150 raeburn 12420:
12421: sub get_reservable_slots {
12422: my ($cnum,$cdom,$uname,$udom) = @_;
12423: my $now = time;
12424: my $reservable_info;
12425: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12426: if (exists($remembered{$key})) {
12427: $reservable_info = $remembered{$key};
12428: } else {
12429: my %resv;
12430: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12431: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12432: $reservable_info = \%resv;
12433: $remembered{$key} = $reservable_info;
12434: }
12435: return $reservable_info;
12436: }
12437:
12438: sub get_course_slots {
12439: my ($cnum,$cdom) = @_;
12440: my $hashid=$cnum.':'.$cdom;
12441: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12442: if (defined($cached)) {
12443: if (ref($result) eq 'HASH') {
12444: return %{$result};
12445: }
12446: } else {
12447: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12448: my ($tmp) = keys(%slots);
12449: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12450: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12451: return %slots;
12452: }
12453: }
12454: return;
12455: }
12456:
12457: sub devalidate_slots_cache {
12458: my ($cnum,$cdom)=@_;
12459: my $hashid=$cnum.':'.$cdom;
12460: &devalidate_cache_new('allslots',$hashid);
12461: }
12462:
1.1172.2.8 raeburn 12463: sub get_coursechange {
12464: my ($cdom,$cnum) = @_;
12465: if ($cdom eq '' || $cnum eq '') {
12466: return unless ($env{'request.course.id'});
12467: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12468: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12469: }
12470: my $hashid=$cdom.'_'.$cnum;
12471: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12472: if ((defined($cached)) && ($change ne '')) {
12473: return $change;
12474: } else {
12475: my %crshash;
12476: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12477: if ($crshash{'internal.contentchange'} eq '') {
12478: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12479: if ($change eq '') {
12480: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12481: $change = $crshash{'internal.created'};
12482: }
12483: } else {
12484: $change = $crshash{'internal.contentchange'};
12485: }
12486: my $cachetime = 600;
12487: &do_cache_new('crschange',$hashid,$change,$cachetime);
12488: }
12489: return $change;
12490: }
12491:
12492: sub devalidate_coursechange_cache {
12493: my ($cnum,$cdom)=@_;
12494: my $hashid=$cnum.':'.$cdom;
12495: &devalidate_cache_new('crschange',$hashid);
12496: }
12497:
1.31 www 12498: # ------------------------------------------------- Update symbolic store links
12499:
12500: sub symblist {
12501: my ($mapname,%newhash)=@_;
1.438 www 12502: $mapname=&deversion(&declutter($mapname));
1.31 www 12503: my %hash;
1.620 albertel 12504: if (($env{'request.course.fn'}) && (%newhash)) {
12505: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12506: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12507: foreach my $url (keys(%newhash)) {
1.711 albertel 12508: next if ($url eq 'last_known'
12509: && $env{'form.no_update_last_known'});
12510: $hash{declutter($url)}=&encode_symb($mapname,
12511: $newhash{$url}->[1],
12512: $newhash{$url}->[0]);
1.191 harris41 12513: }
1.31 www 12514: if (untie(%hash)) {
12515: return 'ok';
12516: }
12517: }
12518: }
12519: return 'error';
1.212 www 12520: }
12521:
12522: # --------------------------------------------------------------- Verify a symb
12523:
12524: sub symbverify {
1.1172.2.11 raeburn 12525: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12526: my $thisfn=$thisurl;
1.439 www 12527: $thisfn=&declutter($thisfn);
1.215 www 12528: # direct jump to resource in page or to a sequence - will construct own symbs
12529: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12530: # check URL part
1.409 www 12531: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12532:
1.431 www 12533: unless ($url eq $thisfn) { return 0; }
1.213 www 12534:
1.216 www 12535: $symb=&symbclean($symb);
1.510 www 12536: $thisurl=&deversion($thisurl);
1.439 www 12537: $thisfn=&deversion($thisfn);
1.213 www 12538:
12539: my %bighash;
12540: my $okay=0;
1.431 www 12541:
1.620 albertel 12542: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12543: &GDBM_READER(),0640)) {
1.1032 raeburn 12544: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12545: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12546: if ($map =~ m{^uploaded/.+\.page$}) {
12547: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12548: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12549: }
12550: }
12551: my $ids;
1.1172.2.118. .5(raebu 12552:20): if ($map =~ m{^uploaded/.+\.page$}) {
12553:20): $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12554: } else {
12555: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12556: }
1.1102 raeburn 12557: unless ($ids) {
1.1172.2.13 raeburn 12558: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12559: $ids=$bighash{$idkey};
1.216 www 12560: }
12561: if ($ids) {
12562: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12563: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12564: $symb =~ s/\?.+$//;
12565: }
1.800 albertel 12566: foreach my $id (split(/\,/,$ids)) {
12567: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12568: if (
12569: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12570: eq $symb) {
1.1172.2.11 raeburn 12571: if (ref($encstate)) {
12572: $$encstate = $bighash{'encrypted_'.$id};
12573: }
1.1172.2.13 raeburn 12574: if (($env{'request.role.adv'}) ||
12575: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12576: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12577: $okay=1;
12578: last;
12579: }
12580: }
12581: }
1.216 www 12582: }
1.213 www 12583: untie(%bighash);
12584: }
12585: return $okay;
1.31 www 12586: }
12587:
1.210 www 12588: # --------------------------------------------------------------- Clean-up symb
12589:
12590: sub symbclean {
12591: my $symb=shift;
1.568 albertel 12592: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12593: # remove version from map
12594: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12595:
1.210 www 12596: # remove version from URL
12597: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12598:
1.507 www 12599: # remove wrapper
12600:
1.510 www 12601: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12602: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12603: return $symb;
1.409 www 12604: }
12605:
12606: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12607:
12608: sub encode_symb {
12609: my ($map,$resid,$url)=@_;
12610: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12611: }
1.409 www 12612:
12613: sub decode_symb {
1.568 albertel 12614: my $symb=shift;
12615: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12616: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12617: return (&fixversion($map),$resid,&fixversion($url));
12618: }
12619:
12620: sub fixversion {
12621: my $fn=shift;
1.609 banghart 12622: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12623: my %bighash;
12624: my $uri=&clutter($fn);
1.620 albertel 12625: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12626: # is this cached?
1.599 albertel 12627: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12628: if (defined($cached)) { return $result; }
12629: # unfortunately not cached, or expired
1.620 albertel 12630: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12631: &GDBM_READER(),0640)) {
12632: if ($bighash{'version_'.$uri}) {
12633: my $version=$bighash{'version_'.$uri};
1.444 www 12634: unless (($version eq 'mostrecent') ||
12635: ($version==&getversion($uri))) {
1.440 www 12636: $uri=~s/\.(\w+)$/\.$version\.$1/;
12637: }
12638: }
12639: untie %bighash;
1.413 www 12640: }
1.599 albertel 12641: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12642: }
12643:
12644: sub deversion {
12645: my $url=shift;
12646: $url=~s/\.\d+\.(\w+)$/\.$1/;
12647: return $url;
1.210 www 12648: }
12649:
1.31 www 12650: # ------------------------------------------------------ Return symb list entry
12651:
12652: sub symbread {
1.1172.2.118. .8(raebu 12653:20): my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
.9(raebu 12654:20): $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 12655: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.118. .9(raebu 12656:20): if (defined($env{$cache_str})) {
.8(raebu 12657:20): unless (ref($possibles) eq 'HASH') {
12658:20): if ($ignorecachednull) {
12659:20): return $env{$cache_str} unless ($env{$cache_str} eq '');
12660:20): } else {
12661:20): return $env{$cache_str};
12662:20): }
1.1172.2.66 raeburn 12663: }
12664: }
1.242 www 12665: # no filename provided? try from environment
1.1172.2.54 raeburn 12666: unless ($thisfn) {
1.620 albertel 12667: if ($env{'request.symb'}) {
1.1172.2.118. .9(raebu 12668:20): return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 12669: }
12670: $thisfn=$env{'request.filename'};
1.44 www 12671: }
1.569 albertel 12672: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12673: # is that filename actually a symb? Verify, clean, and return
12674: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12675: if (&symbverify($thisfn,$1)) {
1.1172.2.118. .9(raebu 12676:20): return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12677: }
1.242 www 12678: }
1.44 www 12679: $thisfn=declutter($thisfn);
1.31 www 12680: my %hash;
1.37 www 12681: my %bighash;
12682: my $syval='';
1.620 albertel 12683: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12684: my $targetfn = $thisfn;
1.609 banghart 12685: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12686: $targetfn = 'adm/wrapper/'.$thisfn;
12687: }
1.687 albertel 12688: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12689: $targetfn=$1;
12690: }
1.1172.2.118. .9(raebu 12691:20): unless ($ignoresymbdb) {
.8(raebu 12692:20): if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12693:20): &GDBM_READER(),0640)) {
12694:20): $syval=$hash{$targetfn};
12695:20): untie(%hash);
12696:20): }
.9(raebu 12697:20): if ($syval && $checkforblock) {
12698:20): my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
.8(raebu 12699:20): if (@blockers) {
12700:20): $syval='';
12701:20): }
12702:20): }
1.37 www 12703: }
12704: # ---------------------------------------------------------- There was an entry
12705: if ($syval) {
1.601 albertel 12706: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12707: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12708: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12709: #return $env{$cache_str}='';
1.601 albertel 12710: #}
12711: #$syval.=$1;
12712: #}
1.37 www 12713: } else {
12714: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12715: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12716: &GDBM_READER(),0640)) {
1.37 www 12717: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12718: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12719: unless ($ids) {
12720: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12721: }
12722: unless ($ids) {
12723: # alias?
12724: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12725: }
1.37 www 12726: if ($ids) {
12727: # ------------------------------------------------------------------- Has ID(s)
12728: my @possibilities=split(/\,/,$ids);
1.39 www 12729: if ($#possibilities==0) {
12730: # ----------------------------------------------- There is only one possibility
1.37 www 12731: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12732: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12733: $resid,$thisfn);
1.1172.2.66 raeburn 12734: if (ref($possibles) eq 'HASH') {
1.1172.2.118. .8(raebu 12735:20): unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12736:20): $possibles->{$syval} = 1;
12737:20): }
1.1172.2.66 raeburn 12738: }
12739: if ($checkforblock) {
1.1172.2.118. .8(raebu 12740:20): unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12741:20): my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
12742:20): if (@blockers) {
12743:20): $syval = '';
12744:20): untie(%bighash);
12745:20): return $env{$cache_str}='';
12746:20): }
1.1172.2.66 raeburn 12747: }
12748: }
12749: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12750: # ------------------------------------------ There is more than one possibility
12751: my $realpossible=0;
1.800 albertel 12752: foreach my $id (@possibilities) {
12753: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12754: my $canaccess;
12755: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12756: $canaccess = 1;
12757: } else {
12758: $canaccess = &allowed('bre',$file);
12759: }
12760: if ($canaccess) {
12761: my ($mapid,$resid)=split(/\./,$id);
12762: if ($bighash{'map_type_'.$mapid} ne 'page') {
12763: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12764: $resid,$thisfn);
1.1172.2.118. .8(raebu 12765:20): next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
12766:20): next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 12767: if ($checkforblock) {
1.1172.2.118. .8(raebu 12768:20): my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
12769:20): if (@blockers > 0) {
12770:20): $syval = '';
12771:20): } else {
1.1172.2.66 raeburn 12772: $syval = $poss_syval;
12773: $realpossible++;
12774: }
12775: } else {
12776: $syval = $poss_syval;
12777: $realpossible++;
12778: }
1.1172.2.118. .8(raebu 12779:20): if ($syval) {
12780:20): if (ref($possibles) eq 'HASH') {
12781:20): $possibles->{$syval} = 1;
12782:20): }
12783:20): }
1.1172.2.66 raeburn 12784: }
1.39 www 12785: }
1.191 harris41 12786: }
1.39 www 12787: if ($realpossible!=1) { $syval=''; }
1.249 www 12788: } else {
12789: $syval='';
1.37 www 12790: }
12791: }
1.1172.2.66 raeburn 12792: untie(%bighash);
1.481 raeburn 12793: }
1.31 www 12794: }
1.62 www 12795: if ($syval) {
1.1172.2.118. .9(raebu 12796:20): return $env{$cache_str}=$syval;
1.62 www 12797: }
1.31 www 12798: }
1.949 raeburn 12799: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12800: return $env{$cache_str}='';
1.31 www 12801: }
12802:
12803: # ---------------------------------------------------------- Return random seed
12804:
1.32 www 12805: sub numval {
12806: my $txt=shift;
12807: $txt=~tr/A-J/0-9/;
12808: $txt=~tr/a-j/0-9/;
12809: $txt=~tr/K-T/0-9/;
12810: $txt=~tr/k-t/0-9/;
12811: $txt=~tr/U-Z/0-5/;
12812: $txt=~tr/u-z/0-5/;
12813: $txt=~s/\D//g;
1.564 albertel 12814: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12815: return int($txt);
1.368 albertel 12816: }
12817:
1.484 albertel 12818: sub numval2 {
12819: my $txt=shift;
12820: $txt=~tr/A-J/0-9/;
12821: $txt=~tr/a-j/0-9/;
12822: $txt=~tr/K-T/0-9/;
12823: $txt=~tr/k-t/0-9/;
12824: $txt=~tr/U-Z/0-5/;
12825: $txt=~tr/u-z/0-5/;
12826: $txt=~s/\D//g;
12827: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12828: my $total;
12829: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12830: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12831: return int($total);
12832: }
12833:
1.575 albertel 12834: sub numval3 {
12835: use integer;
12836: my $txt=shift;
12837: $txt=~tr/A-J/0-9/;
12838: $txt=~tr/a-j/0-9/;
12839: $txt=~tr/K-T/0-9/;
12840: $txt=~tr/k-t/0-9/;
12841: $txt=~tr/U-Z/0-5/;
12842: $txt=~tr/u-z/0-5/;
12843: $txt=~s/\D//g;
12844: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12845: my $total;
12846: foreach my $val (@txts) { $total+=$val; }
12847: if ($_64bit) { $total=(($total<<32)>>32); }
12848: return $total;
12849: }
12850:
1.675 albertel 12851: sub digest {
12852: my ($data)=@_;
12853: my $digest=&Digest::MD5::md5($data);
12854: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12855: my ($e,$f);
12856: {
12857: use integer;
12858: $e=($a+$b);
12859: $f=($c+$d);
12860: if ($_64bit) {
12861: $e=(($e<<32)>>32);
12862: $f=(($f<<32)>>32);
12863: }
12864: }
12865: if (wantarray) {
12866: return ($e,$f);
12867: } else {
12868: my $g;
12869: {
12870: use integer;
12871: $g=($e+$f);
12872: if ($_64bit) {
12873: $g=(($g<<32)>>32);
12874: }
12875: }
12876: return $g;
12877: }
12878: }
12879:
1.368 albertel 12880: sub latest_rnd_algorithm_id {
1.675 albertel 12881: return '64bit5';
1.366 albertel 12882: }
1.32 www 12883:
1.503 albertel 12884: sub get_rand_alg {
12885: my ($courseid)=@_;
1.790 albertel 12886: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12887: if ($courseid) {
1.620 albertel 12888: return $env{"course.$courseid.rndseed"};
1.503 albertel 12889: }
12890: return &latest_rnd_algorithm_id();
12891: }
12892:
1.562 albertel 12893: sub validCODE {
12894: my ($CODE)=@_;
12895: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12896: return 0;
12897: }
12898:
1.491 albertel 12899: sub getCODE {
1.620 albertel 12900: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12901: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12902: defined($Apache::lonhomework::parsing_a_task) ) &&
12903: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12904: return $Apache::lonhomework::history{'resource.CODE'};
12905: }
12906: return undef;
12907: }
1.1133 foxr 12908: #
12909: # Determines the random seed for a specific context:
12910: #
12911: # parameters:
12912: # symb - in course context the symb for the seed.
12913: # course_id - The course id of the form domain_coursenum.
12914: # domain - Domain for the user.
12915: # course - Course for the user.
12916: # cenv - environment of the course.
12917: #
12918: # NOTE:
12919: # All parameters are picked out of the environment if missing
12920: # or not defined.
12921: # If a symb cannot be determined the current time is used instead.
12922: #
12923: # For a given well defined symb, courside, domain, username,
12924: # and course environment, the seed is reproducible.
12925: #
1.31 www 12926: sub rndseed {
1.1133 foxr 12927: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12928: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12929: if (!defined($symb)) {
1.366 albertel 12930: unless ($symb=$wsymb) { return time; }
12931: }
1.1146 foxr 12932: if (!defined $courseid) {
12933: $courseid=$wcourseid;
12934: }
12935: if (!defined $domain) { $domain=$wdomain; }
12936: if (!defined $username) { $username=$wusername }
1.1133 foxr 12937:
12938: my $which;
12939: if (defined($cenv->{'rndseed'})) {
12940: $which = $cenv->{'rndseed'};
12941: } else {
12942: $which =&get_rand_alg($courseid);
12943: }
1.491 albertel 12944: if (defined(&getCODE())) {
1.675 albertel 12945: if ($which eq '64bit5') {
12946: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12947: } elsif ($which eq '64bit4') {
1.575 albertel 12948: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12949: } else {
12950: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12951: }
1.675 albertel 12952: } elsif ($which eq '64bit5') {
12953: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12954: } elsif ($which eq '64bit4') {
12955: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12956: } elsif ($which eq '64bit3') {
12957: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12958: } elsif ($which eq '64bit2') {
12959: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12960: } elsif ($which eq '64bit') {
12961: return &rndseed_64bit($symb,$courseid,$domain,$username);
12962: }
12963: return &rndseed_32bit($symb,$courseid,$domain,$username);
12964: }
12965:
12966: sub rndseed_32bit {
12967: my ($symb,$courseid,$domain,$username)=@_;
12968: {
12969: use integer;
12970: my $symbchck=unpack("%32C*",$symb) << 27;
12971: my $symbseed=numval($symb) << 22;
12972: my $namechck=unpack("%32C*",$username) << 17;
12973: my $nameseed=numval($username) << 12;
12974: my $domainseed=unpack("%32C*",$domain) << 7;
12975: my $courseseed=unpack("%32C*",$courseid);
12976: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12977: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12978: #&logthis("rndseed :$num:$symb");
1.564 albertel 12979: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12980: return $num;
12981: }
12982: }
12983:
12984: sub rndseed_64bit {
12985: my ($symb,$courseid,$domain,$username)=@_;
12986: {
12987: use integer;
12988: my $symbchck=unpack("%32S*",$symb) << 21;
12989: my $symbseed=numval($symb) << 10;
12990: my $namechck=unpack("%32S*",$username);
12991:
12992: my $nameseed=numval($username) << 21;
12993: my $domainseed=unpack("%32S*",$domain) << 10;
12994: my $courseseed=unpack("%32S*",$courseid);
12995:
12996: my $num1=$symbchck+$symbseed+$namechck;
12997: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12998: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12999: #&logthis("rndseed :$num:$symb");
1.564 albertel 13000: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13001: return "$num1,$num2";
1.155 albertel 13002: }
1.366 albertel 13003: }
13004:
1.443 albertel 13005: sub rndseed_64bit2 {
13006: my ($symb,$courseid,$domain,$username)=@_;
13007: {
13008: use integer;
13009: # strings need to be an even # of cahracters long, it it is odd the
13010: # last characters gets thrown away
13011: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13012: my $symbseed=numval($symb) << 10;
13013: my $namechck=unpack("%32S*",$username.' ');
13014:
13015: my $nameseed=numval($username) << 21;
1.501 albertel 13016: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13017: my $courseseed=unpack("%32S*",$courseid.' ');
13018:
13019: my $num1=$symbchck+$symbseed+$namechck;
13020: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13021: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13022: #&logthis("rndseed :$num:$symb");
1.803 albertel 13023: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13024: return "$num1,$num2";
13025: }
13026: }
13027:
13028: sub rndseed_64bit3 {
13029: my ($symb,$courseid,$domain,$username)=@_;
13030: {
13031: use integer;
13032: # strings need to be an even # of cahracters long, it it is odd the
13033: # last characters gets thrown away
13034: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13035: my $symbseed=numval2($symb) << 10;
13036: my $namechck=unpack("%32S*",$username.' ');
13037:
13038: my $nameseed=numval2($username) << 21;
1.443 albertel 13039: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13040: my $courseseed=unpack("%32S*",$courseid.' ');
13041:
13042: my $num1=$symbchck+$symbseed+$namechck;
13043: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13044: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13045: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13046: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13047:
1.503 albertel 13048: return "$num1:$num2";
1.443 albertel 13049: }
13050: }
13051:
1.575 albertel 13052: sub rndseed_64bit4 {
13053: my ($symb,$courseid,$domain,$username)=@_;
13054: {
13055: use integer;
13056: # strings need to be an even # of cahracters long, it it is odd the
13057: # last characters gets thrown away
13058: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13059: my $symbseed=numval3($symb) << 10;
13060: my $namechck=unpack("%32S*",$username.' ');
13061:
13062: my $nameseed=numval3($username) << 21;
13063: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13064: my $courseseed=unpack("%32S*",$courseid.' ');
13065:
13066: my $num1=$symbchck+$symbseed+$namechck;
13067: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13068: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13069: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13070: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13071:
1.575 albertel 13072: return "$num1:$num2";
13073: }
13074: }
13075:
1.675 albertel 13076: sub rndseed_64bit5 {
13077: my ($symb,$courseid,$domain,$username)=@_;
13078: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13079: return "$num1:$num2";
13080: }
13081:
1.366 albertel 13082: sub rndseed_CODE_64bit {
13083: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13084: {
1.366 albertel 13085: use integer;
1.443 albertel 13086: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13087: my $symbseed=numval2($symb);
1.491 albertel 13088: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13089: my $CODEseed=numval(&getCODE());
1.443 albertel 13090: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13091: my $num1=$symbseed+$CODEchck;
13092: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13093: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13094: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13095: if ($_64bit) { $num1=(($num1<<32)>>32); }
13096: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13097: return "$num1:$num2";
1.366 albertel 13098: }
13099: }
13100:
1.575 albertel 13101: sub rndseed_CODE_64bit4 {
13102: my ($symb,$courseid,$domain,$username)=@_;
13103: {
13104: use integer;
13105: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13106: my $symbseed=numval3($symb);
13107: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13108: my $CODEseed=numval3(&getCODE());
13109: my $courseseed=unpack("%32S*",$courseid.' ');
13110: my $num1=$symbseed+$CODEchck;
13111: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13112: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13113: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13114: if ($_64bit) { $num1=(($num1<<32)>>32); }
13115: if ($_64bit) { $num2=(($num2<<32)>>32); }
13116: return "$num1:$num2";
13117: }
13118: }
13119:
1.675 albertel 13120: sub rndseed_CODE_64bit5 {
13121: my ($symb,$courseid,$domain,$username)=@_;
13122: my $code = &getCODE();
13123: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13124: return "$num1:$num2";
13125: }
13126:
1.366 albertel 13127: sub setup_random_from_rndseed {
13128: my ($rndseed)=@_;
1.503 albertel 13129: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 13130: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13131: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13132: &Math::Random::random_set_seed_from_phrase($rndseed);
13133: } else {
13134: &Math::Random::random_set_seed($num1,$num2);
13135: }
1.366 albertel 13136: } else {
13137: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13138: }
1.36 albertel 13139: }
13140:
1.474 albertel 13141: sub latest_receipt_algorithm_id {
1.835 albertel 13142: return 'receipt3';
1.474 albertel 13143: }
13144:
1.480 www 13145: sub recunique {
13146: my $fucourseid=shift;
13147: my $unique;
1.835 albertel 13148: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13149: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13150: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13151: } else {
13152: $unique=$perlvar{'lonReceipt'};
13153: }
13154: return unpack("%32C*",$unique);
13155: }
13156:
13157: sub recprefix {
13158: my $fucourseid=shift;
13159: my $prefix;
1.835 albertel 13160: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13161: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13162: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13163: } else {
13164: $prefix=$perlvar{'lonHostID'};
13165: }
13166: return unpack("%32C*",$prefix);
13167: }
13168:
1.76 www 13169: sub ireceipt {
1.474 albertel 13170: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13171:
13172: my $return =&recprefix($fucourseid).'-';
13173:
13174: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13175: $env{'request.state'} eq 'construct') {
13176: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13177: return $return;
13178: }
13179:
1.76 www 13180: my $cuname=unpack("%32C*",$funame);
13181: my $cudom=unpack("%32C*",$fudom);
13182: my $cucourseid=unpack("%32C*",$fucourseid);
13183: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13184: my $cunique=&recunique($fucourseid);
1.474 albertel 13185: my $cpart=unpack("%32S*",$part);
1.835 albertel 13186: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13187:
1.790 albertel 13188: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13189:
13190: $return.= ($cunique%$cuname+
13191: $cunique%$cudom+
13192: $cusymb%$cuname+
13193: $cusymb%$cudom+
13194: $cucourseid%$cuname+
13195: $cucourseid%$cudom+
13196: $cpart%$cuname+
13197: $cpart%$cudom);
13198: } else {
13199: $return.= ($cunique%$cuname+
13200: $cunique%$cudom+
13201: $cusymb%$cuname+
13202: $cusymb%$cudom+
13203: $cucourseid%$cuname+
13204: $cucourseid%$cudom);
13205: }
13206: return $return;
1.76 www 13207: }
13208:
13209: sub receipt {
1.474 albertel 13210: my ($part)=@_;
1.790 albertel 13211: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13212: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13213: }
1.260 ng 13214:
1.790 albertel 13215: sub whichuser {
13216: my ($passedsymb)=@_;
13217: my ($symb,$courseid,$domain,$name,$publicuser);
13218: if (defined($env{'form.grade_symb'})) {
13219: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13220: my $allowed=&allowed('vgr',$tmp_courseid);
13221: if (!$allowed &&
13222: exists($env{'request.course.sec'}) &&
13223: $env{'request.course.sec'} !~ /^\s*$/) {
13224: $allowed=&allowed('vgr',$tmp_courseid.
13225: '/'.$env{'request.course.sec'});
13226: }
13227: if ($allowed) {
13228: ($symb)=&get_env_multiple('form.grade_symb');
13229: $courseid=$tmp_courseid;
13230: ($domain)=&get_env_multiple('form.grade_domain');
13231: ($name)=&get_env_multiple('form.grade_username');
13232: return ($symb,$courseid,$domain,$name,$publicuser);
13233: }
13234: }
13235: if (!$passedsymb) {
13236: $symb=&symbread();
13237: } else {
13238: $symb=$passedsymb;
13239: }
13240: $courseid=$env{'request.course.id'};
13241: $domain=$env{'user.domain'};
13242: $name=$env{'user.name'};
13243: if ($name eq 'public' && $domain eq 'public') {
13244: if (!defined($env{'form.username'})) {
13245: $env{'form.username'}.=time.rand(10000000);
13246: }
13247: $name.=$env{'form.username'};
13248: }
13249: return ($symb,$courseid,$domain,$name,$publicuser);
13250:
13251: }
13252:
1.36 albertel 13253: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13254: # returns either the contents of the file or
13255: # -1 if the file doesn't exist
1.481 raeburn 13256: #
13257: # if the target is a file that was uploaded via DOCS,
13258: # a check will be made to see if a current copy exists on the local server,
13259: # if it does this will be served, otherwise a copy will be retrieved from
13260: # the home server for the course and stored in /home/httpd/html/userfiles on
13261: # the local server.
1.472 albertel 13262:
1.36 albertel 13263: sub getfile {
1.538 albertel 13264: my ($file) = @_;
1.609 banghart 13265: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13266: &repcopy($file);
13267: return &readfile($file);
13268: }
13269:
13270: sub repcopy_userfile {
13271: my ($file)=@_;
1.1142 raeburn 13272: my $londocroot = $perlvar{'lonDocRoot'};
13273: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13274: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13275: my ($cdom,$cnum,$filename) =
1.811 albertel 13276: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13277: my $uri="/uploaded/$cdom/$cnum/$filename";
13278: if (-e "$file") {
1.828 www 13279: # we already have a local copy, check it out
1.538 albertel 13280: my @fileinfo = stat($file);
1.828 www 13281: my $rtncode;
13282: my $info;
1.538 albertel 13283: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13284: if ($lwpresp ne 'ok') {
1.828 www 13285: # there is no such file anymore, even though we had a local copy
1.482 albertel 13286: if ($rtncode eq '404') {
1.538 albertel 13287: unlink($file);
1.482 albertel 13288: }
13289: return -1;
13290: }
13291: if ($info < $fileinfo[9]) {
1.828 www 13292: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13293: return 'ok';
1.828 www 13294: } else {
13295: # the file is outdated, get rid of it
13296: unlink($file);
1.482 albertel 13297: }
1.828 www 13298: }
13299: # one way or the other, at this point, we don't have the file
13300: # construct the correct path for the file
13301: my @parts = ($cdom,$cnum);
13302: if ($filename =~ m|^(.+)/[^/]+$|) {
13303: push @parts, split(/\//,$1);
13304: }
13305: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13306: foreach my $part (@parts) {
13307: $path .= '/'.$part;
13308: if (!-e $path) {
13309: mkdir($path,0770);
1.482 albertel 13310: }
13311: }
1.828 www 13312: # now the path exists for sure
13313: # get a user agent
13314: my $ua=new LWP::UserAgent;
13315: my $transferfile=$file.'.in.transfer';
13316: # FIXME: this should flock
13317: if (-e $transferfile) { return 'ok'; }
13318: my $request;
13319: $uri=~s/^\///;
1.980 raeburn 13320: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118. .3(raebu 13321:20): my $hostname = &hostname($homeserver);
1.980 raeburn 13322: my $protocol = $protocol{$homeserver};
13323: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118. .3(raebu 13324:20): $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13325: my $response=$ua->request($request,$transferfile);
13326: # did it work?
13327: if ($response->is_error()) {
13328: unlink($transferfile);
13329: &logthis("Userfile repcopy failed for $uri");
13330: return -1;
13331: }
13332: # worked, rename the transfer file
13333: rename($transferfile,$file);
1.607 raeburn 13334: return 'ok';
1.481 raeburn 13335: }
13336:
1.517 albertel 13337: sub tokenwrapper {
13338: my $uri=shift;
1.980 raeburn 13339: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13340: $uri=~s|^/||;
1.620 albertel 13341: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13342: my $token=$1;
1.552 albertel 13343: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13344: if ($udom && $uname && $file) {
13345: $file=~s|(\?\.*)*$||;
1.949 raeburn 13346: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13347: my $homeserver = &homeserver($uname,$udom);
1.1172.2.118. .3(raebu 13348:20): my $hostname = &hostname($homeserver);
1.980 raeburn 13349: my $protocol = $protocol{$homeserver};
13350: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118. .3(raebu 13351:20): return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13352: (($uri=~/\?/)?'&':'?').'token='.$token.
13353: '&tokenissued='.$perlvar{'lonHostID'};
13354: } else {
13355: return '/adm/notfound.html';
13356: }
13357: }
13358:
1.828 www 13359: # call with reqtype HEAD: get last modification time
13360: # call with reqtype GET: get the file contents
13361: # Do not call this with reqtype GET for large files! It loads everything into memory
13362: #
1.481 raeburn 13363: sub getuploaded {
13364: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13365: $uri=~s/^\///;
1.980 raeburn 13366: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118. .3(raebu 13367:20): my $hostname = &hostname($homeserver);
1.980 raeburn 13368: my $protocol = $protocol{$homeserver};
13369: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118. .3(raebu 13370:20): $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13371: my $ua=new LWP::UserAgent;
13372: my $request=new HTTP::Request($reqtype,$uri);
13373: my $response=$ua->request($request);
13374: $$rtncode = $response->code;
1.482 albertel 13375: if (! $response->is_success()) {
13376: return 'failed';
13377: }
13378: if ($reqtype eq 'HEAD') {
1.486 www 13379: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13380: } elsif ($reqtype eq 'GET') {
13381: $$info = $response->content;
1.472 albertel 13382: }
1.482 albertel 13383: return 'ok';
1.36 albertel 13384: }
13385:
1.481 raeburn 13386: sub readfile {
13387: my $file = shift;
13388: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13389: my $fh;
1.1172.2.96 raeburn 13390: open($fh,"<",$file);
1.481 raeburn 13391: my $a='';
1.800 albertel 13392: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13393: return $a;
13394: }
13395:
1.36 albertel 13396: sub filelocation {
1.590 banghart 13397: my ($dir,$file) = @_;
13398: my $location;
13399: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13400:
13401: if ($file =~ m-^/adm/-) {
13402: $file=~s-^/adm/wrapper/-/-;
13403: $file=~s-^/adm/coursedocs/showdoc/-/-;
13404: }
1.882 albertel 13405:
1.1139 www 13406: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13407: $location = $file;
1.609 banghart 13408: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13409: my ($udom,$uname,$filename)=
1.811 albertel 13410: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13411: my $home=&homeserver($uname,$udom);
13412: my $is_me=0;
13413: my @ids=¤t_machine_ids();
13414: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13415: if ($is_me) {
1.1117 foxr 13416: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13417: } else {
13418: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13419: $udom.'/'.$uname.'/'.$filename;
13420: }
1.882 albertel 13421: } elsif ($file =~ m-^/adm/-) {
13422: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13423: } else {
13424: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13425: $file=~s:^/(res|priv)/:/:;
13426: my $space=$1;
1.590 banghart 13427: if ( !( $file =~ m:^/:) ) {
13428: $location = $dir. '/'.$file;
13429: } else {
1.1142 raeburn 13430: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13431: }
1.59 albertel 13432: }
1.590 banghart 13433: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13434: while ($location=~m{/\.\./}) {
13435: if ($location =~ m{/[^/]+/\.\./}) {
13436: $location=~ s{/[^/]+/\.\./}{/}g;
13437: } else {
13438: $location=~ s{/\.\./}{/}g;
13439: }
13440: } #remove dir/..
1.590 banghart 13441: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13442: return $location;
1.46 www 13443: }
1.36 albertel 13444:
1.46 www 13445: sub hreflocation {
13446: my ($dir,$file)=@_;
1.980 raeburn 13447: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13448: $file=filelocation($dir,$file);
1.700 albertel 13449: } elsif ($file=~m-^/adm/-) {
13450: $file=~s-^/adm/wrapper/-/-;
13451: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13452: }
13453: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13454: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13455: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13456: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13457: {/uploaded/$1/$2/}x;
1.46 www 13458: }
1.913 albertel 13459: if ($file=~ m{^/userfiles/}) {
13460: $file =~ s{^/userfiles/}{/uploaded/};
13461: }
1.462 albertel 13462: return $file;
1.465 albertel 13463: }
13464:
1.1139 www 13465:
13466:
13467:
13468:
1.465 albertel 13469: sub current_machine_domains {
1.853 albertel 13470: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13471: }
13472:
13473: sub machine_domains {
13474: my ($hostname) = @_;
1.465 albertel 13475: my @domains;
1.838 albertel 13476: my %hostname = &all_hostnames();
1.465 albertel 13477: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13478: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13479: if ($hostname eq $name) {
1.844 albertel 13480: push(@domains,&host_domain($id));
1.465 albertel 13481: }
13482: }
13483: return @domains;
13484: }
13485:
13486: sub current_machine_ids {
1.853 albertel 13487: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13488: }
13489:
13490: sub machine_ids {
13491: my ($hostname) = @_;
13492: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13493: my @ids;
1.888 albertel 13494: my %name_to_host = &all_names();
1.889 albertel 13495: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13496: return @{ $name_to_host{$hostname} };
13497: }
13498: return;
1.31 www 13499: }
13500:
1.824 raeburn 13501: sub additional_machine_domains {
13502: my @domains;
1.1172.2.96 raeburn 13503: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 13504: while( my $line = <$fh>) {
13505: $line =~ s/\s//g;
13506: push(@domains,$line);
13507: }
13508: return @domains;
13509: }
13510:
13511: sub default_login_domain {
13512: my $domain = $perlvar{'lonDefDomain'};
13513: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13514: foreach my $posdom (¤t_machine_domains(),
13515: &additional_machine_domains()) {
13516: if (lc($posdom) eq lc($testdomain)) {
13517: $domain=$posdom;
13518: last;
13519: }
13520: }
13521: return $domain;
13522: }
13523:
1.1172.2.106 raeburn 13524: sub shared_institution {
1.1172.2.118. .15(raeb 13525:-21): my ($dom,$lonhost) = @_;
13526:-21): if ($lonhost eq '') {
13527:-21): $lonhost = $perlvar{'lonHostID'};
13528:-21): }
1.1172.2.106 raeburn 13529: my $same_intdom;
1.1172.2.118. .15(raeb 13530:-21): my $hostintdom = &internet_dom($lonhost);
1.1172.2.106 raeburn 13531: if ($hostintdom ne '') {
13532: my %iphost = &get_iphost();
13533: my $primary_id = &domain($dom,'primary');
13534: my $primary_ip = &get_host_ip($primary_id);
13535: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13536: foreach my $id (@{$iphost{$primary_ip}}) {
13537: my $intdom = &internet_dom($id);
13538: if ($intdom eq $hostintdom) {
13539: $same_intdom = 1;
13540: last;
13541: }
13542: }
13543: }
13544: }
13545: return $same_intdom;
13546: }
13547:
1.1172.2.118. .3(raebu 13548:20): sub uses_sts {
13549:20): my ($ignore_cache) = @_;
13550:20): my $lonhost = $perlvar{'lonHostID'};
13551:20): my $hostname = &hostname($lonhost);
13552:20): my $sts_on;
13553:20): if ($protocol{$lonhost} eq 'https') {
13554:20): my $cachetime = 12*3600;
13555:20): if (!$ignore_cache) {
13556:20): ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13557:20): if (defined($cached)) {
13558:20): return $sts_on;
13559:20): }
13560:20): }
.4(raebu 13561:20): my $ua=new LWP::UserAgent;
.3(raebu 13562:20): my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13563:20): my $request=new HTTP::Request('HEAD',$url);
.4(raebu 13564:20): my $response=$ua->request($request);
.3(raebu 13565:20): if ($response->is_success) {
13566:20): my $has_sts = $response->header('Strict-Transport-Security');
13567:20): if ($has_sts eq '') {
13568:20): $sts_on = 0;
13569:20): } else {
13570:20): if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13571:20): my $maxage = $1;
13572:20): if ($maxage) {
13573:20): $sts_on = 1;
13574:20): } else {
13575:20): $sts_on = 0;
13576:20): }
13577:20): } else {
13578:20): $sts_on = 0;
13579:20): }
13580:20): }
13581:20): return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13582:20): }
13583:20): }
13584:20): return;
13585:20): }
13586:20):
.14(raeb 13587:-21): sub get_requestor_ip {
13588:-21): my ($r,$nolookup,$noproxy) = @_;
13589:-21): my $from_ip;
13590:-21): if (ref($r)) {
13591:-21): $from_ip = $r->get_remote_host($nolookup);
13592:-21): } else {
13593:-21): $from_ip = $ENV{'REMOTE_ADDR'};
13594:-21): }
13595:-21): return $from_ip;
13596:-21): }
13597:-21):
1.31 www 13598: # ------------------------------------------------------------- Declutters URLs
13599:
13600: sub declutter {
13601: my $thisfn=shift;
1.569 albertel 13602: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13603: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13604: $thisfn=~s{^/home/httpd/html}{};
13605: }
1.31 www 13606: $thisfn=~s/^\///;
1.697 albertel 13607: $thisfn=~s|^adm/wrapper/||;
13608: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13609: $thisfn=~s/^res\///;
1.1172 bisitz 13610: $thisfn=~s/^priv\///;
1.1032 raeburn 13611: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13612: $thisfn=~s/\?.+$//;
13613: }
1.268 www 13614: return $thisfn;
13615: }
13616:
13617: # ------------------------------------------------------------- Clutter up URLs
13618:
13619: sub clutter {
13620: my $thisfn='/'.&declutter(shift);
1.887 albertel 13621: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13622: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13623: $thisfn='/res'.$thisfn;
13624: }
1.1031 raeburn 13625: if ($thisfn !~m|^/adm|) {
13626: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13627: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13628: } else {
13629: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13630: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13631: if ($embstyle eq 'ssi'
13632: || ($embstyle eq 'hdn')
13633: || ($embstyle eq 'rat')
13634: || ($embstyle eq 'prv')
13635: || ($embstyle eq 'ign')) {
13636: #do nothing with these
13637: } elsif (($embstyle eq 'img')
1.695 albertel 13638: || ($embstyle eq 'emb')
13639: || ($embstyle eq 'wrp')) {
13640: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13641: } elsif ($embstyle eq 'unk'
13642: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13643: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13644: } else {
1.718 www 13645: # &logthis("Got a blank emb style");
1.695 albertel 13646: }
1.694 albertel 13647: }
1.1172.2.118. .1(raebu 13648:20): } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13649:20): $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 13650: }
1.31 www 13651: return $thisfn;
1.12 www 13652: }
13653:
1.787 albertel 13654: sub clutter_with_no_wrapper {
13655: my $uri = &clutter(shift);
13656: if ($uri =~ m-^/adm/-) {
13657: $uri =~ s-^/adm/wrapper/-/-;
13658: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13659: }
13660: return $uri;
13661: }
13662:
1.557 albertel 13663: sub freeze_escape {
13664: my ($value)=@_;
13665: if (ref($value)) {
13666: $value=&nfreeze($value);
13667: return '__FROZEN__'.&escape($value);
13668: }
13669: return &escape($value);
13670: }
13671:
1.11 www 13672:
1.557 albertel 13673: sub thaw_unescape {
13674: my ($value)=@_;
13675: if ($value =~ /^__FROZEN__/) {
13676: substr($value,0,10,undef);
13677: $value=&unescape($value);
13678: return &thaw($value);
13679: }
13680: return &unescape($value);
13681: }
13682:
1.436 albertel 13683: sub correct_line_ends {
13684: my ($result)=@_;
13685: $$result =~s/\r\n/\n/mg;
13686: $$result =~s/\r/\n/mg;
1.415 albertel 13687: }
1.1 albertel 13688: # ================================================================ Main Program
13689:
1.184 www 13690: sub goodbye {
1.204 albertel 13691: &logthis("Starting Shut down");
1.443 albertel 13692: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13693: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13694: #converted
1.599 albertel 13695: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13696: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13697: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13698: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13699: #1.1 only
1.870 albertel 13700: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13701: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13702: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13703: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13704: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13705: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13706: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13707: &flushcourselogs();
13708: &logthis("Shutting down");
13709: }
13710:
1.852 albertel 13711: sub get_dns {
1.1172.2.17 raeburn 13712: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13713: if (!$ignore_cache) {
13714: my ($content,$cached)=
13715: &Apache::lonnet::is_cached_new('dns',$url);
13716: if ($cached) {
1.1172.2.17 raeburn 13717: &$func($content,$hashref);
1.869 albertel 13718: return;
13719: }
13720: }
13721:
13722: my %alldns;
1.1172.2.96 raeburn 13723: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13724: foreach my $dns (<$config>) {
13725: next if ($dns !~ /^\^(\S*)/x);
13726: my $line = $1;
13727: my ($host,$protocol) = split(/:/,$line);
13728: if ($protocol ne 'https') {
13729: $protocol = 'http';
13730: }
13731: $alldns{$host} = $protocol;
1.979 raeburn 13732: }
1.1172.2.96 raeburn 13733: close($config);
1.869 albertel 13734: }
13735: while (%alldns) {
1.1172.2.52 raeburn 13736: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 13737: my $ua=new LWP::UserAgent;
1.1134 raeburn 13738: $ua->timeout(30);
1.979 raeburn 13739: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 13740: my $response=$ua->request($request);
1.979 raeburn 13741: delete($alldns{$dns});
1.852 albertel 13742: next if ($response->is_error());
13743: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 13744: unless ($nocache) {
1.1172.2.23 raeburn 13745: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 13746: }
13747: &$func(\@content,$hashref);
1.869 albertel 13748: return;
1.852 albertel 13749: }
1.871 albertel 13750: my $which = (split('/',$url))[3];
13751: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 13752: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13753: my @content = <$config>;
13754: &$func(\@content,$hashref);
13755: }
1.1172.2.17 raeburn 13756: return;
13757: }
13758:
13759: # ------------------------------------------------------Get DNS checksums file
13760: sub parse_dns_checksums_tab {
13761: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 13762: my $lonhost = $perlvar{'lonHostID'};
13763: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 13764: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 13765: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13766: my $webconfdir = '/etc/httpd/conf';
13767: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13768: $webconfdir = '/etc/apache2';
13769: } elsif ($distro =~ /^sles(\d+)$/) {
13770: if ($1 >= 10) {
13771: $webconfdir = '/etc/apache2';
13772: }
13773: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13774: if ($1 >= 10.0) {
13775: $webconfdir = '/etc/apache2';
13776: }
13777: }
1.1172.2.17 raeburn 13778: my ($release,$timestamp) = split(/\-/,$loncaparev);
13779: my (%chksum,%revnum);
13780: if (ref($lines) eq 'ARRAY') {
13781: chomp(@{$lines});
1.1172.2.34 raeburn 13782: my $version = shift(@{$lines});
13783: if ($version eq $release) {
1.1172.2.17 raeburn 13784: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 13785: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 13786: if ($file =~ m{^/etc/httpd/conf}) {
13787: if ($webconfdir eq '/etc/apache2') {
13788: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13789: }
13790: }
1.1172.2.34 raeburn 13791: $chksum{$file} = $shasum;
13792: $revnum{$file} = $version;
1.1172.2.17 raeburn 13793: }
13794: if (ref($hashref) eq 'HASH') {
13795: %{$hashref} = (
13796: sums => \%chksum,
13797: versions => \%revnum,
13798: );
13799: }
13800: }
13801: }
1.869 albertel 13802: return;
1.852 albertel 13803: }
1.1172.2.17 raeburn 13804:
13805: sub fetch_dns_checksums {
13806: my %checksums;
1.1172.2.34 raeburn 13807: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 13808: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 13809: my ($release,$timestamp) = split(/\-/,$loncaparev);
13810: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 13811: \%checksums);
13812: return \%checksums;
13813: }
13814:
1.327 albertel 13815: # ------------------------------------------------------------ Read domain file
13816: {
1.852 albertel 13817: my $loaded;
1.846 albertel 13818: my %domain;
13819:
1.852 albertel 13820: sub parse_domain_tab {
13821: my ($lines) = @_;
13822: foreach my $line (@$lines) {
13823: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13824:
1.846 albertel 13825: chomp($line);
1.852 albertel 13826: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13827: my %this_domain;
13828: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13829: 'lang_def', 'city', 'longi', 'lati',
13830: 'primary') {
13831: $this_domain{$field} = shift(@elements);
13832: }
13833: $domain{$name} = \%this_domain;
1.852 albertel 13834: }
13835: }
1.864 albertel 13836:
13837: sub reset_domain_info {
13838: undef($loaded);
13839: undef(%domain);
13840: }
13841:
1.852 albertel 13842: sub load_domain_tab {
1.1172.2.70 raeburn 13843: my ($ignore_cache,$nocache) = @_;
13844: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13845: my $fh;
1.1172.2.96 raeburn 13846: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 13847: my @lines = <$fh>;
13848: &parse_domain_tab(\@lines);
1.448 albertel 13849: }
1.852 albertel 13850: close($fh);
13851: $loaded = 1;
1.327 albertel 13852: }
1.846 albertel 13853:
13854: sub domain {
1.852 albertel 13855: &load_domain_tab() if (!$loaded);
13856:
1.846 albertel 13857: my ($name,$what) = @_;
13858: return if ( !exists($domain{$name}) );
13859:
13860: if (!$what) {
13861: return $domain{$name}{'description'};
13862: }
13863: return $domain{$name}{$what};
13864: }
1.974 raeburn 13865:
13866: sub domain_info {
13867: &load_domain_tab() if (!$loaded);
13868: return %domain;
13869: }
13870:
1.327 albertel 13871: }
13872:
13873:
1.1 albertel 13874: # ------------------------------------------------------------- Read hosts file
13875: {
1.838 albertel 13876: my %hostname;
1.844 albertel 13877: my %hostdom;
1.845 albertel 13878: my %libserv;
1.852 albertel 13879: my $loaded;
1.888 albertel 13880: my %name_to_host;
1.1074 raeburn 13881: my %internetdom;
1.1107 raeburn 13882: my %LC_dns_serv;
1.852 albertel 13883:
13884: sub parse_hosts_tab {
13885: my ($file) = @_;
13886: foreach my $configline (@$file) {
13887: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13888: chomp($configline);
13889: if ($configline =~ /^\^/) {
13890: if ($configline =~ /^\^([\w.\-]+)/) {
13891: $LC_dns_serv{$1} = 1;
13892: }
13893: next;
13894: }
1.1074 raeburn 13895: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13896: $name=~s/\s//g;
13897: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 13898: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13899: my $curr = $hostname{$id};
13900: my $skip;
13901: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13902: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13903: $skip = 1;
13904: } else {
13905: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13906: }
13907: }
13908: unless ($skip) {
13909: push(@{$name_to_host{$name}},$id);
13910: }
13911: } else {
13912: push(@{$name_to_host{$name}},$id);
13913: }
1.852 albertel 13914: $hostname{$id}=$name;
13915: $hostdom{$id}=$domain;
13916: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13917: if (defined($protocol)) {
13918: if ($protocol eq 'https') {
13919: $protocol{$id} = $protocol;
13920: } else {
13921: $protocol{$id} = 'http';
13922: }
1.968 raeburn 13923: } else {
1.969 raeburn 13924: $protocol{$id} = 'http';
1.968 raeburn 13925: }
1.1074 raeburn 13926: if (defined($intdom)) {
13927: $internetdom{$id} = $intdom;
13928: }
1.852 albertel 13929: }
13930: }
13931: }
1.864 albertel 13932:
13933: sub reset_hosts_info {
1.897 albertel 13934: &purge_remembered();
1.864 albertel 13935: &reset_domain_info();
13936: &reset_hosts_ip_info();
1.892 albertel 13937: undef(%name_to_host);
1.864 albertel 13938: undef(%hostname);
13939: undef(%hostdom);
13940: undef(%libserv);
13941: undef($loaded);
13942: }
1.1 albertel 13943:
1.852 albertel 13944: sub load_hosts_tab {
1.1172.2.70 raeburn 13945: my ($ignore_cache,$nocache) = @_;
13946: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 13947: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 13948: my @config = <$config>;
13949: &parse_hosts_tab(\@config);
13950: close($config);
13951: $loaded=1;
1.1 albertel 13952: }
1.852 albertel 13953:
1.838 albertel 13954: sub hostname {
1.852 albertel 13955: &load_hosts_tab() if (!$loaded);
13956:
1.838 albertel 13957: my ($lonid) = @_;
13958: return $hostname{$lonid};
13959: }
1.845 albertel 13960:
1.838 albertel 13961: sub all_hostnames {
1.852 albertel 13962: &load_hosts_tab() if (!$loaded);
13963:
1.838 albertel 13964: return %hostname;
13965: }
1.845 albertel 13966:
1.888 albertel 13967: sub all_names {
1.1172.2.70 raeburn 13968: my ($ignore_cache,$nocache) = @_;
13969: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13970:
13971: return %name_to_host;
13972: }
13973:
1.974 raeburn 13974: sub all_host_domain {
13975: &load_hosts_tab() if (!$loaded);
13976: return %hostdom;
13977: }
13978:
1.845 albertel 13979: sub is_library {
1.852 albertel 13980: &load_hosts_tab() if (!$loaded);
13981:
1.845 albertel 13982: return exists($libserv{$_[0]});
13983: }
13984:
13985: sub all_library {
1.852 albertel 13986: &load_hosts_tab() if (!$loaded);
13987:
1.845 albertel 13988: return %libserv;
13989: }
13990:
1.1062 droeschl 13991: sub unique_library {
13992: #2x reverse removes all hostnames that appear more than once
13993: my %unique = reverse &all_library();
13994: return reverse %unique;
13995: }
13996:
1.841 albertel 13997: sub get_servers {
1.852 albertel 13998: &load_hosts_tab() if (!$loaded);
13999:
1.841 albertel 14000: my ($domain,$type) = @_;
14001: my %possible_hosts = ($type eq 'library') ? %libserv
14002: : %hostname;
14003: my %result;
1.842 albertel 14004: if (ref($domain) eq 'ARRAY') {
14005: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14006: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14007: $result{$host} = $hostname;
14008: }
14009: }
14010: } else {
14011: while ( my ($host,$hostname) = each(%possible_hosts)) {
14012: if ($hostdom{$host} eq $domain) {
14013: $result{$host} = $hostname;
14014: }
1.841 albertel 14015: }
14016: }
14017: return %result;
14018: }
1.845 albertel 14019:
1.1062 droeschl 14020: sub get_unique_servers {
14021: my %unique = reverse &get_servers(@_);
14022: return reverse %unique;
14023: }
14024:
1.844 albertel 14025: sub host_domain {
1.852 albertel 14026: &load_hosts_tab() if (!$loaded);
14027:
1.844 albertel 14028: my ($lonid) = @_;
14029: return $hostdom{$lonid};
14030: }
14031:
1.841 albertel 14032: sub all_domains {
1.852 albertel 14033: &load_hosts_tab() if (!$loaded);
14034:
1.841 albertel 14035: my %seen;
14036: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14037: return @uniq;
14038: }
1.1074 raeburn 14039:
14040: sub internet_dom {
14041: &load_hosts_tab() if (!$loaded);
14042:
14043: my ($lonid) = @_;
14044: return $internetdom{$lonid};
14045: }
1.1107 raeburn 14046:
14047: sub is_LC_dns {
14048: &load_hosts_tab() if (!$loaded);
14049:
14050: my ($hostname) = @_;
14051: return exists($LC_dns_serv{$hostname});
14052: }
14053:
1.1 albertel 14054: }
14055:
1.847 albertel 14056: {
14057: my %iphost;
1.856 albertel 14058: my %name_to_ip;
14059: my %lonid_to_ip;
1.869 albertel 14060:
1.847 albertel 14061: sub get_hosts_from_ip {
14062: my ($ip) = @_;
14063: my %iphosts = &get_iphost();
14064: if (ref($iphosts{$ip})) {
14065: return @{$iphosts{$ip}};
14066: }
14067: return;
1.839 albertel 14068: }
1.864 albertel 14069:
14070: sub reset_hosts_ip_info {
14071: undef(%iphost);
14072: undef(%name_to_ip);
14073: undef(%lonid_to_ip);
14074: }
1.856 albertel 14075:
14076: sub get_host_ip {
14077: my ($lonid) = @_;
14078: if (exists($lonid_to_ip{$lonid})) {
14079: return $lonid_to_ip{$lonid};
14080: }
14081: my $name=&hostname($lonid);
14082: my $ip = gethostbyname($name);
14083: return if (!$ip || length($ip) ne 4);
14084: $ip=inet_ntoa($ip);
14085: $name_to_ip{$name} = $ip;
14086: $lonid_to_ip{$lonid} = $ip;
14087: return $ip;
14088: }
1.847 albertel 14089:
14090: sub get_iphost {
1.1172.2.70 raeburn 14091: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14092:
1.869 albertel 14093: if (!$ignore_cache) {
14094: if (%iphost) {
14095: return %iphost;
14096: }
14097: my ($ip_info,$cached)=
14098: &Apache::lonnet::is_cached_new('iphost','iphost');
14099: if ($cached) {
14100: %iphost = %{$ip_info->[0]};
14101: %name_to_ip = %{$ip_info->[1]};
14102: %lonid_to_ip = %{$ip_info->[2]};
14103: return %iphost;
14104: }
14105: }
1.894 albertel 14106:
14107: # get yesterday's info for fallback
14108: my %old_name_to_ip;
14109: my ($ip_info,$cached)=
14110: &Apache::lonnet::is_cached_new('iphost','iphost');
14111: if ($cached) {
14112: %old_name_to_ip = %{$ip_info->[1]};
14113: }
14114:
1.1172.2.70 raeburn 14115: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14116: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14117: my $ip;
14118: if (!exists($name_to_ip{$name})) {
14119: $ip = gethostbyname($name);
14120: if (!$ip || length($ip) ne 4) {
1.894 albertel 14121: if (defined($old_name_to_ip{$name})) {
14122: $ip = $old_name_to_ip{$name};
14123: &logthis("Can't find $name defaulting to old $ip");
14124: } else {
14125: &logthis("Name $name no IP found");
14126: next;
14127: }
14128: } else {
14129: $ip=inet_ntoa($ip);
1.847 albertel 14130: }
14131: $name_to_ip{$name} = $ip;
14132: } else {
14133: $ip = $name_to_ip{$name};
1.653 albertel 14134: }
1.888 albertel 14135: foreach my $id (@{ $name_to_host{$name} }) {
14136: $lonid_to_ip{$id} = $ip;
14137: }
14138: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14139: }
1.1172.2.70 raeburn 14140: unless ($nocache) {
14141: &do_cache_new('iphost','iphost',
14142: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14143: 48*60*60);
14144: }
1.869 albertel 14145:
1.847 albertel 14146: return %iphost;
1.598 albertel 14147: }
14148:
1.992 raeburn 14149: #
14150: # Given a DNS returns the loncapa host name for that DNS
14151: #
14152: sub host_from_dns {
14153: my ($dns) = @_;
14154: my @hosts;
14155: my $ip;
14156:
1.993 raeburn 14157: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14158: $ip = $name_to_ip{$dns};
14159: }
14160: if (!$ip) {
14161: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14162: if (length($ip) == 4) {
14163: $ip = &IO::Socket::inet_ntoa($ip);
14164: }
14165: }
14166: if ($ip) {
14167: @hosts = get_hosts_from_ip($ip);
14168: return $hosts[0];
14169: }
14170: return undef;
1.986 foxr 14171: }
1.992 raeburn 14172:
1.1074 raeburn 14173: sub get_internet_names {
14174: my ($lonid) = @_;
14175: return if ($lonid eq '');
14176: my ($idnref,$cached)=
14177: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14178: if ($cached) {
14179: return $idnref;
14180: }
14181: my $ip = &get_host_ip($lonid);
14182: my @hosts = &get_hosts_from_ip($ip);
14183: my %iphost = &get_iphost();
14184: my (@idns,%seen);
14185: foreach my $id (@hosts) {
14186: my $dom = &host_domain($id);
14187: my $prim_id = &domain($dom,'primary');
14188: my $prim_ip = &get_host_ip($prim_id);
14189: next if ($seen{$prim_ip});
14190: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14191: foreach my $id (@{$iphost{$prim_ip}}) {
14192: my $intdom = &internet_dom($id);
14193: unless (grep(/^\Q$intdom\E$/,@idns)) {
14194: push(@idns,$intdom);
14195: }
14196: }
14197: }
14198: $seen{$prim_ip} = 1;
14199: }
1.1172.2.23 raeburn 14200: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14201: }
14202:
1.986 foxr 14203: }
14204:
1.1079 raeburn 14205: sub all_loncaparevs {
1.1172.2.39 raeburn 14206: 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 2.11);
1.1079 raeburn 14207: }
14208:
1.1172.2.27 raeburn 14209: # ------------------------------------------------------- Read loncaparev table
14210: {
14211: sub load_loncaparevs {
14212: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 14213: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 14214: while (my $configline=<$config>) {
14215: chomp($configline);
14216: my ($hostid,$loncaparev)=split(/:/,$configline);
14217: $loncaparevs{$hostid}=$loncaparev;
14218: }
14219: close($config);
14220: }
14221: }
14222: }
14223: }
14224:
14225: # ----------------------------------------------------- Read serverhostID table
14226: {
14227: sub load_serverhomeIDs {
14228: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 14229: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 14230: while (my $configline=<$config>) {
14231: chomp($configline);
14232: my ($name,$id)=split(/:/,$configline);
14233: $serverhomeIDs{$name}=$id;
14234: }
14235: close($config);
14236: }
14237: }
14238: }
14239: }
14240:
14241:
1.862 albertel 14242: BEGIN {
14243:
14244: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14245: unless ($readit) {
14246: {
14247: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14248: %perlvar = (%perlvar,%{$configvars});
14249: }
14250:
14251:
1.1 albertel 14252: # ------------------------------------------------------ Read spare server file
14253: {
1.1172.2.96 raeburn 14254: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14255:
14256: while (my $configline=<$config>) {
14257: chomp($configline);
1.284 matthew 14258: if ($configline) {
1.784 albertel 14259: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14260: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14261: push(@{ $spareid{$type} }, $host);
1.1 albertel 14262: }
14263: }
1.448 albertel 14264: close($config);
1.1 albertel 14265: }
1.11 www 14266: # ------------------------------------------------------------ Read permissions
14267: {
1.1172.2.96 raeburn 14268: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14269:
14270: while (my $configline=<$config>) {
1.448 albertel 14271: chomp($configline);
14272: if ($configline) {
14273: my ($role,$perm)=split(/ /,$configline);
14274: if ($perm ne '') { $pr{$role}=$perm; }
14275: }
1.11 www 14276: }
1.448 albertel 14277: close($config);
1.11 www 14278: }
14279:
14280: # -------------------------------------------- Read plain texts for permissions
14281: {
1.1172.2.96 raeburn 14282: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14283:
14284: while (my $configline=<$config>) {
1.448 albertel 14285: chomp($configline);
14286: if ($configline) {
1.742 raeburn 14287: my ($short,@plain)=split(/:/,$configline);
14288: %{$prp{$short}} = ();
14289: if (@plain > 0) {
14290: $prp{$short}{'std'} = $plain[0];
14291: for (my $i=1; $i<@plain; $i++) {
14292: $prp{$short}{'alt'.$i} = $plain[$i];
14293: }
14294: }
1.448 albertel 14295: }
1.135 www 14296: }
1.448 albertel 14297: close($config);
1.135 www 14298: }
14299:
14300: # ---------------------------------------------------------- Read package table
14301: {
1.1172.2.96 raeburn 14302: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14303:
14304: while (my $configline=<$config>) {
1.483 albertel 14305: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14306: chomp($configline);
14307: my ($short,$plain)=split(/:/,$configline);
14308: my ($pack,$name)=split(/\&/,$short);
14309: if ($plain ne '') {
14310: $packagetab{$pack.'&'.$name.'&name'}=$name;
14311: $packagetab{$short}=$plain;
14312: }
1.11 www 14313: }
1.448 albertel 14314: close($config);
1.329 matthew 14315: }
14316:
1.1172.2.27 raeburn 14317: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14318:
1.1172.2.27 raeburn 14319: &load_loncaparevs();
14320:
14321: # ------------------------------------------------------- Read serverhostID table
14322:
14323: &load_serverhomeIDs();
1.1074 raeburn 14324:
1.1172.2.27 raeburn 14325: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14326: {
14327: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14328: if (-e $file) {
14329: my $parser = HTML::LCParser->new($file);
14330: while (my $token = $parser->get_token()) {
14331: if ($token->[0] eq 'S') {
14332: my $item = $token->[1];
14333: my $name = $token->[2]{'name'};
14334: my $value = $token->[2]{'value'};
14335: if ($item ne '' && $name ne '' && $value ne '') {
14336: my $release = $parser->get_text();
14337: $release =~ s/(^\s*|\s*$ )//gx;
14338: $needsrelease{$item.':'.$name.':'.$value} = $release;
14339: }
14340: }
14341: }
14342: }
1.1073 raeburn 14343: }
14344:
1.1138 raeburn 14345: # ---------------------------------------------------------- Read managers table
14346: {
14347: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14348: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14349: while (my $configline=<$config>) {
14350: chomp($configline);
14351: next if ($configline =~ /^\#/);
14352: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14353: $managerstab{$configline} = 1;
14354: }
14355: }
14356: close($config);
14357: }
14358: }
14359: }
14360:
1.329 matthew 14361: # ------------- set up temporary directory
14362: {
1.1117 foxr 14363: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14364:
1.11 www 14365: }
14366:
1.1172.2.104 raeburn 14367: # ------------- set default texengine (domain default overrides this)
14368: {
14369: $deftex = LONCAPA::texengine();
14370: }
14371:
1.1172.2.114 raeburn 14372: # ------------- set default minimum length for passwords for internal auth users
14373: {
14374: $passwdmin = LONCAPA::passwd_min();
14375: }
14376:
1.794 albertel 14377: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14378: 'compress_threshold'=> 20_000,
14379: });
1.185 www 14380:
1.281 www 14381: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14382: $dumpcount=0;
1.958 www 14383: $locknum=0;
1.22 www 14384:
1.163 harris41 14385: &logtouch();
1.672 albertel 14386: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14387: $readit=1;
1.564 albertel 14388: {
14389: use integer;
14390: my $test=(2**32)+1;
1.568 albertel 14391: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14392: &logthis(" Detected 64bit platform ($_64bit)");
14393: }
1.195 www 14394: }
1.1 albertel 14395: }
1.179 www 14396:
1.1 albertel 14397: 1;
1.191 harris41 14398: __END__
14399:
1.243 albertel 14400: =pod
14401:
1.191 harris41 14402: =head1 NAME
14403:
1.243 albertel 14404: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14405:
14406: =head1 SYNOPSIS
14407:
1.243 albertel 14408: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14409:
14410: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14411:
1.243 albertel 14412: Common parameters:
14413:
14414: =over 4
14415:
14416: =item *
14417:
14418: $uname : an internal username (if $cname expecting a course Id specifically)
14419:
14420: =item *
14421:
14422: $udom : a domain (if $cdom expecting a course's domain specifically)
14423:
14424: =item *
14425:
14426: $symb : a resource instance identifier
14427:
14428: =item *
14429:
14430: $namespace : the name of a .db file that contains the data needed or
14431: being set.
14432:
14433: =back
14434:
1.394 bowersj2 14435: =head1 OVERVIEW
1.191 harris41 14436:
1.394 bowersj2 14437: lonnet provides subroutines which interact with the
14438: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14439: about classes, users, and resources.
1.243 albertel 14440:
14441: For many of these objects you can also use this to store data about
14442: them or modify them in various ways.
1.191 harris41 14443:
1.394 bowersj2 14444: =head2 Symbs
1.191 harris41 14445:
1.394 bowersj2 14446: To identify a specific instance of a resource, LON-CAPA uses symbols
14447: or "symbs"X<symb>. These identifiers are built from the URL of the
14448: map, the resource number of the resource in the map, and the URL of
14449: the resource itself. The latter is somewhat redundant, but might help
14450: if maps change.
14451:
14452: An example is
14453:
14454: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14455:
14456: The respective map entry is
14457:
14458: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14459: title="Problem 2">
14460: </resource>
14461:
14462: Symbs are used by the random number generator, as well as to store and
14463: restore data specific to a certain instance of for example a problem.
14464:
14465: =head2 Storing And Retrieving Data
14466:
14467: X<store()>X<cstore()>X<restore()>Three of the most important functions
14468: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14469: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14470: is is the non-critical message twin of cstore. These functions are for
14471: handlers to store a perl hash to a user's permanent data space in an
14472: easy manner, and to retrieve it again on another call. It is expected
14473: that a handler would use this once at the beginning to retrieve data,
14474: and then again once at the end to send only the new data back.
14475:
14476: The data is stored in the user's data directory on the user's
14477: homeserver under the ID of the course.
14478:
14479: The hash that is returned by restore will have all of the previous
14480: value for all of the elements of the hash.
14481:
14482: Example:
14483:
14484: #creating a hash
14485: my %hash;
14486: $hash{'foo'}='bar';
14487:
14488: #storing it
14489: &Apache::lonnet::cstore(\%hash);
14490:
14491: #changing a value
14492: $hash{'foo'}='notbar';
14493:
14494: #adding a new value
14495: $hash{'bar'}='foo';
14496: &Apache::lonnet::cstore(\%hash);
14497:
14498: #retrieving the hash
14499: my %history=&Apache::lonnet::restore();
14500:
14501: #print the hash
14502: foreach my $key (sort(keys(%history))) {
14503: print("\%history{$key} = $history{$key}");
14504: }
14505:
14506: Will print out:
1.191 harris41 14507:
1.394 bowersj2 14508: %history{1:foo} = bar
14509: %history{1:keys} = foo:timestamp
14510: %history{1:timestamp} = 990455579
14511: %history{2:bar} = foo
14512: %history{2:foo} = notbar
14513: %history{2:keys} = foo:bar:timestamp
14514: %history{2:timestamp} = 990455580
14515: %history{bar} = foo
14516: %history{foo} = notbar
14517: %history{timestamp} = 990455580
14518: %history{version} = 2
14519:
14520: Note that the special hash entries C<keys>, C<version> and
14521: C<timestamp> were added to the hash. C<version> will be equal to the
14522: total number of versions of the data that have been stored. The
14523: C<timestamp> attribute will be the UNIX time the hash was
14524: stored. C<keys> is available in every historical section to list which
14525: keys were added or changed at a specific historical revision of a
14526: hash.
14527:
14528: B<Warning>: do not store the hash that restore returns directly. This
14529: will cause a mess since it will restore the historical keys as if the
14530: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14531:
1.394 bowersj2 14532: Calling convention:
1.191 harris41 14533:
1.1172.2.27 raeburn 14534: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14535: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14536:
1.394 bowersj2 14537: For more detailed information, see lonnet specific documentation.
1.191 harris41 14538:
1.394 bowersj2 14539: =head1 RETURN MESSAGES
1.191 harris41 14540:
1.394 bowersj2 14541: =over 4
1.191 harris41 14542:
1.394 bowersj2 14543: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14544:
1.394 bowersj2 14545: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14546: when the connection is brought back up
1.191 harris41 14547:
1.394 bowersj2 14548: =item * B<con_failed>: unable to contact remote host and unable to save message
14549: for later delivery
1.191 harris41 14550:
1.967 bisitz 14551: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14552:
1.394 bowersj2 14553: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14554: that was requested
1.191 harris41 14555:
1.243 albertel 14556: =back
1.191 harris41 14557:
1.243 albertel 14558: =head1 PUBLIC SUBROUTINES
1.191 harris41 14559:
1.243 albertel 14560: =head2 Session Environment Functions
1.191 harris41 14561:
1.243 albertel 14562: =over 4
1.191 harris41 14563:
1.394 bowersj2 14564: =item *
14565: X<appenv()>
1.949 raeburn 14566: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14567: the user envirnoment file, and will be restored for each access this
1.620 albertel 14568: user makes during this session, also modifies the %env for the current
1.949 raeburn 14569: process. Optional rolesarrayref - if defined contains a reference to an array
14570: of roles which are exempt from the restriction on modifying user.role entries
14571: in the user's environment.db and in %env.
1.191 harris41 14572:
14573: =item *
1.394 bowersj2 14574: X<delenv()>
1.987 raeburn 14575: B<delenv($delthis,$regexp)>: removes all items from the session
14576: environment file that begin with $delthis. If the
14577: optional second arg - $regexp - is true, $delthis is treated as a
14578: regular expression, otherwise \Q$delthis\E is used.
14579: The values are also deleted from the current processes %env.
1.191 harris41 14580:
1.795 albertel 14581: =item * get_env_multiple($name)
14582:
14583: gets $name from the %env hash, it seemlessly handles the cases where multiple
14584: values may be defined and end up as an array ref.
14585:
14586: returns an array of values
14587:
1.243 albertel 14588: =back
14589:
14590: =head2 User Information
1.191 harris41 14591:
1.243 albertel 14592: =over 4
1.191 harris41 14593:
14594: =item *
1.394 bowersj2 14595: X<queryauthenticate()>
14596: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14597: authentication scheme
14598:
14599: =item *
1.394 bowersj2 14600: X<authenticate()>
1.1073 raeburn 14601: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14602: authenticate user from domain's lib servers (first use the current
14603: one). C<$upass> should be the users password.
1.1073 raeburn 14604: $checkdefauth is optional (value is 1 if a check should be made to
14605: authenticate user using default authentication method, and allow
14606: account creation if username does not have account in the domain).
14607: $clientcancheckhost is optional (value is 1 if checking whether the
14608: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14609:
14610: =item *
1.394 bowersj2 14611: X<homeserver()>
14612: B<homeserver($uname,$udom)>: find the server which has
14613: the user's directory and files (there must be only one), this caches
14614: the answer, and also caches if there is a borken connection.
1.191 harris41 14615:
14616: =item *
1.394 bowersj2 14617: X<idget()>
14618: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14619: (IDs are a unique resource in a domain, there must be only 1 ID per
14620: username, and only 1 username per ID in a specific domain) (returns
14621: hash: id=>name,id=>name)
1.191 harris41 14622:
14623: =item *
1.394 bowersj2 14624: X<idrget()>
14625: B<idrget($udom,@unames)>: find the IDs behind a list of
14626: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14627:
14628: =item *
1.394 bowersj2 14629: X<idput()>
14630: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14631:
14632: =item *
1.394 bowersj2 14633: X<rolesinit()>
1.1169 droeschl 14634: B<rolesinit($udom,$username)>: get user privileges.
14635: returns user role, first access and timer interval hashes
1.243 albertel 14636:
14637: =item *
1.1171 droeschl 14638: X<privileged()>
14639: B<privileged($username,$domain)>: returns a true if user has a
14640: privileged and active role (i.e. su or dc), false otherwise.
14641:
14642: =item *
1.551 albertel 14643: X<getsection()>
14644: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14645: course $cname, return section name/number or '' for "not in course"
14646: and '-1' for "no section"
14647:
14648: =item *
1.394 bowersj2 14649: X<userenvironment()>
14650: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14651: passed in @what from the requested user's environment, returns a hash
14652:
1.858 raeburn 14653: =item *
14654: X<userlog_query()>
1.859 albertel 14655: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14656: activity.log file. %filters defines filters applied when parsing the
14657: log file. These can be start or end timestamps, or the type of action
14658: - log to look for Login or Logout events, check for Checkin or
14659: Checkout, role for role selection. The response is in the form
14660: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14661: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14662:
1.243 albertel 14663: =back
14664:
14665: =head2 User Roles
14666:
14667: =over 4
14668:
14669: =item *
14670:
1.1172.2.65 raeburn 14671: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14672: returns codes for allowed actions.
14673:
14674: The first argument is required, all others are optional.
14675:
14676: $priv is the privilege being checked.
14677: $uri contains additional information about what is being checked for access (e.g.,
14678: URL, course ID etc.).
14679: $symb is the unique resource instance identifier in a course; if needed,
14680: but not provided, it will be retrieved via a call to &symbread().
14681: $role is the role for which a priv is being checked (only used if priv is evb).
14682: $clientip is the user's IP address (only used when checking for access to portfolio
14683: files).
14684: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14685: prevents recursive calls to &allowed.
14686:
1.243 albertel 14687: F: full access
14688: U,I,K: authentication modes (cxx only)
14689: '': forbidden
14690: 1: user needs to choose course
14691: 2: browse allowed
1.766 albertel 14692: A: passphrase authentication needed
1.1172.2.65 raeburn 14693: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14694:
14695: =item *
14696:
1.1172.2.13 raeburn 14697: constructaccess($url,$setpriv) : check for access to construction space URL
14698:
14699: See if the owner domain and name in the URL match those in the
14700: expected environment. If so, return three element list
14701: ($ownername,$ownerdomain,$ownerhome).
14702:
14703: Otherwise return the null string.
14704:
14705: If second argument 'setpriv' is true, it assigns the privileges,
14706: and returns the same three element list, unless the owner has
14707: blocked "ad hoc" Domain Coordinator access to the Author Space,
14708: in which case the null string is returned.
14709:
14710: =item *
14711:
1.1172.2.84 raeburn 14712: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14713: define a custom role rolename set privileges in format of lonTabs/roles.tab
14714: for system, domain, and course level. $uname and $udom are optional (current
14715: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14716:
14717: =item *
14718:
1.988 raeburn 14719: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14720: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14721: $type is Course (default) or Community.
1.988 raeburn 14722: If $forcedefault evaluates to true, text returned will be default
14723: text for $type. Otherwise, if this is a course, the text returned
14724: will be a custom name for the role (if defined in the course's
14725: environment). If no custom name is defined the default is returned.
14726:
1.832 raeburn 14727: =item *
14728:
1.1172.2.23 raeburn 14729: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14730: All arguments are optional. Returns a hash of a roles, either for
14731: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14732: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14733: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14734: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14735: For each key, value is set to colon-separated start and end times for
14736: the role. If no username and domain are specified, will default to
1.934 raeburn 14737: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14738: of role statuses (active, future or previous), roles
14739: (e.g., cc,in, st etc.) and domains of the roles which can be used
14740: to restrict the list of roles reported. If no array ref is
14741: provided for types, will default to return only active roles.
1.834 albertel 14742:
1.1172.2.13 raeburn 14743: =item *
14744:
14745: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14746: user: $uname:$udom has a role in the course: $cdom_$cnum.
14747:
14748: Additional optional arguments are: $type (if role checking is to be restricted
14749: to certain user status types -- previous (expired roles), active (currently
14750: available roles) or future (roles available in the future), and
14751: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 14752: have active Domain Coordinator role in course's domain or in additional
14753: domains (specified in 'Domains to check for privileged users' in course
14754: environment -- set via: Course Settings -> Classlists and staff listing).
14755:
14756: =item *
14757:
14758: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14759: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14760: $possdomains and $possroles are optional array refs -- to domains to check and
14761: roles to check. If $possdomains is not specified, a dump will be done of the
14762: users' roles.db to check for a dc or su role in any domain. This can be
14763: time consuming if &privileged is called repeatedly (e.g., when displaying a
14764: classlist), so in such cases, supplying a $possdomains array is preferred, as
14765: this then allows &privileged_by_domain() to be used, which caches the identity
14766: of privileged users, eliminating the need for repeated calls to &dump().
14767:
14768: =item *
14769:
14770: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14771: where the outer hash keys are domains specified in the $possdomains array ref,
14772: next inner hash keys are privileged roles specified in the $roles array ref,
14773: and the innermost hash contains key = value pairs for username:domain = end:start
14774: for active or future "privileged" users with that role in that domain. To avoid
14775: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14776: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 14777:
1.243 albertel 14778: =back
14779:
14780: =head2 User Modification
14781:
14782: =over 4
14783:
14784: =item *
14785:
1.957 raeburn 14786: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14787: user for the level given by URL. Optional start and end dates (leave empty
14788: string or zero for "no date")
1.191 harris41 14789:
14790: =item *
14791:
1.243 albertel 14792: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14793: change a users, password, possible return values are: ok,
14794: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14795: refused
1.191 harris41 14796:
14797: =item *
14798:
1.243 albertel 14799: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14800:
14801: =item *
14802:
1.1058 raeburn 14803: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14804: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14805:
14806: will update user information (firstname,middlename,lastname,generation,
14807: permanentemail), and if forceid is true, student/employee ID also.
14808: A user's institutional affiliation(s) can also be updated.
14809: User information fields will not be overwritten with empty entries
14810: unless the field is included in the $candelete array reference.
14811: This array is included when a single user is modified via "Manage Users",
14812: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14813:
14814: =item *
14815:
1.286 matthew 14816: modifystudent
14817:
1.957 raeburn 14818: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 14819: The course id is resolved based on the current user's environment.
14820: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14821: associated with a course.
14822:
1.297 matthew 14823: This call is essentially a wrapper for lonnet::modifyuser and
14824: lonnet::modify_student_enrollment
1.286 matthew 14825:
14826: Inputs:
14827:
14828: =over 4
14829:
1.957 raeburn 14830: =item B<$udom> Student's loncapa domain
1.286 matthew 14831:
1.957 raeburn 14832: =item B<$uname> Student's loncapa login name
1.286 matthew 14833:
1.964 bisitz 14834: =item B<$uid> Student/Employee ID
1.286 matthew 14835:
1.957 raeburn 14836: =item B<$umode> Student's authentication mode
1.286 matthew 14837:
1.957 raeburn 14838: =item B<$upass> Student's password
1.286 matthew 14839:
1.957 raeburn 14840: =item B<$first> Student's first name
1.286 matthew 14841:
1.957 raeburn 14842: =item B<$middle> Student's middle name
1.286 matthew 14843:
1.957 raeburn 14844: =item B<$last> Student's last name
1.286 matthew 14845:
1.957 raeburn 14846: =item B<$gene> Student's generation
1.286 matthew 14847:
1.957 raeburn 14848: =item B<$usec> Student's section in course
1.286 matthew 14849:
14850: =item B<$end> Unix time of the roles expiration
14851:
14852: =item B<$start> Unix time of the roles start date
14853:
14854: =item B<$forceid> If defined, allow $uid to be changed
14855:
14856: =item B<$desiredhome> server to use as home server for student
14857:
1.957 raeburn 14858: =item B<$email> Student's permanent e-mail address
14859:
14860: =item B<$type> Type of enrollment (auto or manual)
14861:
1.963 raeburn 14862: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14863:
14864: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14865:
1.963 raeburn 14866: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14867:
1.963 raeburn 14868: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14869:
1.1172.2.19 raeburn 14870: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14871:
14872: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957 raeburn 14873:
1.286 matthew 14874: =back
1.297 matthew 14875:
14876: =item *
14877:
14878: modify_student_enrollment
14879:
1.1172.2.31 raeburn 14880: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14881: 'role.request.course' must be defined for this function to proceed.
14882:
14883: Inputs:
14884:
14885: =over 4
14886:
1.1172.2.31 raeburn 14887: =item $udom, student's domain
1.297 matthew 14888:
1.1172.2.31 raeburn 14889: =item $uname, student's name
1.297 matthew 14890:
1.1172.2.31 raeburn 14891: =item $uid, student's user id
1.297 matthew 14892:
1.1172.2.31 raeburn 14893: =item $first, student's first name
1.297 matthew 14894:
14895: =item $middle
14896:
14897: =item $last
14898:
14899: =item $gene
14900:
14901: =item $usec
14902:
14903: =item $end
14904:
14905: =item $start
14906:
1.957 raeburn 14907: =item $type
14908:
14909: =item $locktype
14910:
14911: =item $cid
14912:
14913: =item $selfenroll
14914:
14915: =item $context
14916:
1.1172.2.19 raeburn 14917: =item $credits, number of credits student will earn from this class
14918:
1.1172.2.76 raeburn 14919: =item $instsec, institutional course section code for student
14920:
1.297 matthew 14921: =back
14922:
1.191 harris41 14923:
14924: =item *
14925:
1.243 albertel 14926: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14927: custom role; give a custom role to a user for the level given by URL. Specify
14928: name and domain of role author, and role name
1.191 harris41 14929:
14930: =item *
14931:
1.243 albertel 14932: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14933:
14934: =item *
14935:
1.243 albertel 14936: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14937:
14938: =back
14939:
14940: =head2 Course Infomation
14941:
14942: =over 4
1.191 harris41 14943:
14944: =item *
14945:
1.1118 foxr 14946: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14947: specified course id, including all environment settings for the
14948: course, the description of the course will be in the hash under the
14949: key 'description'
1.191 harris41 14950:
1.1118 foxr 14951: $options is an optional parameter that if supplied is a hash reference that controls
14952: what how this function works. It has the following key/values:
14953:
14954: =over 4
14955:
14956: =item freshen_cache
14957:
14958: If defined, and the environment cache for the course is valid, it is
14959: returned in the returned hash.
14960:
14961: =item one_time
14962:
14963: If defined, the last cache time is set to _now_
14964:
14965: =item user
14966:
14967: If defined, the supplied username is used instead of the current user.
14968:
14969:
14970: =back
14971:
1.191 harris41 14972: =item *
14973:
1.624 albertel 14974: resdata($name,$domain,$type,@which) : request for current parameter
14975: setting for a specific $type, where $type is either 'course' or 'user',
14976: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 14977: answers for 10 minutes.
1.243 albertel 14978:
1.877 foxr 14979: =item *
14980:
14981: get_courseresdata($courseid, $domain) : dump the entire course resource
14982: data base, returning a hash that is keyed by the resource name and has
14983: values that are the resource value. I believe that the timestamps and
14984: versions are also returned.
14985:
1.1172.2.31 raeburn 14986: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14987: supplemental content area. This routine caches the number of files for
14988: 10 minutes.
14989:
1.243 albertel 14990: =back
14991:
14992: =head2 Course Modification
14993:
14994: =over 4
1.191 harris41 14995:
14996: =item *
14997:
1.243 albertel 14998: writecoursepref($courseid,%prefs) : write preferences (environment
14999: database) for a course
1.191 harris41 15000:
15001: =item *
15002:
1.1011 raeburn 15003: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15004:
15005: =item *
15006:
1.1038 raeburn 15007: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15008:
1.1167 droeschl 15009: =item *
15010:
15011: is_course($courseid), is_course($cdom, $cnum)
15012:
15013: Accepts either a combined $courseid (in the form of domain_courseid) or the
15014: two component version $cdom, $cnum. It checks if the specified course exists.
15015:
15016: Returns:
15017: undef if the course doesn't exist, otherwise
15018: in scalar context the combined courseid.
15019: in list context the two components of the course identifier, domain and
15020: courseid.
15021:
1.243 albertel 15022: =back
15023:
1.1172.2.109 raeburn 15024: =head2 Bubblesheet Configuration
15025:
15026: =over 4
15027:
15028: =item *
15029:
15030: get_scantron_config($which)
15031:
15032: $which - the name of the configuration to parse from the file.
15033:
15034: Parses and returns the bubblesheet configuration line selected as a
15035: hash of configuration file fields.
15036:
15037:
15038: Returns:
15039: If the named configuration is not in the file, an empty
15040: hash is returned.
15041:
15042: a hash with the fields
15043: name - internal name for the this configuration setup
15044: description - text to display to operator that describes this config
15045: CODElocation - if 0 or the string 'none'
15046: - no CODE exists for this config
15047: if -1 || the string 'letter'
15048: - a CODE exists for this config and is
15049: a string of letters
15050: Unsupported value (but planned for future support)
15051: if a positive integer
15052: - The CODE exists as the first n items from
15053: the question section of the form
15054: if the string 'number'
15055: - The CODE exists for this config and is
15056: a string of numbers
15057: CODEstart - (only matter if a CODE exists) column in the line where
15058: the CODE starts
15059: CODElength - length of the CODE
15060: IDstart - column where the student/employee ID starts
15061: IDlength - length of the student/employee ID info
15062: Qstart - column where the information from the bubbled
15063: 'questions' start
15064: Qlength - number of columns comprising a single bubble line from
15065: the sheet. (usually either 1 or 10)
15066: Qon - either a single character representing the character used
15067: to signal a bubble was chosen in the positional setup, or
15068: the string 'letter' if the letter of the chosen bubble is
15069: in the final, or 'number' if a number representing the
15070: chosen bubble is in the file (1->A 0->J)
15071: Qoff - the character used to represent that a bubble was
15072: left blank
15073: PaperID - if the scanning process generates a unique number for each
15074: sheet scanned the column that this ID number starts in
15075: PaperIDlength - number of columns that comprise the unique ID number
15076: for the sheet of paper
15077: FirstName - column that the first name starts in
15078: FirstNameLength - number of columns that the first name spans
15079: LastName - column that the last name starts in
15080: LastNameLength - number of columns that the last name spans
15081: BubblesPerRow - number of bubbles available in each row used to
15082: bubble an answer. (If not specified, 10 assumed).
15083:
15084:
15085: =item *
15086:
15087: get_scantronformat_file($cdom)
15088:
15089: $cdom - the course's domain (optional); if not supplied, uses
15090: domain for current $env{'request.course.id'}.
15091:
15092: Returns an array containing lines from the scantron format file for
15093: the domain of the course.
15094:
15095: If a url for a custom.tab file is listed in domain's configuration.db,
15096: lines are from this file.
15097:
15098: Otherwise, if a default.tab has been published in RES space by the
15099: domainconfig user, lines are from this file.
15100:
15101: Otherwise, fall back to getting lines from the legacy file on the
15102: local server: /home/httpd/lonTabs/default_scantronformat.tab
15103:
15104: =back
15105:
1.243 albertel 15106: =head2 Resource Subroutines
15107:
15108: =over 4
1.191 harris41 15109:
15110: =item *
15111:
1.243 albertel 15112: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15113:
15114: =item *
15115:
1.243 albertel 15116: repcopy($filename) : subscribes to the requested file, and attempts to
15117: replicate from the owning library server, Might return
1.607 raeburn 15118: 'unavailable', 'not_found', 'forbidden', 'ok', or
15119: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15120: resource. Expects the local filesystem pathname
15121: (/home/httpd/html/res/....)
15122:
15123: =back
15124:
15125: =head2 Resource Information
15126:
15127: =over 4
1.191 harris41 15128:
15129: =item *
15130:
1.1172.2.28 raeburn 15131: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15132: and returns the value of a variety of different possible values,
15133: $varname should be a request string, and the other parameters can be
15134: used to specify who and what one is asking about. Ordinarily, $cid
15135: does not need to be specified, as it is retrived from
15136: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15137: within lonuserstate::loadmap() when initializing a course, before
15138: $env{'request.course.id'} has been set, so it needs to be provided
15139: in that one case.
1.243 albertel 15140:
15141: Possible values for $varname are environment.lastname (or other item
15142: from the envirnment hash), user.name (or someother aspect about the
15143: user), resource.0.maxtries (or some other part and parameter of a
15144: resource)
1.204 albertel 15145:
15146: =item *
15147:
1.243 albertel 15148: directcondval($number) : get current value of a condition; reads from a state
15149: string
1.204 albertel 15150:
15151: =item *
15152:
1.243 albertel 15153: condval($condidx) : value of condition index based on state
1.204 albertel 15154:
15155: =item *
15156:
1.243 albertel 15157: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15158: resource's metadata, $what should be either a specific key, or either
15159: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15160: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15161:
15162: this function automatically caches all requests
1.191 harris41 15163:
15164: =item *
15165:
1.243 albertel 15166: metadata_query($query,$custom,$customshow) : make a metadata query against the
15167: network of library servers; returns file handle of where SQL and regex results
15168: will be stored for query
1.191 harris41 15169:
15170: =item *
15171:
1.1172.2.66 raeburn 15172: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15173: return symbolic list entry (all arguments optional).
15174:
15175: Args: filename is the filename (including path) for the file for which a symb
15176: is required; donotrecurse, if true will prevent calls to allowed() being made
15177: to check access status if more than one resource was found in the bighash
15178: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15179: a randompick); ignorecachednull, if true will prevent a symb of '' being
15180: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15181: cause possible symbs to be checked to determine if they are subject to content
15182: blocking, if so they will not be included as possible symbs; possibles is a
15183: ref to a hash, which, as a side effect, will be populated with all possible
15184: symbs (content blocking not tested).
15185:
1.243 albertel 15186: returns the data handle
1.191 harris41 15187:
15188: =item *
15189:
1.1172.2.17 raeburn 15190: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 15191: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15192: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 15193: on failure, user must be in a course, as it assumes the existence of
15194: the course initial hash, and uses $env('request.course.id'}. The third
15195: arg is an optional reference to a scalar. If this arg is passed in the
15196: call to symbverify, it will be set to 1 if the symb has been set to be
15197: encrypted; otherwise it will be null.
1.243 albertel 15198:
1.191 harris41 15199: =item *
15200:
1.243 albertel 15201: symbclean($symb) : removes versions numbers from a symb, returns the
15202: cleaned symb
1.191 harris41 15203:
15204: =item *
15205:
1.243 albertel 15206: is_on_map($uri) : checks if the $uri is somewhere on the current
15207: course map, user must be in a course for it to work.
1.191 harris41 15208:
15209: =item *
15210:
1.243 albertel 15211: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15212:
15213: =item *
15214:
1.243 albertel 15215: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15216: a random seed, all arguments are optional, if they aren't sent it uses the
15217: environment to derive them. Note: if symb isn't sent and it can't get one
15218: from &symbread it will use the current time as its return value
1.191 harris41 15219:
15220: =item *
15221:
1.243 albertel 15222: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15223: unfakeable, receipt
1.191 harris41 15224:
15225: =item *
15226:
1.620 albertel 15227: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15228:
15229: =item *
15230:
1.243 albertel 15231: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15232:
15233: =item *
15234:
1.243 albertel 15235: 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 15236:
15237: =item *
15238:
1.243 albertel 15239: 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 15240:
15241: =item *
15242:
1.243 albertel 15243: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15244:
15245: =item *
15246:
1.243 albertel 15247: devalidate($symb) : devalidate temporary spreadsheet calculations,
15248: forcing spreadsheet to reevaluate the resource scores next time.
15249:
1.1172.2.13 raeburn 15250: =item *
15251:
15252: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15253: when viewing in course context.
15254:
15255: input: six args -- filename (decluttered), course number, course domain,
15256: url, symb (if registered) and group (if this is a
15257: group item -- e.g., bulletin board, group page etc.).
15258:
15259: output: array of five scalars --
15260: $cfile -- url for file editing if editable on current server
15261: $home -- homeserver of resource (i.e., for author if published,
15262: or course if uploaded.).
15263: $switchserver -- 1 if server switch will be needed.
15264: $forceedit -- 1 if icon/link should be to go to edit mode
15265: $forceview -- 1 if icon/link should be to go to view mode
15266:
15267: =item *
15268:
15269: is_course_upload($file,$cnum,$cdom)
15270:
15271: Used in course context to determine if current file was uploaded to
15272: the course (i.e., would be found in /userfiles/docs on the course's
15273: homeserver.
15274:
15275: input: 3 args -- filename (decluttered), course number and course domain.
15276: output: boolean -- 1 if file was uploaded.
15277:
1.243 albertel 15278: =back
15279:
15280: =head2 Storing/Retreiving Data
15281:
15282: =over 4
1.191 harris41 15283:
15284: =item *
15285:
1.1172.2.64 raeburn 15286: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15287: permanently for this url; hashref needs to be given and should be a \%hashname;
15288: the remaining args aren't required and if they aren't passed or are '' they will
15289: be derived from the env (with the exception of $laststore, which is an
15290: optional arg used when a user's submission is stored in grading).
15291: $laststore is $version=$timestamp, where $version is the most recent version
15292: number retrieved for the corresponding $symb in the $namespace db file, and
15293: $timestamp is the timestamp for that transaction (UNIX time).
15294: $laststore is currently only passed when cstore() is called by
15295: structuretags::finalize_storage().
1.191 harris41 15296:
15297: =item *
15298:
1.1172.2.64 raeburn 15299: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15300: but uses critical subroutine
1.191 harris41 15301:
15302: =item *
15303:
1.243 albertel 15304: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15305: all args are optional
1.191 harris41 15306:
15307: =item *
15308:
1.717 albertel 15309: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15310: dumps the complete (or key matching regexp) namespace into a hash
15311: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15312: normally &store()ed into
15313:
15314: $range should be either an integer '100' (give me the first 100
15315: matching records)
15316: or be two integers sperated by a - with no spaces
15317: '30-50' (give me the 30th through the 50th matching
15318: records)
15319:
15320:
15321: =item *
15322:
1.1172.2.59 raeburn 15323: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15324: replaces a &store() version of data with a replacement set of data
15325: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15326: reference. If $tolog is true, the transaction is logged in the courselog
15327: with an action=PUTSTORE.
1.717 albertel 15328:
15329: =item *
15330:
1.243 albertel 15331: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15332: works very similar to store/cstore, but all data is stored in a
15333: temporary location and can be reset using tmpreset, $storehash should
15334: be a hash reference, returns nothing on success
1.191 harris41 15335:
15336: =item *
15337:
1.243 albertel 15338: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15339: similar to restore, but all data is stored in a temporary location and
15340: can be reset using tmpreset. Returns a hash of values on success,
15341: error string otherwise.
1.191 harris41 15342:
15343: =item *
15344:
1.243 albertel 15345: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15346: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15347:
15348: =item *
15349:
1.243 albertel 15350: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15351: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15352:
15353: =item *
15354:
1.243 albertel 15355: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15356: namesp ($udom and $uname are optional)
1.191 harris41 15357:
15358: =item *
15359:
1.702 albertel 15360: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15361: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15362: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15363:
1.702 albertel 15364: $range should be either an integer '100' (give me the first 100
15365: matching records)
15366: or be two integers sperated by a - with no spaces
15367: '30-50' (give me the 30th through the 50th matching
15368: records)
1.449 matthew 15369: =item *
15370:
15371: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15372: $store can be a scalar, an array reference, or if the amount to be
15373: incremented is > 1, a hash reference.
15374:
15375: ($udom and $uname are optional)
1.191 harris41 15376:
15377: =item *
15378:
1.243 albertel 15379: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15380: ($udom and $uname are optional)
1.191 harris41 15381:
15382: =item *
15383:
1.243 albertel 15384: cput($namespace,$storehash,$udom,$uname) : critical put
15385: ($udom and $uname are optional)
1.191 harris41 15386:
15387: =item *
15388:
1.748 albertel 15389: newput($namespace,$storehash,$udom,$uname) :
15390:
15391: Attempts to store the items in the $storehash, but only if they don't
15392: currently exist, if this succeeds you can be certain that you have
15393: successfully created a new key value pair in the $namespace db.
15394:
15395:
15396: Args:
15397: $namespace: name of database to store values to
15398: $storehash: hashref to store to the db
15399: $udom: (optional) domain of user containing the db
15400: $uname: (optional) name of user caontaining the db
15401:
15402: Returns:
15403: 'ok' -> succeeded in storing all keys of $storehash
15404: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15405: least <key> already existed in the db (other
15406: requested keys may also already exist)
1.967 bisitz 15407: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15408: 'con_lost' -> unable to contact request server
15409: 'refused' -> action was not allowed by remote machine
15410:
15411:
15412: =item *
15413:
1.243 albertel 15414: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15415: reference filled in from namesp (encrypts the return communication)
15416: ($udom and $uname are optional)
1.191 harris41 15417:
15418: =item *
15419:
1.243 albertel 15420: log($udom,$name,$home,$message) : write to permanent log for user; use
15421: critical subroutine
15422:
1.806 raeburn 15423: =item *
15424:
1.860 raeburn 15425: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15426: array reference filled in from namespace found in domain level on either
15427: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15428:
15429: =item *
15430:
1.860 raeburn 15431: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15432: domain level either on specified domain server ($uhome) or primary domain
15433: server ($udom and $uhome are optional)
1.806 raeburn 15434:
1.943 raeburn 15435: =item *
15436:
1.1172.2.35 raeburn 15437: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15438: for: authentication, language, quotas, timezone, date locale, and portal URL in
15439: the target domain.
15440:
15441: May also include additional key => value pairs for the following groups:
15442:
15443: =over
15444:
15445: =item
15446: disk quotas (MB allocated by default to portfolios and authoring spaces).
15447:
15448: =over
15449:
15450: =item defaultquota, authorquota
15451:
15452: =back
15453:
15454: =item
15455: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15456: portfolio for users).
15457:
15458: =over
15459:
15460: =item
15461: aboutme, blog, webdav, portfolio
15462:
15463: =back
15464:
15465: =item
15466: requestcourses: ability to request courses, and how requests are processed.
15467:
15468: =over
15469:
15470: =item
1.1172.2.37 raeburn 15471: official, unofficial, community, textbook
1.1172.2.35 raeburn 15472:
15473: =back
15474:
15475: =item
15476: inststatus: types of institutional affiliation, and order in which they are displayed.
15477:
15478: =over
15479:
15480: =item
1.1172.2.44 raeburn 15481: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15482:
15483: =back
15484:
15485: =item
15486: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15487: for course's uploaded content.
15488:
15489: =over
15490:
15491: =item
1.1172.2.68 raeburn 15492: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15493: communityquota, textbookquota
1.1172.2.35 raeburn 15494:
15495: =back
15496:
15497: =item
15498: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15499: on your servers.
15500:
15501: =over
15502:
15503: =item
15504: remotesessions, hostedsessions
15505:
15506: =back
15507:
15508: =back
15509:
15510: In cases where a domain coordinator has never used the "Set Domain Configuration"
15511: utility to create a configuration.db file on a domain's primary library server
15512: only the following domain defaults: auth_def, auth_arg_def, lang_def
15513: -- corresponding values are authentication type (internal, krb4, krb5,
15514: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15515: will be available. Values are retrieved from cache (if current), unless the
15516: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15517: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15518:
15519: Typical usage:
1.943 raeburn 15520:
1.1172.2.35 raeburn 15521: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15522:
1.243 albertel 15523: =back
15524:
15525: =head2 Network Status Functions
15526:
15527: =over 4
1.191 harris41 15528:
15529: =item *
15530:
1.1137 raeburn 15531: dirlist() : return directory list based on URI (first arg).
15532:
15533: Inputs: 1 required, 5 optional.
15534:
15535: =over
15536:
15537: =item
15538: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15539:
15540: =item
15541: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15542:
15543: =item
15544: $username - username of user/course to be listed. Extracted from $uri if absent.
15545:
15546: =item
15547: $getpropath - boolean: 1 if prepend path using &propath().
15548:
15549: =item
15550: $getuserdir - boolean: 1 if prepend path for "userfiles".
15551:
15552: =item
15553: $alternateRoot - path to prepend in place of path from $uri.
15554:
15555: =back
15556:
15557: Returns: Array of up to two items.
15558:
15559: =over
15560:
15561: a reference to an array of files/subdirectories
15562:
15563: =over
15564:
15565: Each element in the array of files/subdirectories is a & separated list of
15566: item name and the result of running stat on the item. If dirlist was requested
15567: for a file instead of a directory, the item name will be ''. For a directory
15568: listing, if the item is a metadata file, the element will end &N&M
15569: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15570: default copyright set (1).
15571:
15572: =back
15573:
15574: a scalar containing error condition (if encountered).
15575:
15576: =over
15577:
15578: =item
15579: no_host (no homeserver identified for $username:$domain).
15580:
15581: =item
15582: no_such_host (server contacted for listing not identified as valid host).
15583:
15584: =item
15585: con_lost (connection to remote server failed).
15586:
15587: =item
15588: refused (invalid $username:$domain received on lond side).
15589:
15590: =item
15591: no_such_dir (directory at specified path on lond side does not exist).
15592:
15593: =item
15594: empty (directory at specified path on lond side is empty).
15595:
15596: =over
15597:
15598: This is currently not encountered because the &ls3, &ls2,
15599: &ls (_handler) routines on the lond side do not filter out
15600: . and .. from a directory listing.
15601:
15602: =back
15603:
15604: =back
15605:
15606: =back
1.191 harris41 15607:
15608: =item *
15609:
1.243 albertel 15610: spareserver() : find server with least workload from spare.tab
15611:
1.986 foxr 15612:
15613: =item *
15614:
15615: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15616: if there is no corresponding loncapa host.
15617:
1.243 albertel 15618: =back
15619:
1.986 foxr 15620:
1.243 albertel 15621: =head2 Apache Request
15622:
15623: =over 4
1.191 harris41 15624:
15625: =item *
15626:
1.243 albertel 15627: ssi($url,%hash) : server side include, does a complete request cycle on url to
15628: localhost, posts hash
15629:
15630: =back
15631:
15632: =head2 Data to String to Data
15633:
15634: =over 4
1.191 harris41 15635:
15636: =item *
15637:
1.243 albertel 15638: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15639: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15640:
15641: =item *
15642:
1.243 albertel 15643: hashref2str($hashref) : convert a hashref into a string complete with
15644: escaping and '=' and '&' separators, supports elements that are
15645: arrayrefs and hashrefs
1.191 harris41 15646:
15647: =item *
15648:
1.243 albertel 15649: arrayref2str($arrayref) : convert an arrayref into a string complete
15650: with escaping and '&' separators, supports elements that are arrayrefs
15651: and hashrefs
1.191 harris41 15652:
15653: =item *
15654:
1.243 albertel 15655: str2hash($string) : convert string to hash using unescaping and
15656: splitting on '=' and '&', supports elements that are arrayrefs and
15657: hashrefs
1.191 harris41 15658:
15659: =item *
15660:
1.243 albertel 15661: str2array($string) : convert string to hash using unescaping and
15662: splitting on '&', supports elements that are arrayrefs and hashrefs
15663:
15664: =back
15665:
15666: =head2 Logging Routines
15667:
15668:
15669: These routines allow one to make log messages in the lonnet.log and
15670: lonnet.perm logfiles.
1.191 harris41 15671:
1.1119 foxr 15672: =over 4
15673:
1.191 harris41 15674: =item *
15675:
1.243 albertel 15676: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15677:
15678: =item *
15679:
1.243 albertel 15680: logthis() : append message to the normal lonnet.log file, it gets
15681: preiodically rolled over and deleted.
1.191 harris41 15682:
15683: =item *
15684:
1.243 albertel 15685: logperm() : append a permanent message to lonnet.perm.log, this log
15686: file never gets deleted by any automated portion of the system, only
15687: messages of critical importance should go in here.
15688:
1.1119 foxr 15689:
1.243 albertel 15690: =back
15691:
15692: =head2 General File Helper Routines
15693:
15694: =over 4
1.191 harris41 15695:
15696: =item *
15697:
1.481 raeburn 15698: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15699: (a) files in /uploaded
15700: (i) If a local copy of the file exists -
15701: compares modification date of local copy with last-modified date for
15702: definitive version stored on home server for course. If local copy is
15703: stale, requests a new version from the home server and stores it.
15704: If the original has been removed from the home server, then local copy
15705: is unlinked.
15706: (ii) If local copy does not exist -
15707: requests the file from the home server and stores it.
15708:
15709: If $caller is 'uploadrep':
15710: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15711: for request for files originally uploaded via DOCS.
15712: - returns 'ok' if fresh local copy now available, -1 otherwise.
15713:
15714: Otherwise:
15715: This indicates a call from the content generation phase of the request.
15716: - returns the entire contents of the file or -1.
15717:
15718: (b) files in /res
15719: - returns the entire contents of a file or -1;
15720: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15721:
1.712 albertel 15722:
15723: =item *
15724:
15725: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15726: reference
15727:
15728: returns either a stat() list of data about the file or an empty list
15729: if the file doesn't exist or couldn't find out about it (connection
15730: problems or user unknown)
15731:
1.191 harris41 15732: =item *
15733:
1.243 albertel 15734: filelocation($dir,$file) : returns file system location of a file
15735: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15736: directory that relative $file lookups are to looked in ($dir of /a/dir
15737: and a file of ../bob will become /a/bob)
1.191 harris41 15738:
15739: =item *
15740:
15741: hreflocation($dir,$file) : returns file system location or a URL; same as
15742: filelocation except for hrefs
15743:
15744: =item *
15745:
1.1172.2.49 raeburn 15746: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15747: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15748:
1.243 albertel 15749: =back
15750:
1.608 albertel 15751: =head2 Usererfile file routines (/uploaded*)
15752:
15753: =over 4
15754:
15755: =item *
15756:
15757: userfileupload(): main rotine for putting a file in a user or course's
15758: filespace, arguments are,
15759:
1.620 albertel 15760: formname - required - this is the name of the element in $env where the
1.608 albertel 15761: filename, and the contents of the file to create/modifed exist
1.620 albertel 15762: the filename is in $env{'form.'.$formname.'.filename'} and the
15763: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15764: context - if coursedoc, store the file in the course of the active role
15765: of the current user;
15766: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15767: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15768: subdir - required - subdirectory to put the file in under ../userfiles/
15769: if undefined, it will be placed in "unknown"
15770:
15771: (This routine calls clean_filename() to remove any dangerous
15772: characters from the filename, and then calls finuserfileupload() to
15773: complete the transaction)
15774:
15775: returns either the url of the uploaded file (/uploaded/....) if successful
15776: and /adm/notfound.html if unsuccessful
15777:
15778: =item *
15779:
15780: clean_filename(): routine for cleaing a filename up for storage in
15781: userfile space, argument is:
15782:
15783: filename - proposed filename
15784:
15785: returns: the new clean filename
15786:
15787: =item *
15788:
1.1090 raeburn 15789: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15790: userspace, probably shouldn't be called directly
15791:
15792: docuname: username or courseid of destination for the file
15793: docudom: domain of user/course of destination for the file
15794: formname: same as for userfileupload()
1.1090 raeburn 15795: fname: filename (including subdirectories) for the file
15796: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 15797: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 15798: allfiles: reference to hash used to store objects found by parser
15799: codebase: reference to hash used for codebases of java objects found by parser
15800: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15801: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15802: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15803: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15804: context: if 'overwrite', will move the uploaded file from its temporary location to
15805: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15806: mimetype: reference to scalar to accommodate mime type determined
15807: from File::MMagic if $parser = parse.
1.608 albertel 15808:
15809: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15810: and /adm/notfound.html if unsuccessful (or an error message if context
15811: was 'overwrite').
15812:
1.608 albertel 15813:
15814: =item *
15815:
15816: renameuserfile(): renames an existing userfile to a new name
15817:
15818: Args:
15819: docuname: username or courseid of destination for the file
15820: docudom: domain of user/course of destination for the file
15821: old: current file name (including any subdirs under userfiles)
15822: new: desired file name (including any subdirs under userfiles)
15823:
15824: =item *
15825:
15826: mkdiruserfile(): creates a directory is a userfiles dir
15827:
15828: Args:
15829: docuname: username or courseid of destination for the file
15830: docudom: domain of user/course of destination for the file
15831: dir: dir to create (including any subdirs under userfiles)
15832:
15833: =item *
15834:
15835: removeuserfile(): removes a file that exists in userfiles
15836:
15837: Args:
15838: docuname: username or courseid of destination for the file
15839: docudom: domain of user/course of destination for the file
15840: fname: filname to delete (including any subdirs under userfiles)
15841:
15842: =item *
15843:
15844: removeuploadedurl(): convience function for removeuserfile()
15845:
15846: Args:
15847: url: a full /uploaded/... url to delete
15848:
1.747 albertel 15849: =item *
15850:
15851: get_portfile_permissions():
15852: Args:
15853: domain: domain of user or course contain the portfolio files
15854: user: name of user or num of course contain the portfolio files
15855: Returns:
15856: hashref of a dump of the proper file_permissions.db
15857:
15858:
15859: =item *
15860:
15861: get_access_controls():
15862:
15863: Args:
15864: current_permissions: the hash ref returned from get_portfile_permissions()
15865: group: (optional) the group you want the files associated with
15866: file: (optional) the file you want access info on
15867:
15868: Returns:
1.749 raeburn 15869: a hash (keys are file names) of hashes containing
15870: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15871: values are XML containing access control settings (see below)
1.747 albertel 15872:
15873: Internal notes:
15874:
1.749 raeburn 15875: access controls are stored in file_permissions.db as key=value pairs.
15876: key -> path to file/file_name\0uniqueID:scope_end_start
15877: where scope -> public,guest,course,group,domains or users.
15878: end -> UNIX time for end of access (0 -> no end date)
15879: start -> UNIX time for start of access
15880:
15881: value -> XML description of access control
15882: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15883: <start></start>
15884: <end></end>
15885:
15886: <password></password> for scope type = guest
15887:
15888: <domain></domain> for scope type = course or group
15889: <number></number>
15890: <roles id="">
15891: <role></role>
15892: <access></access>
15893: <section></section>
15894: <group></group>
15895: </roles>
15896:
15897: <dom></dom> for scope type = domains
15898:
15899: <users> for scope type = users
15900: <user>
15901: <uname></uname>
15902: <udom></udom>
15903: </user>
15904: </users>
15905: </scope>
15906:
15907: Access data is also aggregated for each file in an additional key=value pair:
15908: key -> path to file/file_name\0accesscontrol
15909: value -> reference to hash
15910: hash contains key = value pairs
15911: where key = uniqueID:scope_end_start
15912: value = UNIX time record was last updated
15913:
15914: Used to improve speed of look-ups of access controls for each file.
15915:
15916: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15917:
1.1172.2.13 raeburn 15918: =item *
15919:
1.749 raeburn 15920: modify_access_controls():
15921:
15922: Modifies access controls for a portfolio file
15923: Args
15924: 1. file name
15925: 2. reference to hash of required changes,
15926: 3. domain
15927: 4. username
15928: where domain,username are the domain of the portfolio owner
15929: (either a user or a course)
15930:
15931: Returns:
15932: 1. result of additions or updates ('ok' or 'error', with error message).
15933: 2. result of deletions ('ok' or 'error', with error message).
15934: 3. reference to hash of any new or updated access controls.
15935: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15936: key = integer (inbound ID)
1.1172.2.13 raeburn 15937: value = uniqueID
15938:
15939: =item *
15940:
15941: get_timebased_id():
15942:
15943: Attempts to get a unique timestamp-based suffix for use with items added to a
15944: course via the Course Editor (e.g., folders, composite pages,
15945: group bulletin boards).
15946:
15947: Args: (first three required; six others optional)
15948:
15949: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15950: docssequence, or name of group
15951:
15952: 2. keyid (alphanumeric): name of temporary locking key in hash,
15953: e.g., num, boardids
15954:
15955: 3. namespace: name of gdbm file used to store suffixes already assigned;
15956: file will be named nohist_namespace.db
15957:
15958: 4. cdom: domain of course; default is current course domain from %env
15959:
15960: 5. cnum: course number; default is current course number from %env
15961:
15962: 6. idtype: set to concat if an additional digit is to be appended to the
15963: unix timestamp to form the suffix, if the plain timestamp is already
15964: in use. Default is to not do this, but simply increment the unix
15965: timestamp by 1 until a unique key is obtained.
15966:
15967: 7. who: holder of locking key; defaults to user:domain for user.
15968:
15969: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15970: retrying); default is 3.
15971:
15972: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15973:
15974: Returns:
15975:
15976: 1. suffix obtained (numeric)
15977:
15978: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15979:
15980: 3. error: contains (localized) error message if an error occurred.
15981:
1.747 albertel 15982:
1.608 albertel 15983: =back
15984:
1.243 albertel 15985: =head2 HTTP Helper Routines
15986:
15987: =over 4
15988:
1.191 harris41 15989: =item *
15990:
15991: escape() : unpack non-word characters into CGI-compatible hex codes
15992:
15993: =item *
15994:
15995: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15996:
1.243 albertel 15997: =back
15998:
15999: =head1 PRIVATE SUBROUTINES
16000:
16001: =head2 Underlying communication routines (Shouldn't call)
16002:
16003: =over 4
16004:
16005: =item *
16006:
16007: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16008:
16009: =item *
16010:
16011: reply() : uses subreply to send a message to remote machine, logs all failures
16012:
16013: =item *
16014:
16015: critical() : passes a critical message to another server; if cannot
16016: get through then place message in connection buffer directory and
16017: returns con_delayed, if incapable of saving message, returns
16018: con_failed
16019:
16020: =item *
16021:
16022: reconlonc() : tries to reconnect lonc client processes.
16023:
16024: =back
16025:
16026: =head2 Resource Access Logging
16027:
16028: =over 4
16029:
16030: =item *
16031:
16032: flushcourselogs() : flush (save) buffer logs and access logs
16033:
16034: =item *
16035:
16036: courselog($what) : save message for course in hash
16037:
16038: =item *
16039:
16040: courseacclog($what) : save message for course using &courselog(). Perform
16041: special processing for specific resource types (problems, exams, quizzes, etc).
16042:
1.191 harris41 16043: =item *
16044:
16045: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16046: as a PerlChildExitHandler
1.243 albertel 16047:
16048: =back
16049:
16050: =head2 Other
16051:
16052: =over 4
16053:
16054: =item *
16055:
16056: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16057:
16058: =back
16059:
16060: =cut
1.877 foxr 16061:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>