File:
[LON-CAPA] /
loncom /
homework /
lonhomework.pm
Revision
1.358:
download - view:
text,
annotated -
select for diffs
Mon Oct 5 02:35:40 2015 UTC (8 years, 10 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Slots can now require each student to check-in from a unique IP address
when using a particular slot for a specific resource. The IP address of
the student's computer is then tied to that student's access to the resource
thereafter, until the end date of the slot.
(Intended use case is high stakes online testing where students are using
computers with statically assigned IP addresses).
1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Homework handler
3: #
4: # $Id: lonhomework.pm,v 1.358 2015/10/05 02:35:40 raeburn Exp $
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:
28:
29: package Apache::lonhomework;
30: use strict;
31: use Apache::style();
32: use Apache::lonxml();
33: use Apache::lonnet;
34: use Apache::lonplot();
35: use Apache::inputtags();
36: use Apache::structuretags();
37: use Apache::randomlabel();
38: use Apache::response();
39: use Apache::hint();
40: use Apache::outputtags();
41: use Apache::caparesponse();
42: use Apache::radiobuttonresponse();
43: use Apache::optionresponse();
44: use Apache::imageresponse();
45: use Apache::essayresponse();
46: use Apache::externalresponse();
47: use Apache::rankresponse();
48: use Apache::matchresponse();
49: use Apache::chemresponse();
50: use Apache::functionplotresponse();
51: use Apache::drawimage();
52: use Apache::loncapamath();
53: use Apache::Constants qw(:common);
54: use Apache::loncommon();
55: use Apache::lonparmset();
56: use Apache::lonlocal;
57: use Time::HiRes qw( gettimeofday tv_interval );
58: use HTML::Entities();
59: use File::Copy();
60:
61: # FIXME - improve commenting
62:
63:
64: BEGIN {
65: &Apache::lonxml::register_insert();
66: }
67:
68:
69: =pod
70:
71: =item set_bubble_lines()
72:
73: Called at analysis time to set the bubble lines
74: hash for the problem.. This should be called in the
75: end_problemtype tag in analysis mode.
76:
77: We fetch the hash of part id counters from lonxml
78: and push them into analyze:{part_id.bubble_lines}.
79:
80: =cut
81:
82: sub set_bubble_lines {
83: my %bubble_counters = &Apache::lonxml::get_bubble_line_hash();
84:
85: foreach my $key (keys(%bubble_counters)) {
86: $Apache::lonhomework::analyze{"$key.bubble_lines"} =
87: $bubble_counters{"$key"};
88: }
89: }
90:
91: #
92: # Decides what targets to render for.
93: # Implicit inputs:
94: # Various session environment variables:
95: # request.state - published - is a /res/ resource
96: # uploaded - is a /uploaded/ resource
97: # contruct - is a /priv/ resource
98: # form.grade_target - a form parameter requesting a specific target
99: sub get_target {
100: &Apache::lonxml::debug("request.state = $env{'request.state'}");
101: if( defined($env{'form.grade_target'})) {
102: &Apache::lonxml::debug("form.grade_target= $env{'form.grade_target'}");
103: } else {
104: &Apache::lonxml::debug("form.grade_target <undefined>");
105: }
106: if (($env{'request.state'} eq "published") ||
107: ($env{'request.state'} eq "uploaded")) {
108: if ( defined($env{'form.grade_target'} )
109: && ($env{'form.grade_target'} eq 'tex')) {
110: return ($env{'form.grade_target'});
111: } elsif ( defined($env{'form.grade_target'} )
112: && ($Apache::lonhomework::viewgrades eq 'F' )) {
113: return ($env{'form.grade_target'});
114: } elsif ( $env{'form.grade_target'} eq 'webgrade'
115: && ($Apache::lonhomework::queuegrade eq 'F' )) {
116: return ($env{'form.grade_target'});
117: } elsif ($env{'form.grade_target'} eq 'answer') {
118: if ($env{'form.answer_output_mode'} eq 'tex') {
119: return ($env{'form.grade_target'});
120: }
121: }
122: if ($env{'form.webgrade'} &&
123: ($Apache::lonhomework::modifygrades eq 'F'
124: || $Apache::lonhomework::queuegrade eq 'F' )) {
125: return ('grade','webgrade');
126: }
127: if ( defined($env{'form.submitted'}) &&
128: ( !defined($env{'form.newrandomization'}))) {
129: return ('grade', 'web');
130: } else {
131: return ('web');
132: }
133: } elsif ($env{'request.state'} eq "construct") {
134: #
135: # We are in construction space, editing and testing problems
136: #
137: if ( defined($env{'form.grade_target'}) ) {
138: return ($env{'form.grade_target'});
139: }
140: if ( defined($env{'form.preview'})) {
141: if ( defined($env{'form.submitted'})) {
142: #
143: # We are doing a problem preview
144: #
145: return ('grade', 'web');
146: } else {
147: return ('web');
148: }
149: } else {
150: if ($env{'form.problemstate'} eq 'WEB_GRADE') {
151: return ('grade','webgrade','answer');
152: } elsif ($env{'form.problemmode'} eq 'view') {
153: return ('grade','web','answer');
154: } elsif ($env{'form.problemmode'} eq 'saveview') {
155: return ('modified','web','answer');
156: } elsif ($env{'form.problemmode'} eq 'discard') {
157: return ('web','answer');
158: } elsif (($env{'form.problemmode'} eq 'saveedit') ||
159: ($env{'form.problemmode'} eq 'undo')) {
160: return ('modified','no_output_web','edit');
161: } elsif ($env{'form.problemmode'} eq 'edit') {
162: return ('no_output_web','edit');
163: } else {
164: return ('web');
165: }
166: }
167: #
168: # End of Authoring Space
169: #
170: }
171: #
172: # Huh? We are nowhere, so do nothing.
173: #
174: return ();
175: }
176:
177: sub setup_vars {
178: my ($target) = @_;
179: return ';'
180: # return ';$external::target='.$target.';';
181: }
182:
183: sub proctor_checked_in {
184: my ($slot_name,$slot,$type)=@_;
185: my @possible_proctors=split(",",$slot->{'proctor'});
186:
187: return 1 if (!@possible_proctors);
188:
189: my $key;
190: if ($type eq 'Task') {
191: my $version=$Apache::lonhomework::history{'resource.0.version'};
192: $key ="resource.$version.0.checkedin";
193: } elsif ($type eq 'problem') {
194: $key ='resource.0.checkedin';
195: }
196: # backward compatability, used to be username@domain,
197: # now is username:domain
198: my $who = $Apache::lonhomework::history{$key};
199: if ($who !~ /:/) {
200: $who =~ tr/@/:/;
201: }
202: foreach my $possible (@possible_proctors) {
203: if ($who eq $possible
204: && $Apache::lonhomework::history{$key.'.slot'} eq $slot_name) {
205: return 1;
206: }
207: }
208:
209: return 0;
210: }
211:
212: sub check_slot_access {
213: my ($id,$type,$symb)=@_;
214:
215: # does it pass normal muster
216: my ($status,$datemsg)=&check_access($id,$symb);
217:
218: my $useslots = &Apache::lonnet::EXT("resource.0.useslots",$symb);
219: if ($useslots ne 'resource' && $useslots ne 'map'
220: && $useslots ne 'map_map') {
221: return ($status,$datemsg);
222: }
223:
224: my $checkin = 'resource.0.checkedin';
225: my $version;
226: if ($type eq 'Task') {
227: $version=$Apache::lonhomework::history{'resource.version'};
228: $checkin = "resource.$version.0.checkedin";
229: }
230: my $checkedin = $Apache::lonhomework::history{$checkin};
231: my ($returned_slot,$slot_name,$checkinslot,$ipused,$blockip,$now,$ip);
232: $now = time;
233: $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
234:
235: if ($checkedin) {
236: $checkinslot = $Apache::lonhomework::history{"$checkin.slot"};
237: my %slot=&Apache::lonnet::get_slot($checkinslot);
238: if ($slot{'iptied'}) {
239: $ipused = $Apache::lonhomework::history{"$checkin.ip"};
240: unless (($ip ne '') && ($ipused eq $ip)) {
241: $blockip = $slot{'iptied'};
242: $slot_name = $checkinslot;
243: $returned_slot = \%slot;
244: }
245: }
246: }
247:
248: if ($status eq 'SHOW_ANSWER') {
249: if ($blockip eq 'answer') {
250: return ('NEED_DIFFERENT_IP','',$slot_name,$returned_slot,$ipused);
251: } else {
252: return ($status,$datemsg);
253: }
254: }
255:
256: if ($status eq 'CLOSED' ||
257: $status eq 'INVALID_ACCESS' ||
258: $status eq 'UNAVAILABLE') {
259: return ($status,$datemsg);
260: }
261: if ($env{'request.state'} eq "construct") {
262: return ($status,$datemsg);
263: }
264:
265: if ($type eq 'Task') {
266: if ($checkedin &&
267: $Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass') {
268: if ($blockip eq 'answer') {
269: return ('NEED_DIFFERENT_IP','',$slot_name,$returned_slot,$ipused);
270: } else {
271: return ('SHOW_ANSWER');
272: }
273: }
274: }
275:
276: my $availablestudent = &Apache::lonnet::EXT("resource.0.availablestudent",$symb);
277: my $available = &Apache::lonnet::EXT("resource.0.available",$symb);
278: my @slots= (split(':',$availablestudent),split(':',$available));
279:
280: # if (!@slots) {
281: # return ($status,$datemsg);
282: # }
283: undef($returned_slot);
284: undef($slot_name);
285: my $slotstatus='NOT_IN_A_SLOT';
286: my $num_usable_slots = 0;
287: if (!$symb) {
288: ($symb) = &Apache::lonnet::whichuser();
289: }
290: foreach my $slot (@slots) {
291: $slot =~ s/(^\s*|\s*$)//g;
292: &Apache::lonxml::debug("getting $slot");
293: my %slot=&Apache::lonnet::get_slot($slot);
294: &Apache::lonhomework::showhash(%slot);
295: next if ($slot{'endtime'} < $now);
296: $num_usable_slots ++;
297: if ($slot{'starttime'} < $now &&
298: $slot{'endtime'} > $now &&
299: &Apache::loncommon::check_ip_acc($slot{'ip'})) {
300: if ($slot{'iptied'}) {
301: if ($env{'request.course.id'}) {
302: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
303: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
304: if ($slot eq $checkinslot) {
305: if ($ip eq $ipused) {
306: &Apache::lonxml::debug("$slot is good");
307: $slotstatus ='NEEDS_CHECKIN';
308: } else {
309: $slotstatus = 'NEED_DIFFERENT_IP';
310: $slot_name = $slot;
311: $returned_slot = \%slot;
312: last;
313: }
314: } elsif ($ip) {
315: my $uniqkey = "$slot\0$symb\0$ip";
316: my %used_ip = &Apache::lonnet::get('slot_uniqueips',[$uniqkey],$cdom,$cnum);
317: if ($used_ip{$uniqkey}) {
318: $slotstatus = 'NEED_DIFFERENT_IP';
319: } else {
320: &Apache::lonxml::debug("$slot is good");
321: $slotstatus ='NEEDS_CHECKIN';
322: }
323: }
324: }
325: } else {
326: &Apache::lonxml::debug("$slot is good");
327: $slotstatus='NEEDS_CHECKIN';
328: }
329: if ($slotstatus eq 'NEEDS_CHECKIN') {
330: $returned_slot=\%slot;
331: $slot_name=$slot;
332: last;
333: }
334: }
335: }
336: if ($slotstatus eq 'NEEDS_CHECKIN' &&
337: &proctor_checked_in($slot_name,$returned_slot,$type)) {
338: &Apache::lonxml::debug("proctor checked in");
339: $slotstatus=$status;
340: }
341:
342: my ($is_correct,$got_grade);
343: if ($type eq 'Task') {
344: my $version=$Apache::lonhomework::history{'resource.0.version'};
345: $got_grade =
346: ($Apache::lonhomework::history{"resource.$version.0.status"}
347: =~ /^(?:pass|fail)$/);
348: $is_correct =
349: ($Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass'
350: || $Apache::lonhomework::history{"resource.0.solved"} =~ /^correct_/ );
351: } elsif ($type eq 'problem') {
352: $got_grade = 1;
353: $is_correct =
354: ($Apache::lonhomework::history{"resource.0.solved"} =~/^correct_/);
355: }
356:
357: &Apache::lonxml::debug(" slot is $slotstatus checkedin ($checkedin) got_grade ($got_grade) is_correct ($is_correct)");
358:
359: # no slot is currently open, and has been checked in for this version
360: # but hasn't got a grade, therefore must be awaiting a grade
361: if (!defined($slot_name)
362: && $checkedin
363: && !$got_grade) {
364: return ('WAITING_FOR_GRADE');
365: }
366:
367: # Previously used slot is no longer open, and has been checked in for this version.
368: # However, the problem is not closed, and potentially, another slot might be
369: # used to gain access to it to work on it, until the due date is reached, and the
370: # problem then becomes CLOSED. Therefore return the slotstatus -
371: # (which will be one of: NOT_IN_A_SLOT, RESERVABLE, RESERVABLE_LATER, or NOTRESERVABLE).
372: if (!defined($slot_name) && $type eq 'problem') {
373: if ($slotstatus eq 'NOT_IN_A_SLOT') {
374: if (!$num_usable_slots) {
375: if ($env{'request.course.id'}) {
376: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
377: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
378: unless ($symb) {
379: ($symb)=&Apache::lonnet::whichuser();
380: }
381: $slotstatus = 'NOTRESERVABLE';
382: my ($reservable_now_order,$reservable_now,$reservable_future_order,
383: $reservable_future) =
384: &Apache::loncommon::get_future_slots($cnum,$cdom,$now,$symb);
385: if ((ref($reservable_now_order) eq 'ARRAY') && (ref($reservable_now) eq 'HASH')) {
386: if (@{$reservable_now_order} > 0) {
387: $slotstatus = 'RESERVABLE';
388: $datemsg = $reservable_now->{$reservable_now_order->[-1]}{'endreserve'};
389: }
390: }
391: unless ($slotstatus eq 'RESERVABLE') {
392: if ((ref($reservable_future_order) eq 'ARRAY') && (ref($reservable_future) eq 'HASH')) {
393: if (@{$reservable_future_order} > 0) {
394: $slotstatus = 'RESERVABLE_LATER';
395: $datemsg = $reservable_future->{$reservable_future_order->[0]}{'startreserve'};
396: }
397: }
398: }
399: }
400: }
401: }
402: return ($slotstatus,$datemsg);
403: }
404:
405: if ($slotstatus eq 'NOT_IN_A_SLOT'
406: && $checkedin ) {
407:
408: if ($got_grade) {
409: if ($blockip eq 'answer') {
410: return ('NEED_DIFFERENT_IP','',$slot_name,$returned_slot,$ipused);
411: } else {
412: return ('SHOW_ANSWER');
413: }
414: } else {
415: return ('WAITING_FOR_GRADE');
416: }
417:
418: }
419:
420: if (($is_correct) && ($blockip ne 'answer')) {
421: if ($type eq 'problem') {
422: return ($status);
423: }
424: return ('SHOW_ANSWER');
425: }
426:
427: if ( $status eq 'CANNOT_ANSWER' &&
428: ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT' &&
429: $slotstatus ne 'NEED_DIFFERENT_IP') ) {
430: return ($status,$datemsg);
431: }
432: return ($slotstatus,$datemsg,$slot_name,$returned_slot,$ipused);
433: }
434:
435: # JB, 9/24/2002: Any changes in this function may require a change
436: # in lonnavmaps::resource::getDateStatus.
437: sub check_access {
438: my ($id,$symb) = @_;
439: my $date ='';
440: my $status;
441: my $datemsg = '';
442: my $lastdate = '';
443: my $type;
444: my $passed;
445:
446: if ($env{'request.state'} eq "construct") {
447: if ($env{'form.problemstate'}) {
448: if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
449: if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct'
450: && &hide_problem_status())) {
451: return ('CANNOT_ANSWER',
452: &mt('is in this state due to author settings.'));
453: }
454: } else {
455: return ($env{'form.problemstate'},
456: &mt('is in this state due to author settings.'));
457: }
458: }
459: &Apache::lonxml::debug("in construction ignoring dates");
460: $status='CAN_ANSWER';
461: $datemsg=&mt('is in under construction');
462: # return ($status,$datemsg);
463: }
464:
465: &Apache::lonxml::debug("checking for part :$id:");
466: &Apache::lonxml::debug("time:".time);
467:
468: unless ($symb) {
469: ($symb)=&Apache::lonnet::whichuser();
470: }
471: &Apache::lonxml::debug("symb:".$symb);
472: #if ($env{'request.state'} ne "construct" && $symb ne '') {
473: if ($env{'request.state'} ne "construct") {
474: my $idacc = &Apache::lonnet::EXT("resource.$id.acc",$symb);
475: my $allowed=&Apache::loncommon::check_ip_acc($idacc);
476: if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
477: $status='INVALID_ACCESS';
478: $date=&mt("can not be accessed from your location.");
479: return($status,$date);
480: }
481: if ($env{'form.grade_imsexport'}) {
482: if (($env{'request.course.id'}) &&
483: (&Apache::lonnet::allowed('mdc',$env{'request.course.id'}))) {
484: return ('SHOW_ANSWER');
485: }
486: }
487: foreach my $temp ("opendate","duedate","answerdate") {
488: $lastdate = $date;
489: if ($temp eq 'duedate') {
490: $date = &due_date($id,$symb);
491: } else {
492: $date = &Apache::lonnet::EXT("resource.$id.$temp",$symb);
493: }
494:
495: my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type",$symb);
496: if ($thistype =~ /^(con_lost|no_such_host)/ ||
497: $date =~ /^(con_lost|no_such_host)/) {
498: $status='UNAVAILABLE';
499: $date=&mt("may open later.");
500: return($status,$date);
501: }
502: if ($thistype eq 'date_interval') {
503: if ($temp eq 'opendate') {
504: $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)-$date;
505: }
506: if ($temp eq 'answerdate') {
507: $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)+$date;
508: }
509: }
510: &Apache::lonxml::debug("found :$date: for :$temp:");
511: if ($date eq '') {
512: $date = &mt("an unknown date"); $passed = 0;
513: } elsif ($date eq 'con_lost') {
514: $date = &mt("an indeterminate date"); $passed = 0;
515: } else {
516: if (time < $date) { $passed = 0; } else { $passed = 1; }
517: $date = &Apache::lonlocal::locallocaltime($date);
518: }
519: if (!$passed) { $type=$temp; last; }
520: }
521: &Apache::lonxml::debug("have :$type:$passed:");
522: if ($passed) {
523: $status='SHOW_ANSWER';
524: $datemsg=$date;
525: } elsif ($type eq 'opendate') {
526: $status='CLOSED';
527: $datemsg = &mt('will open on [_1]',$date);
528: } elsif ($type eq 'duedate') {
529: $status='CAN_ANSWER';
530: $datemsg = &mt('is due at [_1]',$date);
531: } elsif ($type eq 'answerdate') {
532: $status='CLOSED';
533: $datemsg = &mt('was due on [_1], and answers will be available on [_2]',
534: $lastdate,$date);
535: }
536: }
537: if ($status eq 'CAN_ANSWER' ||
538: (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
539: #check #tries, and if correct.
540: my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
541: my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries",$symb);
542: if ( $tries eq '' ) { $tries = '0'; }
543: if ( $maxtries eq '' &&
544: $env{'request.state'} ne 'construct') { $maxtries = '2'; }
545: if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
546: # if (correct and show prob status) or excused then CANNOT_ANSWER
547: if ( ($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/)
548: && (&show_problem_status()) ) {
549: if (($Apache::lonhomework::history{"resource.$id.awarded"} >= 1) ||
550: (&Apache::lonnet::EXT("resource.$id.retrypartial",$symb) !~/^1|on|yes$/i)) {
551: $status = 'CANNOT_ANSWER';
552: }
553: } elsif ($Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
554: $status = 'CANNOT_ANSWER';
555: }
556: if ($status eq 'CANNOT_ANSWER'
557: && &show_answer_problem_status()) {
558: $status = 'SHOW_ANSWER';
559: }
560: }
561: if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
562: my @interval=&Apache::lonnet::EXT("resource.$id.interval",$symb);
563: &Apache::lonxml::debug("looking for interval @interval");
564: if ($interval[0]) {
565: my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
566: &Apache::lonxml::debug("looking for accesstime $first_access");
567: if (!$first_access) {
568: $status='NOT_YET_VIEWED';
569: my $due_date = &due_date($id,$symb);
570: my $seconds_left = $due_date - time;
571: if ($seconds_left > $interval[0] || $due_date eq '') {
572: $seconds_left = $interval[0];
573: }
574: $datemsg=&seconds_to_human_length($seconds_left);
575: }
576: }
577: }
578:
579: #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
580: # (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
581: # return ('UNCHECKEDOUT','needs to be checked out');
582: #}
583:
584: &Apache::lonxml::debug("sending back :$status:$datemsg:");
585: if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
586: &Apache::lonxml::debug("should be allowed to browse a resource when closed");
587: $status='CAN_ANSWER';
588: $datemsg=&mt('is closed but you are allowed to view it');
589: }
590:
591: return ($status,$datemsg);
592: }
593: # this should work exactly like the copy in lonnavmaps.pm
594: sub due_date {
595: my ($part_id,$symb,$udom,$uname)=@_;
596: my $date;
597: my @interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
598: $udom,$uname);
599: &Apache::lonxml::debug("looking for interval $part_id $symb @interval");
600: my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
601: $udom,$uname);
602: &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
603: if ($interval[0] =~ /\d+/) {
604: my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
605: &Apache::lonxml::debug("looking for first_access $first_access ($interval[1])");
606: if (defined($first_access)) {
607: my $interval = $first_access+$interval[0];
608: $date = (!$due_date || $interval < $due_date) ? $interval
609: : $due_date;
610: } else {
611: $date = $due_date;
612: }
613: } else {
614: $date = $due_date;
615: }
616: return $date;
617: }
618:
619: sub seconds_to_human_length {
620: my ($length)=@_;
621:
622: my $seconds=$length%60; $length=int($length/60);
623: my $minutes=$length%60; $length=int($length/60);
624: my $hours=$length%24; $length=int($length/24);
625: my $days=$length;
626:
627: my $timestr;
628: if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
629: if ($hours > 0) { $timestr.=($timestr?", ":"").
630: &mt('[quant,_1,hour]',$hours); }
631: if ($minutes > 0) { $timestr.=($timestr?", ":"").
632: &mt('[quant,_1,minute]',$minutes); }
633: if ($seconds > 0) { $timestr.=($timestr?", ":"").
634: &mt('[quant,_1,second]',$seconds); }
635: return $timestr;
636: }
637:
638: sub showhash {
639: my (%hash) = @_;
640: &showhashsubset(\%hash,'.');
641: return '';
642: }
643:
644: sub showarray {
645: my ($array)=@_;
646: my $string="(";
647: foreach my $elm (@{ $array }) {
648: if (ref($elm) eq 'ARRAY') {
649: $string.=&showarray($elm);
650: } elsif (ref($elm) eq 'HASH') {
651: $string.= "HASH --- \n<br />";
652: $string.= &showhashsubset($elm,'.');
653: } else {
654: $string.="$elm,"
655: }
656: }
657: chop($string);
658: $string.=")";
659: return $string;
660: }
661:
662: sub showhashsubset {
663: my ($hash,$keyre) = @_;
664: my $resultkey;
665: foreach $resultkey (sort(keys(%$hash))) {
666: if ($resultkey !~ /$keyre/) { next; }
667: if (ref($$hash{$resultkey}) eq 'ARRAY' ) {
668: &Apache::lonxml::debug("$resultkey ---- ".
669: &showarray($$hash{$resultkey}));
670: } elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
671: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
672: &showhashsubset($$hash{$resultkey},'.');
673: } else {
674: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
675: }
676: }
677: &Apache::lonxml::debug("\n<br />restored values^</br>\n");
678: return '';
679: }
680:
681: sub setuppermissions {
682: $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
683: unless ($Apache::lonhomework::browse eq 'F') {
684: $Apache::lonhomework::browse=&Apache::lonnet::allowed('bro',$env{'request.filename'});
685: }
686: my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
687: if (! $viewgrades &&
688: exists($env{'request.course.sec'}) &&
689: $env{'request.course.sec'} !~ /^\s*$/) {
690: $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
691: '/'.$env{'request.course.sec'});
692: }
693: $Apache::lonhomework::viewgrades = $viewgrades;
694:
695: if ($Apache::lonhomework::browse eq 'F' &&
696: $env{'form.devalidatecourseresdata'} eq 'on') {
697: my (undef,$courseid) = &Apache::lonnet::whichuser();
698: &Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
699: $env{"course.$courseid.domain"});
700: }
701:
702: my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
703: if (! $modifygrades &&
704: exists($env{'request.course.sec'}) &&
705: $env{'request.course.sec'} !~ /^\s*$/) {
706: $modifygrades =
707: &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
708: '/'.$env{'request.course.sec'});
709: }
710: $Apache::lonhomework::modifygrades = $modifygrades;
711:
712: my $queuegrade = &Apache::lonnet::allowed('mqg',$env{'request.course.id'});
713: if (! $queuegrade &&
714: exists($env{'request.course.sec'}) &&
715: $env{'request.course.sec'} !~ /^\s*$/) {
716: $queuegrade =
717: &Apache::lonnet::allowed('qgr',$env{'request.course.id'}.
718: '/'.$env{'request.course.sec'});
719: }
720: $Apache::lonhomework::queuegrade = $queuegrade;
721: return '';
722: }
723:
724: sub unset_permissions {
725: undef($Apache::lonhomework::queuegrade);
726: undef($Apache::lonhomework::modifygrades);
727: undef($Apache::lonhomework::viewgrades);
728: undef($Apache::lonhomework::browse);
729: }
730:
731: sub setupheader {
732: my $request=$_[0];
733: &Apache::loncommon::content_type($request,'text/html');
734: if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
735: &Apache::loncommon::no_cache($request);
736: }
737: # $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
738: # 'lastrevisiondate'));
739: $request->send_http_header;
740: return OK if $request->header_only;
741: return ''
742: }
743:
744: sub handle_save_or_undo {
745: my ($request,$problem,$result,$getobjref) = @_;
746:
747: my $file = &Apache::lonnet::filelocation("",$request->uri);
748: my $filebak =$file.".bak";
749: my $filetmp =$file.".tmp";
750: my $error=0;
751: if (($env{'form.problemmode'} eq 'undo') || ($env{'form.problemmode'} eq 'undoxml')) {
752: my $error=0;
753: if (!&File::Copy::copy($file,$filetmp)) { $error=1; }
754: if ((!$error) && (!&File::Copy::copy($filebak,$file))) { $error=1; }
755: if ((!$error) && (!&File::Copy::move($filetmp,$filebak))) { $error=1; }
756: if (!$error) {
757: &Apache::lonxml::info("<p><b>".
758: &mt("Undid changes, Switched [_1] and [_2]",
759: '<span class="LC_filename">'.$filebak.
760: '</span>',
761: '<span class="LC_filename">'.$file.
762: '</span>')."</b></p>");
763: } else {
764: &Apache::lonxml::info("<p><span class=\"LC_error\">".
765: &mt("Unable to undo, unable to switch [_1] and [_2]",
766: '<span class="LC_filename">'.
767: $filebak.'</span>',
768: '<span class="LC_filename">'.
769: $file.'</span>')."</span></p>");
770: $error=1;
771: }
772: } else {
773: &Apache::lonnet::correct_line_ends($result);
774:
775: my $fs=Apache::File->new(">$filebak");
776: if (defined($fs)) {
777: print $fs $$problem;
778: } else {
779: &Apache::lonxml::info("<span class=\"LC_error\">".
780: &mt("Unable to make backup [_1]",
781: '<span class="LC_filename">'.
782: $filebak.'</span>')."</span>");
783: $error=2;
784: }
785: my $fh=Apache::File->new(">$file");
786: if (defined($fh)) {
787: print $fh $$result;
788: if (ref($getobjref) eq 'SCALAR') {
789: if ($file =~ m{([^/]+)\.(html?)$}) {
790: my $fname = $1;
791: my $ext = $2;
792: my $path = $file;
793: $path =~ s/\Q$fname\E\.\Q$ext\E$//;
794: my (%allfiles,%codebase);
795: &Apache::lonnet::extract_embedded_items($file,\%allfiles,
796: \%codebase,$result);
797: if (keys(%allfiles) > 0) {
798: my $url = $request->uri;
799: my $state = <<STATE;
800: <input type="hidden" name="action" value="upload_embedded" />
801: <input type="hidden" name="url" value="$url" />
802: STATE
803: $$getobjref = "<h3>".&mt("Reference Warning")."</h3>".
804: "<p>".&mt("Completed upload of the file. This file contained references to other files.")."</p>".
805: "<p>".&mt("Please select the locations from which the referenced files are to be uploaded.")."</p>".
806: &Apache::loncommon::ask_for_embedded_content($url,$state,\%allfiles,\%codebase,
807: {'error_on_invalid_names' => 1,
808: 'ignore_remote_references' => 1,});
809: }
810: }
811: }
812: } else {
813: &Apache::lonxml::info('<span class="LC_error">'.
814: &mt("Unable to write to [_1]",
815: '<span class="LC_filename">'.
816: $file.'</span>').
817: '</span>');
818: $error|=4;
819: }
820: }
821: return $error;
822: }
823:
824: sub analyze_header {
825: my ($request) = @_;
826: my $js = &Apache::structuretags::setmode_javascript();
827:
828: # Breadcrumbs
829: my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
830: 'text' => 'Authoring Space'},
831: {'href' => '',
832: 'text' => 'Problem Testing'},
833: {'href' => '',
834: 'text' => 'Analyzing a problem'}];
835:
836: my $result =
837: &Apache::loncommon::start_page('Analyzing a problem',
838: $js,
839: {'bread_crumbs' => $brcrum,})
840: .&Apache::loncommon::head_subbox(
841: &Apache::loncommon::CSTR_pageheader());
842: $result .=
843: '<form name="lonhomework" method="post" action="'.
844: &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
845: '<input type="hidden" name="problemmode" value="'.
846: $env{'form.problemmode'}.'" />'.
847: &Apache::structuretags::remember_problem_state().'
848: <div class="LC_edit_problem_analyze_header">
849: <input type="button" name="submitmode" value="'.&mt("EditXML").'" '.
850: 'onclick="javascript:setmode(this.form,'."'editxml'".')" />
851: <input type="button" name="submitmode" value="'.&mt('Edit').'" '.
852: 'onclick="javascript:setmode(this.form,'."'edit'".')" />
853: <hr />
854: <input type="button" name="submitmode" value="'.&mt("View").'" '.
855: 'onclick="javascript:setmode(this.form,'."'view'".')" />
856: <hr />
857: </div>'
858: .&Apache::lonxml::message_location().
859: '</form>';
860: &Apache::lonxml::add_messages(\$result);
861: $request->print($result);
862: $request->rflush();
863: }
864:
865: sub analyze_footer {
866: my ($request) = @_;
867: $request->print(&Apache::loncommon::end_page());
868: $request->rflush();
869: }
870:
871: sub analyze {
872: my ($request,$file) = @_;
873: &Apache::lonxml::debug("Analyze");
874: my $result;
875: my %overall;
876: my %seedexample;
877: my %allparts;
878: my $rndseed=$env{'form.rndseed'};
879: &analyze_header($request);
880: my %prog_state=
881: &Apache::lonhtmlcommon::Create_PrgWin($request,$env{'form.numtoanalyze'});
882: for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
883: &Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last problem');
884: if (&Apache::loncommon::connection_aborted($request)) { return; }
885: my $thisseed=$i+$rndseed;
886: my $subresult=&Apache::lonnet::ssi($request->uri,
887: ('grade_target' => 'analyze'),
888: ('rndseed' => $thisseed));
889: (my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
890: my %analyze=&Apache::lonnet::str2hash($subresult);
891: my @parts;
892: if (ref($analyze{'parts'}) eq 'ARRAY') {
893: @parts=@{ $analyze{'parts'} };
894: }
895: foreach my $part (@parts) {
896: if (!exists($allparts{$part})) {$allparts{$part}=1;};
897: if ($analyze{$part.'.type'} eq 'numericalresponse' ||
898: $analyze{$part.'.type'} eq 'stringresponse' ||
899: $analyze{$part.'.type'} eq 'formularesponse' ) {
900: foreach my $name (keys(%{ $analyze{$part.'.answer'} })) {
901: my $i=0;
902: foreach my $answer_part (@{ $analyze{$part.'.answer'}{$name} }) {
903: push( @{ $overall{$part.'.answer'}[$i] },
904: $answer_part);
905: my $concatanswer= join("\0",@{ $answer_part });
906: if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
907: $answer_part = ['<span class="LC_error">'.&mt('Error').'</span>'];
908: }
909: $seedexample{join("\0",$part,$i,@{$answer_part})}=
910: $thisseed;
911: $i++;
912: }
913: }
914: if (!keys(%{ $analyze{$part.'.answer'} })) {
915: my $answer_part =
916: ['<span class="LC_error">'.&mt('Error').'</span>'];
917: $seedexample{join("\0",$part,0,@{$answer_part})}=
918: $thisseed;
919: push( @{ $overall{$part.'.answer'}[0] },
920: $answer_part);
921: }
922: }
923: }
924: }
925: &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,&mt('Analyzing Results'));
926: $request->print('<hr />'
927: .'<h3>'
928: .&mt('List of possible answers')
929: .'</h3>'
930: );
931: foreach my $part (sort(keys(%allparts))) {
932: if ((ref($overall{$part.'.answer'}) eq 'ARRAY') &&
933: (@{$overall{$part.'.answer'}} > 0)) {
934: for (my $i=0;$i<scalar(@{ $overall{$part.'.answer'} });$i++) {
935: my $num_cols=scalar(@{ $overall{$part.'.answer'}[$i][0] });
936: $request->print(&Apache::loncommon::start_data_table()
937: .&Apache::loncommon::start_data_table_header_row()
938: .'<th colspan="'.($num_cols+1).'">'
939: .&mt('Part').' '.$part
940: );
941: if (scalar(@{ $overall{$part.'.answer'} }) > 1) {
942: $request->print(' '.&mt('Answer [_1]',$i+1));
943: }
944: $request->print('</th>'
945: .&Apache::loncommon::end_data_table_header_row()
946: );
947: my %frequency;
948: foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'}[$i] })) {
949: $frequency{join("\0",@{ $answer })}++;
950: }
951: $request->print(&Apache::loncommon::start_data_table_header_row()
952: .'<th colspan="'.($num_cols).'">'.&mt('Answer').'</th>'
953: .'<th>'.&mt('Frequency').'<br />'
954: .'('.&mt('click for example').')</th>'
955: .&Apache::loncommon::end_data_table_header_row()
956: );
957: foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
958: $request->print(&Apache::loncommon::start_data_table_row()
959: .'<td>'
960: .join('</td><td>',split("\0",$answer))
961: .'</td>'
962: .'<td>'
963: .'<a href="'.$request->uri.'?rndseed='.$seedexample{join("\0",$part,$i,$answer)}.'">'.$frequency{$answer}.'</a>'
964: .'</td>'
965: .&Apache::loncommon::end_data_table_row()
966: );
967: }
968: $request->print(&Apache::loncommon::end_data_table());
969: }
970: } else {
971: $request->print('<p class="LC_warning">'
972: .&mt('Response [_1] is not analyzable at this time.',$part)
973: .'</p>'
974: );
975: }
976: }
977: if (scalar(keys(%allparts)) == 0 ) {
978: $request->print('<p class="LC_warning">'
979: .&mt('Found no analyzable responses in this problem.'
980: .' Currently only Numerical, Formula and String response styles are supported.')
981: .'</p>'
982: );
983: }
984: &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
985: &analyze_footer($request);
986: &Apache::lonhomework::showhash(%overall);
987: return $result;
988: }
989:
990: {
991: my $show_problem_status;
992: sub reset_show_problem_status {
993: undef($show_problem_status);
994: }
995:
996: sub set_show_problem_status {
997: my ($new_status) = @_;
998: $show_problem_status = lc($new_status);
999: }
1000:
1001: sub hide_problem_status {
1002: return ($show_problem_status eq 'no'
1003: || $show_problem_status eq 'no_feedback_ever');
1004: }
1005:
1006: sub show_problem_status {
1007: return ($show_problem_status eq 'yes'
1008: || $show_problem_status eq 'answer'
1009: || $show_problem_status eq '');
1010: }
1011:
1012: sub show_some_problem_status {
1013: return ($show_problem_status eq 'no');
1014: }
1015:
1016: sub show_no_problem_status {
1017: return ($show_problem_status eq 'no_feedback_ever');
1018: }
1019:
1020: sub show_answer_problem_status {
1021: return ($show_problem_status eq 'answer');
1022: }
1023: }
1024:
1025: sub editxmlmode {
1026: my ($request,$file) = @_;
1027: my $result;
1028: my $problem=&Apache::lonnet::getfile($file);
1029: if ($problem eq -1) {
1030: &Apache::lonxml::error(
1031: '<p class="LC_error">'
1032: .&mt('Unable to find [_1]',
1033: '<span class="LC_filename">'.$file.'</span>')
1034: .'</p>');
1035:
1036: $problem='';
1037: }
1038: if (($env{'form.problemmode'} eq 'saveeditxml') ||
1039: ($env{'form.problemmode'} eq 'saveviewxml') ||
1040: ($env{'form.problemmode'} eq 'undoxml')) {
1041: my $error=&handle_save_or_undo($request,\$problem,
1042: \$env{'form.editxmltext'});
1043: if (!$error) { $problem=&Apache::lonnet::getfile($file); }
1044: }
1045: &Apache::lonhomework::showhashsubset(\%env,'^form');
1046: if ($env{'form.problemmode'} eq 'saveviewxml') {
1047: &Apache::lonhomework::showhashsubset(\%env,'^form');
1048: $env{'form.problemmode'}='view';
1049: &renderpage($request,$file);
1050: } else {
1051: my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
1052: if ($cols > 80) { $cols = 80; }
1053: if ($cols < 70) { $cols = 70; }
1054: if ($rows < 20) { $rows = 20; }
1055: my $js =
1056: &Apache::edit::js_change_detection().
1057: &Apache::loncommon::resize_textarea_js().
1058: &Apache::structuretags::setmode_javascript().
1059: &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
1060:
1061: # Breadcrumbs
1062: my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1063: 'text' => 'Authoring Space'},
1064: {'href' => '',
1065: 'text' => 'Problem Editing'}];
1066:
1067: my $start_page =
1068: &Apache::loncommon::start_page(&mt("EditXML [_1]",$file),$js,
1069: {'no_auto_mt_title' => 1,
1070: 'only_body' => 0,
1071: 'add_entries' => {
1072: 'onresize' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
1073: 'onload' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
1074: },
1075: 'bread_crumbs' => $brcrum,
1076: });
1077:
1078: $result=$start_page
1079: .&Apache::loncommon::head_subbox(
1080: &Apache::loncommon::CSTR_pageheader());
1081: $result.=&renderpage($request,$file,['no_output_web'],1).
1082: '<form '.&Apache::edit::form_change_detection().' name="lonhomework" method="post" action="'.
1083: &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
1084: &Apache::structuretags::remember_problem_state().'
1085: <div class="LC_edit_problem_header">
1086: <div class="LC_edit_problem_header_title">'.
1087: &mt('Problem Editing').' '.&Apache::loncommon::help_open_topic('Problem_Editor_XML_Index').
1088: '</div><div class="LC_edit_actionbar" id="actionbar">';
1089:
1090: $result.='<input type="hidden" name="problemmode" value="saveedit" />'.
1091: &Apache::structuretags::problem_edit_buttons('editxml');
1092: $result.='<div>';
1093:
1094: $result .= '<ol class="LC_primary_menu" style="display:inline-block;font-size:90%;vertical-align:middle;">';
1095:
1096: unless ($env{'environment.nocodemirror'}) {
1097: # dropdown menus
1098: $result .= Apache::lonmenu::create_submenu("#", "",
1099: &mt("Problem Templates"), template_dropdown_datastructure());
1100:
1101: $result .= Apache::lonmenu::create_submenu("#", "",
1102: &mt("Response Types"), responseblock_dropdown_datastructure());
1103:
1104: $result .= Apache::lonmenu::create_submenu("#", "",
1105: &mt("Conditional Blocks"), conditional_scripting_datastructure());
1106:
1107: $result .= Apache::lonmenu::create_submenu("#", "",
1108: &mt("Miscellaneous"), misc_datastructure());
1109: }
1110:
1111: $result .= Apache::lonmenu::create_submenu("#", "",
1112: &mt("Help") . ' <img src="/adm/help/help.png" alt="' . &mt("Help") .
1113: '" style="vertical-align:text-bottom; height: auto; margin:0; "/>',
1114: helpmenu_datastructure(),"");
1115:
1116: $result.="</ol></div>";
1117:
1118: $result .= '</div></div>' .
1119: &Apache::lonxml::message_location() .
1120: &Apache::loncommon::xmleditor_js() .
1121: '<textarea ' . &Apache::edit::element_change_detection() .
1122: ' rows="'.$rows.'" cols="'.$cols.'" style="width:100%" ' .
1123: ' name="editxmltext" id="LC_editxmltext">' .
1124: &HTML::Entities::encode($problem,'<>&"') .
1125: '</textarea> <div id="LC_aftertextarea"> </div> </form>';
1126:
1127: my $resource = $env{'request.ambiguous'};
1128: unless($env{'environment.nocodemirror'}){
1129: $result .= '<link rel="stylesheet" href="/adm/codemirror/codemirror-combined-xml.css">
1130: <script src="/adm/codemirror/codemirror-compressed-xml.js"></script>
1131: <script>
1132: CodeMirror.defineMode("mixedmode", function(config) {
1133: return CodeMirror.multiplexingMode(
1134: CodeMirror.getMode(config, "xml"),
1135: {
1136: open: "\<script type=\"loncapa/perl\"\>", close: "\</script\>",
1137: mode: CodeMirror.getMode(config, "perl"),
1138: delimStyle: "tag",
1139: }
1140: );
1141: });
1142: var cm = CodeMirror.fromTextArea(document.getElementById("LC_editxmltext"),
1143: {
1144: mode: "mixedmode",
1145: lineWrapping: true,
1146: lineNumbers: true,
1147: tabSize: 4,
1148: indentUnit: 4,
1149:
1150: autoCloseTags: true,
1151: autoCloseBrackets: true,
1152: height: "auto",
1153: styleActiveLine: true,
1154:
1155: extraKeys: {
1156: "Tab": "indentMore",
1157: "Shift-Tab": "indentLess",
1158: }
1159: });
1160: restoreScrollPosition("'.$resource.'");
1161: </script>';
1162: }
1163:
1164: $result .= &Apache::loncommon::end_page();
1165: &Apache::lonxml::add_messages(\$result);
1166: $request->print($result);
1167: }
1168: return '';
1169: }
1170:
1171: #
1172: # Render the page in whatever target desired.
1173: #
1174: sub renderpage {
1175: my ($request,$file,$targets,$return_string) = @_;
1176:
1177: my @targets = @{$targets || [&get_target()]};
1178: &Apache::lonhomework::showhashsubset(\%env,'form.');
1179: &Apache::lonxml::debug("Running targets ".join(':',@targets));
1180:
1181: my $overall_result;
1182: foreach my $target (@targets) {
1183: # FIXME need to do something intelligent when a problem goes
1184: # from viewable to not viewable due to map conditions
1185: #&setuppermissions();
1186: #if ( $Apache::lonhomework::browse ne '2'
1187: # && $Apache::lonhomework::browse ne 'F' ) {
1188: # $request->print(" You most likely shouldn't see me.");
1189: #}
1190: #my $t0 = [&gettimeofday()];
1191: my $output=1;
1192: if ($target eq 'no_output_web') {
1193: $target = 'web'; $output=0;
1194: }
1195: my $problem=&Apache::lonnet::getfile($file);
1196: my $result;
1197: if ($problem eq -1) {
1198: $problem='';
1199: my $filename=(split('/',$file))[-1];
1200: my $error =
1201: '<p class="LC_error">'
1202: .&mt('Unable to find [_1]',
1203: '<span class="LC_filename">'.$filename.'</span>')
1204: ."</p>";
1205: $result.=
1206: &Apache::loncommon::simple_error_page($request,'Not available',
1207: $error,{'no_auto_mt_msg' => 1});
1208: return;
1209: }
1210:
1211: my %mystyle;
1212: if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
1213: if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
1214: if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
1215:
1216: &Apache::lonxml::debug("Should be parsing now");
1217: $result .= &Apache::lonxml::xmlparse($request, $target, $problem,
1218: &setup_vars($target),%mystyle);
1219: &finished_parsing();
1220: if (!$output) { $result = ''; }
1221: #$request->print("Result follows:");
1222: if ($target eq 'modified') {
1223: &handle_save_or_undo($request,\$problem,\$result);
1224: } else {
1225: if ($target eq 'analyze') {
1226: $result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
1227: undef(%Apache::lonhomework::analyze);
1228: }
1229: #my $td=&tv_interval($t0);
1230: #if ( $Apache::lonxml::debug) {
1231: #$result =~ s:</body>::;
1232: #$result.="<br />Spent $td seconds processing target $target\n</body>";
1233: #}
1234: # $request->print($result);
1235: $overall_result.=$result;
1236: # $request->rflush();
1237: }
1238: #$request->print(":Result ends");
1239: #my $td=&tv_interval($t0);
1240: }
1241: if (!$return_string) {
1242: &Apache::lonxml::add_messages(\$overall_result);
1243: $request->print($overall_result);
1244: $request->rflush();
1245: } else {
1246: return $overall_result;
1247: }
1248: }
1249:
1250: sub finished_parsing {
1251: undef($Apache::lonhomework::parsing_a_problem);
1252: undef($Apache::lonhomework::parsing_a_task);
1253: }
1254:
1255: # function extracted from get_template_html
1256: # returns "key" -> list
1257: # key: path of template
1258: # value 1: title
1259: # value 2: category
1260: # value 3: name of help topic ???
1261: sub get_template_list{
1262: my ($extension) = @_;
1263:
1264: my @files = glob($Apache::lonnet::perlvar{'lonIncludes'}.
1265: '/templates/*.'.$extension);
1266: @files = map {[$_,&mt(&Apache::lonnet::metadata($_, 'title')),
1267: (&Apache::lonnet::metadata($_, 'category')?&mt(&Apache::lonnet::metadata($_, 'category')):&mt('Miscellaneous')),
1268: &mt(&Apache::lonnet::metadata($_, 'help'))]} (@files);
1269: @files = sort {$a->[2].$a->[1] cmp $b->[2].$b->[1]} (@files);
1270: return @files;
1271: }
1272:
1273: sub get_template_html {
1274: my ($extension) = @_;
1275: my $result;
1276: my @allnames;
1277: &Apache::lonxml::debug("Looking for :$extension:");
1278: my $glob_extension = $extension;
1279: if ($extension eq 'survey' || $extension eq 'exam') {
1280: $glob_extension = 'problem';
1281: }
1282: my @files = &get_template_list($extension);
1283: my ($midpoint,$seconddiv,$numfiles);
1284: my @noexamplelink = ('blank.problem','blank.library','script.library');
1285: $numfiles = 0;
1286: foreach my $file (@files) {
1287: next if ($file->[1] !~ /\S/);
1288: $numfiles ++;
1289: }
1290: if ($numfiles > 0) {
1291: $result = '<div class="LC_left_float">';
1292: $midpoint = int($numfiles/2);
1293: if ($numfiles%2) {
1294: $midpoint ++;
1295: }
1296: }
1297: my $count = 0;
1298: my $currentcategory='';
1299: my $first = 1;
1300: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1301: foreach my $file (@files) {
1302: next if ($file->[1] !~ /\S/);
1303: if ($file->[2] ne $currentcategory) {
1304: $currentcategory=$file->[2];
1305: if ((!$seconddiv) && ($count >= $midpoint)) {
1306: $result .= '</div></div>'."\n".'<div class="LC_left_float">'."\n";
1307: $seconddiv = 1;
1308: } elsif (!$first) {
1309: $result.='</div>'."\n";
1310: } else {
1311: $first = 0;
1312: }
1313: $result.= '<div class="LC_Box">'."\n"
1314: .'<h3 class="LC_hcell">'.$currentcategory.'</h3>'."\n";
1315: $count++;
1316: }
1317: $result .=
1318: '<label><input type="radio" name="template" value="'.$file->[0].'" />'.
1319: $file->[1].'</label>';
1320: if ($file->[3]) {
1321: $result.=&Apache::loncommon::help_open_topic($file->[3]);
1322: }
1323: # Provide example link
1324: my $filename=$file->[0];
1325: $filename=~s{^\Q$londocroot\E}{};
1326: if (!(grep($filename =~ /\Q$_\E$/,@noexamplelink))) {
1327: $result .= ' <span class="LC_fontsize_small">'
1328: .&Apache::loncommon::modal_link(
1329: $filename.'?inhibitmenu=yes',&mt('Example'),600,420,'sample')
1330: .'</span>';
1331: }
1332: $result .= '<br />'."\n";
1333: $count ++;
1334: }
1335: if ($numfiles > 0) {
1336: $result .= '</div></div>'."\n".'<div class="LC_clear_float_footer"></div>'."\n";
1337: }
1338: return $result;
1339: }
1340:
1341: sub newproblem {
1342: my ($request) = @_;
1343:
1344: if ($env{'form.mode'} eq 'blank'){
1345: my $dest = &Apache::lonnet::filelocation("",$request->uri);
1346: &File::Copy::copy('/home/httpd/html/res/adm/includes/templates/blank.problem',$dest);
1347: &renderpage($request,$dest);
1348: return;
1349: }
1350: if ($env{'form.template'}) {
1351: my $file = $env{'form.template'};
1352: my $dest = &Apache::lonnet::filelocation("",$request->uri);
1353: &File::Copy::copy($file,$dest);
1354: &renderpage($request,$dest);
1355: return;
1356: }
1357:
1358: my ($extension) = ($request->uri =~ m/\.(\w+)$/);
1359: &Apache::lonxml::debug("Looking for :$extension:");
1360: my $templatelist=&get_template_html($extension);
1361: if ($env{'form.newfile'} && !$templatelist) {
1362: # no templates found
1363: my $templatefilename =
1364: $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
1365: &Apache::lonxml::debug("$templatefilename");
1366: my $dest = &Apache::lonnet::filelocation("",$request->uri);
1367: &File::Copy::copy($templatefilename,$dest);
1368: &renderpage($request,$dest);
1369: } else {
1370: my $url=&HTML::Entities::encode($request->uri,'<>&"');
1371: my $dest = &Apache::lonnet::filelocation("",$request->uri);
1372: my $errormsg;
1373: my $instructions;
1374: my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1375: 'text' => 'Authoring Space'},
1376: {'href' => '',
1377: 'text' => "Create New $extension"}];
1378: my $start_page =
1379: &Apache::loncommon::start_page("Create New $extension",
1380: undef,
1381: {'bread_crumbs' => $brcrum,});
1382: $request->print(
1383: $start_page
1384: .&Apache::loncommon::head_subbox(
1385: &Apache::loncommon::CSTR_pageheader())
1386: .'<h1>'.&mt("Creating a new $extension resource.")."</h1>
1387: $errormsg
1388: ".&mt("The requested file [_1] currently does not exist.",
1389: '<span class="LC_filename">'.$url.'</span>').'
1390: <p class="LC_info">
1391: '.&mt("To create a new $extension, select a template from the".
1392: " list below. Then click on the \"Create $extension\" button.").'
1393: </p><div><form action="'.$url.'" method="post">');
1394:
1395: if (defined($templatelist)) {
1396: $request->print($templatelist);
1397: }
1398: $request->print('<br /><input type="submit" name="newfile" value="'.
1399: &mt("Create $extension").'" />');
1400: $request->print('</form></div>'.&Apache::loncommon::end_page());
1401: }
1402: return;
1403: }
1404:
1405: sub update_construct_style {
1406: if ($env{'request.state'} eq "construct"
1407: && $env{'form.problemmode'} eq 'view'
1408: && defined($env{'form.submitted'})
1409: && !defined($env{'form.resetdata'})
1410: && !defined($env{'form.newrandomization'})) {
1411: if ((!$env{'form.style_file'} && $env{'construct.style'})
1412: ||$env{'form.clear_style_file'}) {
1413: &Apache::lonnet::delenv('construct.style');
1414: } elsif ($env{'form.style_file'}
1415: && $env{'construct.style'} ne $env{'form.style_file'}) {
1416: &Apache::lonnet::appenv({'construct.style' =>
1417: $env{'form.style_file'}});
1418: }
1419: }
1420: }
1421:
1422: #
1423: # Sets interval for current user so time left will be zero, either for the entire folder
1424: # containing the current resource, or just the resource, depending on value of first item
1425: # in interval array retrieved from EXT("resource.0.interval");
1426: #
1427: sub zero_timer {
1428: my ($symb) = @_;
1429: my ($hastimeleft,$first_access,$now);
1430: my @interval=&Apache::lonnet::EXT("resource.0.interval",$symb);
1431: if (@interval > 1) {
1432: if ($interval[1] eq 'course') {
1433: return;
1434: } else {
1435: my $now = time;
1436: my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
1437: if ($first_access > 0) {
1438: my ($timelimit) = split(/_/,$interval[0]);
1439: if ($first_access+$timelimit > $now) {
1440: my $done_time = $now - $first_access;
1441: my $snum = 1;
1442: if ($interval[1] eq 'map') {
1443: $snum = 2;
1444: }
1445: my $result =
1446: &Apache::lonparmset::storeparm_by_symb_inner($symb,'0_interval',
1447: $snum,$done_time,
1448: 'date_interval',
1449: $env{'user.name'},
1450: $env{'user.domain'});
1451: return $result;
1452: }
1453: }
1454: }
1455: }
1456: return;
1457: }
1458:
1459: sub handler {
1460: #my $t0 = [&gettimeofday()];
1461: my $request=$_[0];
1462:
1463: $Apache::lonxml::request=$request;
1464: $Apache::lonxml::debug=$env{'user.debug'};
1465: $env{'request.uri'}=$request->uri;
1466: &setuppermissions();
1467:
1468: my $file=&Apache::lonnet::filelocation("",$request->uri);
1469:
1470: #check if we know where we are
1471: if ($env{'request.course.fn'} && !&Apache::lonnet::symbread('','',1,1)) {
1472: # if we are browsing we might not be able to know where we are
1473: if ($Apache::lonhomework::browse ne 'F' &&
1474: $env{'request.state'} ne "construct") {
1475: #should know where we are, so ask
1476: &unset_permissions();
1477: $request->internal_redirect('/adm/ambiguous');
1478: return OK;
1479: }
1480: }
1481: if (&setupheader($request)) {
1482: &unset_permissions();
1483: return OK;
1484: }
1485:
1486: &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
1487: &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
1488: my ($symb) = &Apache::lonnet::whichuser();
1489: &Apache::lonxml::debug('symb is '.$symb);
1490: if ($env{'request.state'} eq "construct") {
1491: if ( -e $file ) {
1492: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1493: ['problemmode']);
1494: if (!(defined $env{'form.problemmode'})) {
1495: #first visit to problem in construction space
1496: $env{'form.problemmode'}= 'view';
1497: &renderpage($request,$file);
1498: } elsif (($env{'form.problemmode'} eq 'editxml') ||
1499: ($env{'form.problemmode'} eq 'saveeditxml') ||
1500: ($env{'form.problemmode'} eq 'saveviewxml') ||
1501: ($env{'form.problemmode'} eq 'undoxml')) {
1502: &editxmlmode($request,$file);
1503: } elsif ($env{'form.problemmode'} eq 'calcanswers') {
1504: &analyze($request,$file);
1505: } else {
1506: &update_construct_style();
1507: &renderpage($request,$file);
1508: }
1509: } else {
1510: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1511: ['mode']);
1512: # requested file doesn't exist in contruction space
1513: &newproblem($request);
1514: }
1515: } else {
1516: # Set the event timer to zero if the "done button" was clicked. The button is
1517: # part of the doneButton form created in lonmenu.pm
1518: if ($symb && $env{'form.LC_interval_done'} eq 'true') {
1519: &zero_timer($symb);
1520: undef($env{'form.LC_interval_done'});
1521: }
1522: # just render the page normally outside of construction space
1523: &Apache::lonxml::debug("not construct");
1524: &renderpage($request,$file);
1525: }
1526: #my $td=&tv_interval($t0);
1527: #&Apache::lonxml::debug("Spent $td seconds processing");
1528: # always turn off debug messages
1529: $Apache::lonxml::debug=0;
1530: &unset_permissions();
1531: return OK;
1532:
1533: }
1534:
1535: sub template_dropdown_datastructure {
1536: # gathering the all templates and their path, title, category and help topic
1537: my @templates = get_template_list('problem');
1538: # template category => title
1539: my %tmplthash = ();
1540: # template title => path
1541: my %tmpltcontent = ();
1542:
1543: foreach my $template (@templates){
1544: # put in hash if the template is not empty
1545: unless ($template->[1] eq ''){
1546: push(@{$tmplthash{$template->[2]}}, $template->[1]);
1547: push(@{$tmpltcontent{$template->[1]}},$template->[0]);
1548: }
1549: }
1550:
1551: my $catList = [];
1552: foreach my $cat (sort keys %tmplthash) {
1553: my $catItems = [];
1554: foreach my $title (sort @{$tmplthash{$cat}}) {
1555: my $path = $tmpltcontent{$title}->[0];
1556: my $code;
1557: open(FH, "<$path");
1558: while(<FH>){
1559: $code.= $_ unless $_ =~ /(<problem>)|(<\/problem>)/;
1560: }
1561: close(FH);
1562:
1563: if ($code ne '') {
1564: my $href = 'javascript:insertText(\'' . &convert_for_js(&HTML::Entities::encode($code,'<>&"')) . '\')';
1565: my $currItem = [$href, $title, undef];
1566: push @{$catItems}, $currItem;
1567: }
1568: }
1569: push @{$catList}, [$catItems, $cat, undef];
1570: }
1571:
1572: return $catList;
1573: }
1574:
1575: sub responseblock_dropdown_datastructure {
1576:
1577: my $mathCat = [
1578: [
1579: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_formularesponse())) . "\')", &mt("Formula Response"), undef],
1580: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_functionplotresponse())) . "\')", &mt("Function Plot Response"), undef],
1581: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_mathresponse())) . "\')", &mt("Math Response"), undef],
1582: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_numericalresponse())) . "\')", &mt("Numerical Response"), undef]
1583: ],
1584: &mt("Math"),
1585: undef
1586: ];
1587:
1588: my $miscCat = [
1589: [
1590: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_imageresponse())) . "\')", &mt("Click on Image"), undef],
1591: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_customresponse())) . "\')", &mt("Custom Response"), undef],
1592: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_externalresponse())) . "\')", &mt("External Response"), undef],
1593: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_matchresponse())) . "\')", &mt("Match Two Lists"), undef],
1594: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_radiobuttonresponse())) . "\')", &mt("One out of N statements"), undef],
1595: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_optionresponse())) . "\')", &mt("Select from Options"), undef],
1596: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_rankresponse())) . "\')", &mt("Rank Values"), undef]
1597: ],
1598: &mt("Miscellaneous"),
1599: undef
1600: ];
1601:
1602: my $chemCat = [
1603: [
1604: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_reactionresponse())) . "\')", &mt("Chemical Reaction"), undef],
1605: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_organicresponse())) . "\')", &mt("Organic Chemical Structure"), undef]
1606: ],
1607: &mt("Chemistry"),
1608: undef
1609: ];
1610:
1611: my $textCat = [
1612: [
1613: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_stringresponse())) . "\')", &mt("String Response"), undef],
1614: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_essayresponse())) . "\')", &mt("Essay"), undef]
1615: ],
1616: &mt("Text"),
1617: undef
1618: ];
1619:
1620: return [$mathCat, $miscCat, $chemCat, $textCat];
1621: }
1622:
1623:
1624: sub conditional_scripting_datastructure {
1625: # TODO: corresponding routines should be used for the javascript:insertText parts
1626: # instead of the placeholder routine default_xml_tag with the tags
1627: # e.g. &default_xml_tag("postanswerdate") should be replaced with a routine which
1628: # returns the corresponding content for this case
1629:
1630: #TODO translated is currently temporarily here, another solution should be found where the
1631: # needed string can be retrieved
1632:
1633: my $translatedTag = '
1634: <translated>
1635: <lang which="en"></lang>
1636: <lang which="default"></lang>
1637: </translated>';
1638: return [
1639: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode($translatedTag)) . "\')", &mt("Translated Block"), undef],
1640: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("block"))) . "\')", &mt("Conditional Block"), undef],
1641: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("postanswerdate"))) . "\')", &mt("After Answer Date Block"), undef],
1642: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("preduedate"))) . "\')", &mt("Before Due Date Block"), undef],
1643: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("solved"))) . "\')", &mt("Block For After Solved"), undef],
1644: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("notsolved"))) . "\')", &mt("Block For When Not Solved"), undef]
1645: ];
1646: }
1647:
1648: sub misc_datastructure {
1649: return [
1650: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_img())) . "\')", &mt("Image"), undef],
1651: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::lonplot::insert_gnuplot())) . "\')", &mt("GNU Plot"), undef],
1652: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_organicstructure())) . "\')", &mt("Organic Structure"), undef],
1653: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_script())) . "\')", &mt("Script Block"), undef],
1654: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("allow"))) . "\')", &mt("File Dependencies"), undef],
1655: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("import"))) . "\')", &mt("Import a File"), undef],
1656: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::londefdef::insert_meta())) . "\')", &mt("Custom Metadata"), undef],
1657: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("part"))) . "\')", &mt("Problem Part"), undef]
1658: ];
1659: }
1660:
1661: # helper routine for the datastructure building subroutines
1662: sub default_xml_tag {
1663: my ($tag) = @_;
1664: return "\n<$tag></$tag>";
1665: }
1666:
1667:
1668: sub helpmenu_datastructure {
1669:
1670: my $width = 500;
1671: my $height = 600;
1672:
1673: my $helpers = [
1674: ['Problem_LON-CAPA_Functions', &mt('Script Functions')],
1675: ['Greek_Symbols', &mt('Greek Symbols')],
1676: ['Other_Symbols', &mt('Other Symbols')],
1677: ['Authoring_Output_Tags', &mt('Output Tags')],
1678: ['Authoring_Multilingual_Problems',
1679: &mt('How to create problems in different languages')]
1680: ];
1681:
1682: my $help_structure = [];
1683:
1684: foreach my $count (0..(scalar(@{$helpers})-1)) {
1685: my $filename = $helpers->[$count]->[0];
1686: my $title = $helpers->[$count]->[1];
1687: my $href = &HTML::Entities::encode("javascript:openMyModal('/adm/help/$filename.hlp',$width,$height,'yes');");
1688: push @{$help_structure}, [$href, $title, undef];
1689: }
1690:
1691: return $help_structure;
1692: }
1693:
1694: # we need substitution to not break javascript code
1695: sub convert_for_js {
1696: my $return = shift;
1697: $return =~ s|script|ESCAPEDSCRIPT|g;
1698: $return =~ s|\\|\\\\|g;
1699: $return =~ s|\n|\\r\\n|g;
1700: $return =~ s|'|\\'|g;
1701: $return =~ s|'|\\'|g;
1702: return $return;
1703: }
1704:
1705: 1;
1706: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>