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