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