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