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