File:
[LON-CAPA] /
loncom /
interface /
lonhtmlcommon.pm
Revision
1.300:
download - view:
text,
annotated -
select for diffs
Tue Jan 3 00:28:29 2012 UTC (12 years, 7 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD,
BZ4492-merge,
BZ4492-feature_horizontal_radioresponse
- Bug 6450. Course personnel with vgr priv can view student's prior
versions of a Bridge Task (BT).
- bridgetask.pm
- generation of Show Slot list and Show Grading Status buttons moved
to new routine: &add_slotlist_button().
- "Show Slot list", "Show Grading Status", "Show a previously done version"
"Get a submission to grade", "Change reservation" buttons not shown
when course personnel display student's version of a BT.
- ensure tags have unique ids (replace duplicate LC_task_feedback with
LC_task_answer.
- grades.pm
- Header: "View of the problem" replaced with "View of the problem for
<student name>
- Header: "Correct answer" replaced with "Correct answer for "
<student name>
- New routine: &show_previous_task_version() to show student's previous
version of a BT.
- New routine: &choose_task_version_form() provides a web form to select
display of a student's version of a BT (in same window or in pop-up).
- New routine: &previous_display_javascript() javascript to launch pop-up
etc. for other version.
- &startpage() has four additional args: $stuvcurrent,$stuvdisp,$nomenu,$js
student's current BT version, version being displayed, no page menu (for
pop-up), and javascript to launch previous version pop-up.a
- lonhtmlcommon.pm
- &resource_info_box() has two additional args: $stuvcurrent,$stuvdisp
student's current BT version, and version being displayed.
1: # The LearningOnline Network with CAPA
2: # a pile of common html routines
3: #
4: # $Id: lonhtmlcommon.pm,v 1.300 2012/01/03 00:28:29 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: ######################################################################
30:
31: =pod
32:
33: =head1 NAME
34:
35: Apache::lonhtmlcommon - routines to do common html things
36:
37: =head1 SYNOPSIS
38:
39: Referenced by other mod_perl Apache modules.
40:
41: =head1 INTRODUCTION
42:
43: lonhtmlcommon is a collection of subroutines used to present information
44: in a consistent html format, or provide other functionality related to
45: html.
46:
47: =head2 General Subroutines
48:
49: =over 4
50:
51: =cut
52:
53: ######################################################################
54: ######################################################################
55:
56: package Apache::lonhtmlcommon;
57:
58: use strict;
59: use Time::Local;
60: use Time::HiRes;
61: use Apache::lonlocal;
62: use Apache::lonnet;
63: use HTML::Entities();
64: use LONCAPA;
65:
66: sub java_not_enabled {
67: return "\n".'<span class="LC_error">'.
68: &mt('The required Java applet could not be started. Please make sure to have Java installed and active in your browser.').
69: "</span>\n";
70: }
71:
72: sub coursepreflink {
73: my ($text,$category)=@_;
74: if (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
75: return '<a target="_top" href="'.&HTML::Entities::encode("/adm/courseprefs?phase=display&actions=$category",'<>&"').'"><span class="LC_setting">'.$text.'</span></a>';
76: } else {
77: return '';
78: }
79: }
80:
81: sub raw_href_to_link {
82: my ($message)=@_;
83: $message=~s/(https?\:\/\/[^\s\'\"\<]+)([\s\<]|$)/<a href="$1"><tt>$1<\/tt><\/a>$2/gi;
84: return $message;
85: }
86:
87: sub entity_encode {
88: my ($text)=@_;
89: return &HTML::Entities::encode($text, '<>&"');
90: }
91:
92: sub direct_parm_link {
93: my ($linktext,$symb,$filter,$part,$target)=@_;
94: $symb=&entity_encode($symb);
95: $filter=&entity_encode($filter);
96: $part=&entity_encode($part);
97: if (($symb) && (&Apache::lonnet::allowed('opa')) && ($target ne 'tex')) {
98: return "<a target='_top' href='/adm/parmset?symb=$symb&filter=$filter&part=$part'><span class='LC_setting'>$linktext</span></a>";
99: } else {
100: return $linktext;
101: }
102: }
103: ##############################################
104: ##############################################
105:
106: =item confirm_success
107:
108: Successful completion of an operation message
109:
110: =cut
111:
112: sub confirm_success {
113: my ($message,$failure)=@_;
114: if ($failure) {
115: return '<span class="LC_error" style="font-size: inherit;">'."\n"
116: .'<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.&mt('Error').'" /> '."\n"
117: .$message."\n"
118: .'</span>'."\n";
119: } else {
120: return '<span class="LC_success">'."\n"
121: .'<img src="/adm/lonIcons/navmap.correct.gif" alt="'.&mt('OK').'" /> '."\n"
122: .$message."\n"
123: .'</span>'."\n";
124: }
125: }
126:
127: ##############################################
128: ##############################################
129:
130: =pod
131:
132: =item dragmath_button
133:
134: Creates a button that launches a dragmath popup-window, in which an
135: expression can be edited and pasted as LaTeX into a specified textarea.
136:
137: textarea - Name of the textarea to edit.
138: helpicon - If true, show a help icon to the right of the button.
139:
140: =cut
141:
142: sub dragmath_button {
143: my ($textarea,$helpicon) = @_;
144: my $help_text;
145: if ($helpicon) {
146: $help_text = &Apache::loncommon::help_open_topic('Authoring_Math_Editor',undef,undef,undef,undef,'mathhelpicon_'.$textarea);
147: }
148: my $buttontext=&mt('Edit Math');
149: return <<ENDDRAGMATH;
150: <input type="button" value="$buttontext" onclick="javascript:mathedit('$textarea',document)" />$help_text
151: ENDDRAGMATH
152: }
153:
154: ##############################################
155:
156: =pod
157:
158: =item dragmath_js
159:
160: Javascript used to open pop-up window containing dragmath applet which
161: can be used to paste LaTeX into a textarea.
162: =cut
163:
164: sub dragmath_js {
165: my ($popup) = @_;
166: return <<ENDDRAGMATHJS;
167: <script type="text/javascript">
168: // <![CDATA[
169: function mathedit(textarea, doc) {
170: targetEntry = textarea;
171: targetDoc = doc;
172: newwin = window.open("/adm/dragmath/applet/$popup.html","","width=565,height=500,resizable");
173: }
174: // ]]>
175: </script>
176:
177: ENDDRAGMATHJS
178: }
179:
180:
181: ##############################################
182: ##############################################
183:
184: =pod
185:
186: =item authorbombs
187:
188: =cut
189:
190: ##############################################
191: ##############################################
192:
193: sub authorbombs {
194: my $url=shift;
195: $url=&Apache::lonnet::declutter($url);
196: my ($udom,$uname)=($url=~m{^($LONCAPA::domain_re)/($LONCAPA::username_re)/});
197: my %bombs=&Apache::lonmsg::all_url_author_res_msg($uname,$udom);
198: foreach my $bomb (keys(%bombs)) {
199: if ($bomb =~ /^$udom\/$uname\//) {
200: return '<a href="/adm/bombs/'.$url.
201: '"><img src="'.&Apache::loncommon::lonhttpdurl('/adm/lonMisc/bomb.gif').'" alt="'.&mt('Bomb').'" border="0" /></a>'.
202: &Apache::loncommon::help_open_topic('About_Bombs');
203: }
204: }
205: return '';
206: }
207:
208: ##############################################
209: ##############################################
210:
211: sub recent_filename {
212: my $area=shift;
213: return 'nohist_recent_'.&escape($area);
214: }
215:
216: sub store_recent {
217: my ($area,$name,$value,$freeze)=@_;
218: my $file=&recent_filename($area);
219: my %recent=&Apache::lonnet::dump($file);
220: if (scalar(keys(%recent))>20) {
221: # remove oldest value
222: my $oldest=time();
223: my $delkey='';
224: foreach my $item (keys(%recent)) {
225: my $thistime=(split(/\&/,$recent{$item}))[0];
226: if (($thistime ne "always_include") && ($thistime<$oldest)) {
227: $oldest=$thistime;
228: $delkey=$item;
229: }
230: }
231: &Apache::lonnet::del($file,[$delkey]);
232: }
233: # store new value
234: my $timestamp;
235: if ($freeze) {
236: $timestamp = "always_include";
237: } else {
238: $timestamp = time();
239: }
240: &Apache::lonnet::put($file,{ $name =>
241: $timestamp.'&'.&escape($value) });
242: }
243:
244: sub remove_recent {
245: my ($area,$names)=@_;
246: my $file=&recent_filename($area);
247: return &Apache::lonnet::del($file,$names);
248: }
249:
250: sub select_recent {
251: my ($area,$fieldname,$event)=@_;
252: my %recent=&Apache::lonnet::dump(&recent_filename($area));
253: my $return="\n<select name='$fieldname'".
254: ($event?" onchange='$event'":'').
255: ">\n<option value=''>--- ".&mt('Recent')." ---</option>";
256: foreach my $value (sort(keys(%recent))) {
257: unless ($value =~/^error\:/) {
258: my $escaped = &Apache::loncommon::escape_url($value);
259: &Apache::loncommon::inhibit_menu_check(\$escaped);
260: if ($area eq 'residx') {
261: next if ((!&Apache::lonnet::allowed('bre',$value)) && (!&Apache::lonnet::allowed('bro',$value)));
262: }
263: $return.="\n<option value='$escaped'>".
264: &unescape((split(/\&/,$recent{$value}))[1]).
265: '</option>';
266: }
267: }
268: $return.="\n</select>\n";
269: return $return;
270: }
271:
272: sub get_recent {
273: my ($area, $n) = @_;
274: my %recent=&Apache::lonnet::dump(&recent_filename($area));
275:
276: # Create hash with key as time and recent as value
277: # Begin filling return_hash with any 'always_include' option
278: my %time_hash = ();
279: my %return_hash = ();
280: foreach my $item (keys(%recent)) {
281: my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
282: if ($thistime eq 'always_include') {
283: $return_hash{$item} = &unescape($thisvalue);
284: $n--;
285: } else {
286: $time_hash{$thistime} = $item;
287: }
288: }
289:
290: # Sort by decreasing time and return key value pairs
291: my $idx = 1;
292: foreach my $item (reverse(sort(keys(%time_hash)))) {
293: $return_hash{$time_hash{$item}} =
294: &unescape((split(/\&/,$recent{$time_hash{$item}}))[1]);
295: if ($n && ($idx++ >= $n)) {last;}
296: }
297:
298: return %return_hash;
299: }
300:
301: sub get_recent_frozen {
302: my ($area) = @_;
303: my %recent=&Apache::lonnet::dump(&recent_filename($area));
304:
305: # Create hash with all 'frozen' items
306: my %return_hash = ();
307: foreach my $item (keys(%recent)) {
308: my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
309: if ($thistime eq 'always_include') {
310: $return_hash{$item} = &unescape($thisvalue);
311: }
312: }
313: return %return_hash;
314: }
315:
316:
317:
318: =pod
319:
320: =item textbox
321:
322: =cut
323:
324: ##############################################
325: ##############################################
326: sub textbox {
327: my ($name,$value,$size,$special) = @_;
328: $size = 40 if (! defined($size));
329: $value = &HTML::Entities::encode($value,'<>&"');
330: my $Str = '<input type="text" name="'.$name.'" size="'.$size.'" '.
331: 'value="'.$value.'" '.$special.' />';
332: return $Str;
333: }
334:
335: ##############################################
336: ##############################################
337:
338: =pod
339:
340: =item checkbox
341:
342: =cut
343:
344: ##############################################
345: ##############################################
346: sub checkbox {
347: my ($name,$checked,$value) = @_;
348: my $Str = '<input type="checkbox" name="'.$name.'" ';
349: if (defined($value)) {
350: $Str .= 'value="'.$value.'"';
351: }
352: if ($checked) {
353: $Str .= ' checked="checked"';
354: }
355: $Str .= ' />';
356: return $Str;
357: }
358:
359:
360: =pod
361:
362: =item radiobutton
363:
364: =cut
365:
366: ##############################################
367: ##############################################
368: sub radio {
369: my ($name,$checked,$value) = @_;
370: my $Str = '<input type="radio" name="'.$name.'" ';
371: if (defined($value)) {
372: $Str .= 'value="'.$value.'"';
373: }
374: if ($checked eq $value) {
375: $Str .= ' checked="checked"';
376: }
377: $Str .= ' />';
378: return $Str;
379: }
380:
381: ##############################################
382: ##############################################
383:
384: =pod
385:
386: =item &date_setter
387:
388: &date_setter returns html and javascript for a compact date-setting form.
389: To retrieve values from it, use &get_date_from_form().
390:
391: Inputs
392:
393: =over 4
394:
395: =item $dname
396:
397: The name to prepend to the form elements.
398: The form elements defined will be dname_year, dname_month, dname_day,
399: dname_hour, dname_min, and dname_sec.
400:
401: =item $currentvalue
402:
403: The current setting for this time parameter. A unix format time
404: (time in seconds since the beginning of Jan 1st, 1970, GMT.
405: An undefined value is taken to indicate the value is the current time
406: unless it is requested to leave it empty. See $includeempty.
407: Also, to be explicit, a value of 'now' also indicates the current time.
408:
409: =item $special
410:
411: Additional html/javascript to be associated with each element in
412: the date_setter. See lonparmset for example usage.
413:
414: =item $includeempty
415:
416: If it is set (true) and no date/time value is provided,
417: the date/time fields are left empty.
418:
419: =item $state
420:
421: Specifies the initial state of the form elements. Either 'disabled' or empty.
422: Defaults to empty, which indiciates the form elements are not disabled.
423:
424: =back
425:
426: Bugs
427:
428: The method used to restrict user input will fail in the year 2400.
429:
430: =cut
431:
432: ##############################################
433: ##############################################
434: sub date_setter {
435: my ($formname,$dname,$currentvalue,$special,$includeempty,$state,
436: $no_hh_mm_ss,$defhour,$defmin,$defsec,$nolink) = @_;
437: my $now = time;
438:
439: my $tzname;
440: my ($sec,$min,$hour,$mday,$month,$year) = ('', '', undef,''.''.'');
441: #other potentially useful values: wkday,yrday,is_daylight_savings
442:
443: if (! defined($state) || $state ne 'disabled') {
444: $state = '';
445: }
446: if (! defined($no_hh_mm_ss)) {
447: $no_hh_mm_ss = 0;
448: }
449: if ($currentvalue eq 'now') {
450: $currentvalue = $now;
451: }
452:
453: # Default value: Set empty date field to current time
454: # unless empty inclusion is requested
455: if ((!$includeempty) && (!$currentvalue)) {
456: $currentvalue = $now;
457: }
458: # Do we have a date? Split it!
459: if ($currentvalue) {
460: ($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($currentvalue);
461:
462: #No values provided for hour, min, sec? Use default 0
463: if (($defhour) || ($defmin) || ($defsec)) {
464: $sec = ($defsec ? $defsec : 0);
465: $min = ($defmin ? $defmin : 0);
466: $hour = ($defhour ? $defhour : 0);
467: }
468: }
469: my $result = "\n<!-- $dname date setting form -->\n";
470: $result .= <<ENDJS;
471: <script type="text/javascript">
472: // <![CDATA[
473: function $dname\_checkday() {
474: var day = document.$formname.$dname\_day.value;
475: var month = document.$formname.$dname\_month.value;
476: var year = document.$formname.$dname\_year.value;
477: var valid = true;
478: if (day < 1) {
479: document.$formname.$dname\_day.value = 1;
480: }
481: if (day > 31) {
482: document.$formname.$dname\_day.value = 31;
483: }
484: if ((month == 1) || (month == 3) || (month == 5) ||
485: (month == 7) || (month == 8) || (month == 10) ||
486: (month == 12)) {
487: if (day > 31) {
488: document.$formname.$dname\_day.value = 31;
489: day = 31;
490: }
491: } else if (month == 2 ) {
492: if ((year % 4 == 0) && (year % 100 != 0)) {
493: if (day > 29) {
494: document.$formname.$dname\_day.value = 29;
495: }
496: } else if (day > 29) {
497: document.$formname.$dname\_day.value = 28;
498: }
499: } else if (day > 30) {
500: document.$formname.$dname\_day.value = 30;
501: }
502: }
503:
504: function $dname\_disable() {
505: document.$formname.$dname\_month.disabled=true;
506: document.$formname.$dname\_day.disabled=true;
507: document.$formname.$dname\_year.disabled=true;
508: document.$formname.$dname\_hour.disabled=true;
509: document.$formname.$dname\_minute.disabled=true;
510: document.$formname.$dname\_second.disabled=true;
511: }
512:
513: function $dname\_enable() {
514: document.$formname.$dname\_month.disabled=false;
515: document.$formname.$dname\_day.disabled=false;
516: document.$formname.$dname\_year.disabled=false;
517: document.$formname.$dname\_hour.disabled=false;
518: document.$formname.$dname\_minute.disabled=false;
519: document.$formname.$dname\_second.disabled=false;
520: }
521:
522: function $dname\_opencalendar() {
523: if (! document.$formname.$dname\_month.disabled) {
524: var calwin=window.open(
525: "/adm/announcements?pickdate=yes&formname=$formname&element=$dname&month="+
526: document.$formname.$dname\_month.value+"&year="+
527: document.$formname.$dname\_year.value,
528: "LONCAPAcal",
529: "height=350,width=350,scrollbars=yes,resizable=yes,menubar=no");
530: }
531:
532: }
533: // ]]>
534: </script>
535: ENDJS
536: $result .= ' <span class="LC_nobreak">';
537: my $monthselector = qq{<select name="$dname\_month" $special $state onchange="javascript:$dname\_checkday()" >};
538: # Month
539: my @Months = qw/January February March April May June
540: July August September October November December/;
541: # Pad @Months with a bogus value to make indexing easier
542: unshift(@Months,'If you can read this an error occurred');
543: if ($includeempty) { $monthselector.="<option value=''></option>"; }
544: for(my $m = 1;$m <=$#Months;$m++) {
545: $monthselector .= qq{ <option value="$m"};
546: $monthselector .= ' selected="selected"' if ($m-1 eq $month);
547: $monthselector .= '> '.&mt($Months[$m]).' </option>'."\n";
548: }
549: $monthselector.= ' </select>';
550: # Day
551: my $dayselector = qq{<input type="text" name="$dname\_day" $state value="$mday" size="3" $special onchange="javascript:$dname\_checkday()" />};
552: # Year
553: my $yearselector = qq{<input type="text" name="$dname\_year" $state value="$year" size="5" $special onchange="javascript:$dname\_checkday()" />};
554: #
555: my $hourselector = qq{<select name="$dname\_hour" $special $state >};
556: if ($includeempty) {
557: $hourselector.=qq{<option value=''></option>};
558: }
559: for (my $h = 0;$h<24;$h++) {
560: $hourselector .= qq{<option value="$h"};
561: $hourselector .= ' selected="selected"' if (defined($hour) && $hour == $h);
562: $hourselector .= ">";
563: my $timest='';
564: if ($h == 0) {
565: $timest .= "12 am";
566: } elsif($h == 12) {
567: $timest .= "12 noon";
568: } elsif($h < 12) {
569: $timest .= "$h am";
570: } else {
571: $timest .= $h-12 ." pm";
572: }
573: $timest=&mt($timest);
574: $hourselector .= $timest." </option>\n";
575: }
576: $hourselector .= " </select>\n";
577: my $minuteselector = qq{<input type="text" name="$dname\_minute" $special $state value="$min" size="3" />};
578: my $secondselector= qq{<input type="text" name="$dname\_second" $special $state value="$sec" size="3" />};
579: my $cal_link;
580: if (!$nolink) {
581: $cal_link = qq{<a href="javascript:$dname\_opencalendar()">};
582: }
583: #
584: my $tzone = ' '.$tzname.' ';
585: if ($no_hh_mm_ss) {
586: $result .= &mt('[_1] [_2] [_3] ',
587: $monthselector,$dayselector,$yearselector).
588: $tzone;
589: if (!$nolink) {
590: $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
591: }
592: } else {
593: $result .= &mt('[_1] [_2] [_3] [_4] [_5]m [_6]s ',
594: $monthselector,$dayselector,$yearselector,
595: $hourselector,$minuteselector,$secondselector).
596: $tzone;
597: if (!$nolink) {
598: $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
599: }
600: }
601: $result .= "</span>\n<!-- end $dname date setting form -->\n";
602: return $result;
603: }
604:
605: sub get_timedates {
606: my ($epoch) = @_;
607: my $dt = DateTime->from_epoch(epoch => $epoch)
608: ->set_time_zone(&Apache::lonlocal::gettimezone());
609: my $tzname = $dt->time_zone_short_name();
610: my $sec = $dt->second;
611: my $min = $dt->minute;
612: my $hour = $dt->hour;
613: my $mday = $dt->day;
614: my $month = $dt->month;
615: if ($month) {
616: $month --;
617: }
618: my $year = $dt->year;
619: return ($tzname,$sec,$min,$hour,$mday,$month,$year);
620: }
621:
622: sub build_url {
623: my ($base, $fields)=@_;
624: my $url;
625: $url = $base.'?';
626: foreach my $key (keys(%$fields)) {
627: $url.=&escape($key).'='.&escape($$fields{$key}).'&';
628: }
629: $url =~ s/&$//;
630: return $url;
631: }
632:
633:
634: ##############################################
635: ##############################################
636:
637: =pod
638:
639: =item &get_date_from_form
640:
641: get_date_from_form retrieves the date specified in an &date_setter form.
642:
643: Inputs:
644:
645: =over 4
646:
647: =item $dname
648:
649: The name passed to &date_setter, which prefixes the form elements.
650:
651: =item $defaulttime
652:
653: The unix time to use as the default in case of poor inputs.
654:
655: =back
656:
657: Returns: Unix time represented in the form.
658:
659: =cut
660:
661: ##############################################
662: ##############################################
663: sub get_date_from_form {
664: my ($dname) = @_;
665: my ($sec,$min,$hour,$day,$month,$year);
666: #
667: if (defined($env{'form.'.$dname.'_second'})) {
668: my $tmpsec = $env{'form.'.$dname.'_second'};
669: if (($tmpsec =~ /^\d+$/) && ($tmpsec >= 0) && ($tmpsec < 60)) {
670: $sec = $tmpsec;
671: }
672: if (!defined($tmpsec) || $tmpsec eq '') { $sec = 0; }
673: } else {
674: $sec = 0;
675: }
676: if (defined($env{'form.'.$dname.'_minute'})) {
677: my $tmpmin = $env{'form.'.$dname.'_minute'};
678: if (($tmpmin =~ /^\d+$/) && ($tmpmin >= 0) && ($tmpmin < 60)) {
679: $min = $tmpmin;
680: }
681: if (!defined($tmpmin) || $tmpmin eq '') { $min = 0; }
682: } else {
683: $min = 0;
684: }
685: if (defined($env{'form.'.$dname.'_hour'})) {
686: my $tmphour = $env{'form.'.$dname.'_hour'};
687: if (($tmphour =~ /^\d+$/) && ($tmphour >= 0) && ($tmphour < 24)) {
688: $hour = $tmphour;
689: }
690: } else {
691: $hour = 0;
692: }
693: if (defined($env{'form.'.$dname.'_day'})) {
694: my $tmpday = $env{'form.'.$dname.'_day'};
695: if (($tmpday =~ /^\d+$/) && ($tmpday > 0) && ($tmpday < 32)) {
696: $day = $tmpday;
697: }
698: }
699: if (defined($env{'form.'.$dname.'_month'})) {
700: my $tmpmonth = $env{'form.'.$dname.'_month'};
701: if (($tmpmonth =~ /^\d+$/) && ($tmpmonth > 0) && ($tmpmonth < 13)) {
702: $month = $tmpmonth;
703: }
704: }
705: if (defined($env{'form.'.$dname.'_year'})) {
706: my $tmpyear = $env{'form.'.$dname.'_year'};
707: if (($tmpyear =~ /^\d+$/) && ($tmpyear >= 1970)) {
708: $year = $tmpyear;
709: }
710: }
711: if (($year<1970) || ($year>2037)) { return undef; }
712: if (defined($sec) && defined($min) && defined($hour) &&
713: defined($day) && defined($month) && defined($year)) {
714: my $timezone = &Apache::lonlocal::gettimezone();
715: my $dt = DateTime->new( year => $year,
716: month => $month,
717: day => $day,
718: hour => $hour,
719: minute => $min,
720: second => $sec,
721: time_zone => $timezone,
722: );
723: my $epoch_time = $dt->epoch;
724: if ($epoch_time ne '') {
725: return $epoch_time;
726: } else {
727: return undef;
728: }
729: } else {
730: return undef;
731: }
732: }
733:
734: ##############################################
735: ##############################################
736:
737: =pod
738:
739: =item &pjump_javascript_definition()
740:
741: Returns javascript defining the 'pjump' function, which opens up a
742: parameter setting wizard.
743:
744: =cut
745:
746: ##############################################
747: ##############################################
748: sub pjump_javascript_definition {
749: my $Str = <<END;
750: function pjump(type,dis,value,marker,ret,call,hour,min,sec) {
751: openMyModal("/adm/rat/parameter.html?type="+escape(type)
752: +"&value="+escape(value)+"&marker="+escape(marker)
753: +"&return="+escape(ret)
754: +"&call="+escape(call)+"&name="+escape(dis)
755: +"&defhour="+escape(hour)+"&defmin="+escape(min)
756: +"&defsec="+escape(sec)+"&modal=1",350,350,'no');
757: }
758: END
759: return $Str;
760: }
761:
762: ##############################################
763: ##############################################
764:
765: =pod
766:
767: =item &javascript_nothing()
768:
769: Return an appropriate null for the users browser. This is used
770: as the first arguement for window.open calls when you want a blank
771: window that you can then write to.
772:
773: =cut
774:
775: ##############################################
776: ##############################################
777: sub javascript_nothing {
778: # mozilla and other browsers work with "''", but IE on mac does not.
779: my $nothing = "''";
780: my $user_browser;
781: my $user_os;
782: $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
783: $user_os = $env{'browser.os'} if (exists($env{'browser.os'}));
784: if (! defined($user_browser) || ! defined($user_os)) {
785: (undef,$user_browser,undef,undef,undef,$user_os) =
786: &Apache::loncommon::decode_user_agent();
787: }
788: if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
789: $nothing = "'javascript:void(0);'";
790: }
791: return $nothing;
792: }
793:
794: ##############################################
795: ##############################################
796: sub javascript_docopen {
797: my ($mimetype) = @_;
798: $mimetype ||= 'text/html';
799: # safari does not understand document.open() and loads "text/html"
800: my $nothing = "''";
801: my $user_browser;
802: my $user_os;
803: $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
804: $user_os = $env{'browser.os'} if (exists($env{'browser.os'}));
805: if (! defined($user_browser) || ! defined($user_os)) {
806: (undef,$user_browser,undef,undef,undef,$user_os) =
807: &Apache::loncommon::decode_user_agent();
808: }
809: if ($user_browser eq 'safari' && $user_os =~ 'mac') {
810: $nothing = "document.clear()";
811: } else {
812: $nothing = "document.open('$mimetype','replace')";
813: }
814: return $nothing;
815: }
816:
817:
818: ##############################################
819: ##############################################
820:
821: =pod
822:
823: =item &StatusOptions()
824:
825: Returns html for a selection box which allows the user to choose the
826: enrollment status of students. The selection box name is 'Status'.
827:
828: Inputs:
829:
830: $status: the currently selected status. If undefined the value of
831: $env{'form.Status'} is taken. If that is undefined, a value of 'Active'
832: is used.
833:
834: $formname: The name of the form. If defined the onchange attribute of
835: the selection box is set to document.$formname.submit().
836:
837: $size: the size (number of lines) of the selection box.
838:
839: $onchange: javascript to use when the value is changed. Enclosed in
840: double quotes, ""s, not single quotes.
841:
842: Returns: a perl string as described.
843:
844: =cut
845:
846: ##############################################
847: ##############################################
848: sub StatusOptions {
849: my ($status, $formName,$size,$onchange,$mult)=@_;
850: $size = 1 if (!defined($size));
851: if (! defined($status)) {
852: $status = 'Active';
853: $status = $env{'form.Status'} if (exists($env{'form.Status'}));
854: }
855:
856: my $Str = '';
857: $Str .= '<select name="Status"';
858: if (defined($mult)){
859: $Str .= ' multiple="multiple" ';
860: }
861: if(defined($formName) && $formName ne '' && ! defined($onchange)) {
862: $Str .= ' onchange="document.'.$formName.'.submit()"';
863: }
864: if (defined($onchange)) {
865: $Str .= ' onchange="'.$onchange.'"';
866: }
867: $Str .= ' size="'.$size.'" ';
868: $Str .= '>'."\n";
869: foreach my $type (['Active', &mt('Currently Has Access')],
870: ['Future', &mt('Will Have Future Access')],
871: ['Expired', &mt('Previously Had Access')],
872: ['Any', &mt('Any Access Status')]) {
873: my ($name,$label) = @$type;
874: $Str .= '<option value="'.$name.'" ';
875: if ($status eq $name) {
876: $Str .= 'selected="selected" ';
877: }
878: $Str .= '>'.$label.'</option>'."\n";
879: }
880:
881: $Str .= '</select>'."\n";
882: }
883:
884: ########################################################
885: ########################################################
886:
887: =pod
888:
889: =item Progess Window Handling Routines
890:
891: These routines handle the creation, update, increment, and closure of
892: progress windows. The progress window reports to the user the number
893: of items completed and an estimate of the time required to complete the rest.
894:
895: =over 4
896:
897:
898: =item &Create_PrgWin
899:
900: Writes javascript to the client to open a progress window and returns a
901: data structure used for bookkeeping.
902:
903: Inputs
904:
905: =over 4
906:
907: =item $r Apache request
908:
909: =item $title The title of the progress window
910:
911: =item $heading A description (usually 1 line) of the process being initiated.
912:
913: =item $number_to_do The total number of items being processed.
914:
915: =item $type Either 'popup' or 'inline' (popup is assumed if nothing is
916: specified)
917:
918: =item $width Specify the width in charaters of the input field.
919:
920: =item $formname Only useful in the inline case, if a form already exists, this needs to be used and specfiy the name of the form, otherwise the Progress line will be created in a new form of it's own
921:
922: =item $inputname Only useful in the inline case, if a form and an input of type text exists, use this to specify the name of the input field
923:
924: =back
925:
926: Returns a hash containing the progress state data structure.
927:
928:
929: =item &Update_PrgWin
930:
931: Updates the text in the progress indicator. Does not increment the count.
932: See &Increment_PrgWin.
933:
934: Inputs:
935:
936: =over 4
937:
938: =item $r Apache request
939:
940: =item $prog_state Pointer to the data structure returned by &Create_PrgWin
941:
942: =item $displaystring The string to write to the status indicator
943:
944: =back
945:
946: Returns: none
947:
948:
949: =item Increment_PrgWin
950:
951: Increment the count of items completed for the progress window by $step or 1 if no step is provided.
952:
953: Inputs:
954:
955: =over 4
956:
957: =item $r Apache request
958:
959: =item $prog_state Pointer to the data structure returned by Create_PrgWin
960:
961: =item $extraInfo A description of the items being iterated over. Typically
962: 'student'.
963:
964: =item $step (optional) counter step. Will be set to default 1 if ommited. step must be greater than 0 or empty.
965:
966: =back
967:
968: Returns: none
969:
970:
971: =item Close_PrgWin
972:
973: Closes the progress window.
974:
975: Inputs:
976:
977: =over 4
978:
979: =item $r Apache request
980:
981: =item $prog_state Pointer to the data structure returned by Create_PrgWin
982:
983: =back
984:
985: Returns: none
986:
987: =back
988:
989: =cut
990:
991: ########################################################
992: ########################################################
993:
994:
995: # Create progress
996: sub Create_PrgWin {
997: my ($r,$number_to_do)=@_;
998: my %prog_state;
999: $prog_state{'done'}=0;
1000: $prog_state{'firststart'}=&Time::HiRes::time();
1001: $prog_state{'laststart'}=&Time::HiRes::time();
1002: $prog_state{'max'}=$number_to_do;
1003: &Apache::loncommon::LCprogressbar($r);
1004: return %prog_state;
1005: }
1006:
1007: # update progress
1008: sub Update_PrgWin {
1009: my ($r,$prog_state,$displayString)=@_;
1010: &Apache::loncommon::LCprogressbarUpdate($r,undef,$displayString);
1011: $$prog_state{'laststart'}=&Time::HiRes::time();
1012: }
1013:
1014: # increment progress state
1015: sub Increment_PrgWin {
1016: my ($r,$prog_state,$extraInfo,$step)=@_;
1017: $step = $step > 0 ? $step : 1;
1018: $$prog_state{'done'} += $step;
1019:
1020: # Catch (max modulo step) <> 0
1021: my $current = $$prog_state{'done'};
1022: my $last = ($$prog_state{'max'} - $current);
1023: if ($last <= 0) {
1024: $last = 1;
1025: $current = $$prog_state{'max'};
1026: }
1027:
1028: my $time_est= (&Time::HiRes::time() - $$prog_state{'firststart'})/
1029: $current * $last;
1030: $time_est = int($time_est);
1031: #
1032: my $min = int($time_est/60);
1033: my $sec = $time_est % 60;
1034:
1035: my $lasttime = &Time::HiRes::time()-$$prog_state{'laststart'};
1036: if ($lasttime > 9) {
1037: $lasttime = int($lasttime);
1038: } elsif ($lasttime < 0.01) {
1039: $lasttime = 0;
1040: } else {
1041: $lasttime = sprintf("%3.2f",$lasttime);
1042: }
1043:
1044: $sec = 0 if ($min >= 10); # Don't show seconds if remaining time >= 10 min.
1045: $sec = 1 if ( ($min == 0) && ($sec == 0) ); # Little cheating: pretend to have 1 second remaining instead of 0 to have something to display
1046:
1047: my $timeinfo =
1048: &mt('[_1]/[_2]:'
1049: .' [quant,_3,minute,minutes,] [quant,_4,second ,seconds ,]remaining'
1050: .' ([quant,_5,second] for '.$extraInfo.')',
1051: $current,
1052: $$prog_state{'max'},
1053: $min,
1054: $sec,
1055: $lasttime);
1056: my $percent=0;
1057: if ($$prog_state{'max'}) {
1058: $percent=int(100.*$current/$$prog_state{'max'});
1059: }
1060: &Apache::loncommon::LCprogressbarUpdate($r,$percent,$timeinfo);
1061: $$prog_state{'laststart'}=&Time::HiRes::time();
1062: }
1063:
1064: # close Progress Line
1065: sub Close_PrgWin {
1066: my ($r,$prog_state)=@_;
1067: &Apache::loncommon::LCprogressbarClose($r);
1068: undef(%$prog_state);
1069: }
1070:
1071: # ------------------------------------------------------- Puts directory header
1072:
1073: sub crumbs {
1074: my ($uri,$target,$prefix,$form,$skiplast)=@_;
1075: if ($target) {
1076: $target = ' target="'.
1077: &Apache::loncommon::escape_single($target).'"';
1078: }
1079: my $output='<span class="LC_filename">';
1080: $output.=$prefix.'/';
1081: if (($env{'user.adv'}) || ($env{'user.author'})) {
1082: my $path=$prefix.'/';
1083: foreach my $dir (split('/',$uri)) {
1084: if (! $dir) { next; }
1085: $path .= $dir;
1086: if ($path eq $uri) {
1087: if ($skiplast) {
1088: $output.=$dir;
1089: last;
1090: }
1091: } else {
1092: $path.='/';
1093: }
1094: my $href_path = &HTML::Entities::encode($path,'<>&"');
1095: &Apache::loncommon::inhibit_menu_check(\$href_path);
1096: if ($form) {
1097: my $href = 'javascript:'.$form.".action='".$href_path."';".$form.'.submit();';
1098: $output.=qq{<a href="$href"$target>$dir</a>/};
1099: } else {
1100: $output.=qq{<a href="$href_path"$target>$dir</a>/};
1101: }
1102: }
1103: } else {
1104: foreach my $dir (split('/',$uri)) {
1105: if (! $dir) { next; }
1106: $output.=$dir.'/';
1107: }
1108: }
1109: if ($uri !~ m|/$|) { $output=~s|/$||; }
1110: $output.='</span>';
1111:
1112: return $output;
1113: }
1114:
1115: # --------------------- A function that generates a window for the spellchecker
1116:
1117: sub spellheader {
1118: my $start_page=
1119: &Apache::loncommon::start_page('Speller Suggestions',undef,
1120: {'only_body' => 1,
1121: 'js_ready' => 1,
1122: 'bgcolor' => '#DDDDDD',
1123: 'add_entries' => {
1124: 'onload' =>
1125: 'document.forms.spellcheckform.submit()',
1126: }
1127: });
1128: my $end_page=
1129: &Apache::loncommon::end_page({'js_ready' => 1});
1130:
1131: my $nothing=&javascript_nothing();
1132: return (<<ENDCHECK);
1133: <script type="text/javascript">
1134: // <![CDATA[
1135: //<!-- BEGIN LON-CAPA Internal
1136: var checkwin;
1137:
1138: function spellcheckerwindow(string) {
1139: var esc_string = string.replace(/\"/g,'"');
1140: checkwin=window.open($nothing,'spellcheckwin','height=320,width=280,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no');
1141: checkwin.document.writeln('$start_page<form name="spellcheckform" action="/adm/spellcheck" method="post"><input type="hidden" name="text" value="'+esc_string+'" /><\\/form>$end_page');
1142: checkwin.document.close();
1143: }
1144: // END LON-CAPA Internal -->
1145: // ]]>
1146: </script>
1147: ENDCHECK
1148: }
1149:
1150: # ---------------------------------- Generate link to spell checker for a field
1151:
1152: sub spelllink {
1153: my ($form,$field)=@_;
1154: my $linktext=&mt('Check Spelling');
1155: return (<<ENDLINK);
1156: <a href="javascript:if (typeof(document.$form.onsubmit)!='undefined') { if (document.$form.onsubmit!=null) { document.$form.onsubmit();}};spellcheckerwindow(this.document.forms.$form.$field.value);">$linktext</a>
1157: ENDLINK
1158: }
1159:
1160: # ------------------------------------------------- Output headers for CKEditor
1161:
1162: sub htmlareaheaders {
1163: my $s="";
1164: if (&htmlareabrowser()) {
1165: $s.=(<<ENDEDITOR);
1166: <script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
1167: ENDEDITOR
1168: }
1169: $s.=(<<ENDJQUERY);
1170: <script type="text/javascript" src="/adm/jQuery/js/jquery-1.6.2.min.js"></script>
1171: <script type="text/javascript" src="/adm/jQuery/js/jquery-ui-1.8.16.custom.min.js"></script>
1172: <link rel="stylesheet" type="text/css" href="/adm/jQuery/css/smoothness/jquery-ui-1.8.16.custom.css" />
1173: ENDJQUERY
1174: return $s;
1175: }
1176:
1177: # ----------------------------------------------------------------- Preferences
1178:
1179: # ------------------------------------------------- lang to use in html editor
1180: sub htmlarea_lang {
1181: my $lang='en';
1182: if (&mt('htmlarea_lang') ne 'htmlarea_lang') {
1183: $lang=&mt('htmlarea_lang');
1184: }
1185: return $lang;
1186: }
1187:
1188: # ----------------------------------------- Script to activate only some fields
1189:
1190: sub htmlareaselectactive {
1191: my ($args) = @_;
1192: unless (&htmlareabrowser()) { return ''; }
1193: my $output='<script type="text/javascript" defer="defer">'."\n"
1194: .'// <![CDATA['."\n";
1195: my $lang = &htmlarea_lang();
1196: my $fullpage = 'false';
1197: my ($dragmath_prefix,$dragmath_helpicon,$dragmath_whitespace);
1198: if (ref($args) eq 'HASH') {
1199: if (exists($args->{'lang'})) {
1200: if ($args->{'lang'} ne '') {
1201: $lang = $args->{'lang'};
1202: }
1203: }
1204: if (exists($args->{'fullpage'})) {
1205: if ($args->{'fullpage'} eq 'true') {
1206: $fullpage = $args->{'fullpage'};
1207: }
1208: }
1209: if (exists($args->{'dragmath'})) {
1210: if ($args->{'dragmath'} ne '') {
1211: $dragmath_prefix = $args->{'dragmath'};
1212: $dragmath_helpicon=&Apache::loncommon::lonhttpdurl("/adm/help/help.png");
1213: $dragmath_whitespace=&Apache::loncommon::lonhttpdurl("/adm/lonIcons/transparent1x1.gif");
1214: }
1215: }
1216: }
1217: $output.='
1218:
1219: function containsBlockHtml(id) {
1220: var re = $("#"+id).html().search(/(?:\<\;|\<)(br|h1|h2|h3|h4|h5|h6|p|ol|ul|table|pre|address|blockquote|center|div)[\s]*((?:[\/]*[\s]*(?:\>\;|\>)|(?:\>\;|\>)[\s\S]*(?:\<\;|\<)\/[\s]*\1[\s]*\(?:\>\;|\>))/im);
1221: return (re >= 0);
1222: }
1223:
1224: function startRichEditor(id) {
1225: CKEDITOR.replace(id,
1226: {
1227: customConfig: "/ckeditor/loncapaconfig.js",
1228: language : "'.$lang.'",
1229: fullPage : '.$fullpage.',
1230: }
1231: );
1232: }
1233:
1234: function destroyRichEditor(id) {
1235: CKEDITOR.instances[id].destroy();
1236: }
1237:
1238: function editorHandler(event) {
1239: var rawid = $(this).attr("id");
1240: var id = new RegExp("LC_rt_(.*)").exec(rawid)[1];
1241: event.preventDefault();
1242: var rt_enabled = $(this).hasClass("LC_enable_rt");
1243: if (rt_enabled) {
1244: startRichEditor(id);
1245: $("#LC_rt_"+id).html("<b>« Plain text</b>");
1246: $("#LC_rt_"+id).attr("title", "Disable rich text formatting and edit in plain text");
1247: $("#LC_rt_"+id).addClass("LC_disable_rt");
1248: $("#LC_rt_"+id).removeClass("LC_enable_rt");
1249: } else {
1250: destroyRichEditor(id);
1251: $("#LC_rt_"+id).html("<b>Rich formatting »</b>");
1252: $("#LC_rt_"+id).attr("title", "Enable rich text formatting (bold, italic, etc.)");
1253: $("#LC_rt_"+id).addClass("LC_enable_rt");
1254: $("#LC_rt_"+id).removeClass("LC_disable_rt");
1255: }';
1256: if ($dragmath_prefix ne '') {
1257: $output .= "\n var visible = '';
1258: if (rt_enabled) {
1259: visible = 'none';
1260: }
1261: editmath_visibility(id,visible);\n";
1262: }
1263: $output .= '
1264: }
1265: $(document).ready(function(){
1266: $(".LC_richAlwaysOn").each(function() {
1267: startRichEditor($(this).attr("id"));
1268: });
1269: $(".LC_richDetectHtml").each(function() {
1270: var id = $(this).attr("id");
1271: var rt_enabled = containsBlockHtml(id);
1272: if(rt_enabled) {
1273: $(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Disable rich text formatting and edit in plain text\" class=\"LC_disable_rt\"><b>« Plain text</b></a></div>");
1274: startRichEditor(id);
1275: $("#LC_rt_"+id).click(editorHandler);
1276: }
1277: else {
1278: $(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Enable rich text formatting (bold, italic, etc.)\" class=\"LC_enable_rt\"><b>Rich formatting »</b></a></div>");
1279: $("#LC_rt_"+id).click(editorHandler);
1280: }';
1281: if ($dragmath_prefix ne '') {
1282: $output .= "\n var visible = '';
1283: if (rt_enabled) {
1284: visible = 'none';
1285: }
1286: editmath_visibility(id,visible);\n";
1287: }
1288: $output .= '
1289: });
1290: $(".LC_richDefaultOn").each(function() {
1291: var id = $(this).attr("id");
1292: $(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Disable rich text formatting and edit in plain text\" class=\"LC_disable_rt\"><b>« Plain text</b></a></div>");
1293: startRichEditor(id);
1294: $("#LC_rt_"+id).click(editorHandler);
1295: });
1296: $(".LC_richDefaultOff").each(function() {
1297: var id = $(this).attr("id");
1298: $(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Enable rich text formatting (bold, italic, etc.)\" class=\"LC_enable_rt\"><b>Rich formatting »</b></a></div>");
1299: $("#LC_rt_"+id).click(editorHandler);
1300: });
1301: });
1302: ';
1303: if ($dragmath_prefix ne '') {
1304: $output .= '
1305:
1306: function editmath_visibility(id,value) {
1307:
1308: if ((id == "") || (id == null)) {
1309: return;
1310: }
1311: var mathid = "'.$dragmath_prefix.'_"+id;
1312: mathele = document.getElementById(mathid);
1313: if (mathele == null) {
1314: return;
1315: }
1316: mathele.style.display = value;
1317: var mathhelpicon = "'.$dragmath_prefix.'helpicon'.'_"+id;
1318: mathhelpiconele = document.getElementById(mathhelpicon);
1319: if (mathhelpiconele == null) {
1320: return;
1321: }
1322: if (value == "none") {
1323: mathhelpiconele.src = "'.$dragmath_whitespace.'";
1324: } else {
1325: mathhelpiconele.src = "'.$dragmath_helpicon.'";
1326: }
1327: }
1328: ';
1329:
1330: }
1331: $output.="\nwindow.status='Activated Editfields';\n"
1332: .'// ]]>'."\n"
1333: .'</script>';
1334: return $output;
1335: }
1336:
1337: # --------------------------------------------------------------------- Blocked
1338:
1339: sub htmlareablocked {
1340: unless ($env{'environment.wysiwygeditor'} eq 'on') { return 1; }
1341: return 0;
1342: }
1343:
1344: # ---------------------------------------- Browser capable of running HTMLArea?
1345:
1346: sub htmlareabrowser {
1347: return 1;
1348: }
1349:
1350: #
1351: # Should the "return to content" link be shown?
1352: #
1353:
1354: sub show_return_link {
1355:
1356: unless ($env{'request.course.id'}) { return 0; }
1357: if ($env{'request.noversionuri'}=~m{^/priv/} ||
1358: $env{'request.uri'}=~m{^/~}) { return 1; }
1359:
1360: if (($env{'request.noversionuri'} =~ m{^/adm/(viewclasslist|navmaps)($|\?)})
1361: || ($env{'request.noversionuri'} =~ m{^/adm/.*/aboutme($|\?)})) {
1362:
1363: return if ($env{'form.register'});
1364: }
1365: return (($env{'request.noversionuri'}=~m{^/(res|public)/} &&
1366: $env{'request.symb'} eq '')
1367: ||
1368: ($env{'request.noversionuri'}=~ m{^/cgi-bin/printout.pl})
1369: ||
1370: (($env{'request.noversionuri'}=~/^\/adm\//) &&
1371: ($env{'request.noversionuri'}!~/^\/adm\/wrapper\//) &&
1372: ($env{'request.noversionuri'}!~
1373: m{^/adm/.*/(smppg|bulletinboard)($|\?)})
1374: ));
1375: }
1376:
1377:
1378: ############################################################
1379: ############################################################
1380:
1381: =pod
1382:
1383: =item breadcrumbs
1384:
1385: Compiles the previously registered breadcrumbs into an series of links.
1386: Additionally supports a 'component', which will be displayed on the
1387: right side of the breadcrumbs enclosing div (without a link).
1388: A link to help for the component will be included if one is specified.
1389:
1390: All inputs can be undef without problems.
1391:
1392: Inputs: $component (the text on the right side of the breadcrumbs trail),
1393: $component_help
1394: $menulink (boolean, controls whether to include a link to /adm/menu)
1395: $helplink (if 'nohelp' don't include the orange help link)
1396: $css_class (optional name for the class to apply to the table for CSS)
1397: $no_mt (optional flag, 1 if &mt() is _not_ to be applied to $component
1398: when including the text on the right.
1399: Returns a string containing breadcrumbs for the current page.
1400:
1401: =item clear_breadcrumbs
1402:
1403: Clears the previously stored breadcrumbs.
1404:
1405: =item add_breadcrumb
1406:
1407: Pushes a breadcrumb on the stack of crumbs.
1408:
1409: input: $breadcrumb, a hash reference. The keys 'href','title', and 'text'
1410: are required. If present the keys 'faq' and 'bug' will be used to provide
1411: links to the FAQ and bug sites. If the key 'no_mt' is present the 'title'
1412: and 'text' values won't be sent through &mt()
1413:
1414: returns: nothing
1415:
1416: =cut
1417:
1418: ############################################################
1419: ############################################################
1420: {
1421: my @Crumbs;
1422: my %tools = ();
1423:
1424: sub breadcrumbs {
1425: my ($component,$component_help,$menulink,$helplink,$css_class,$no_mt, $CourseBreadcrumbs) = @_;
1426: #
1427: $css_class ||= 'LC_breadcrumbs';
1428:
1429: # Make the faq and bug data cascade
1430: my $faq = '';
1431: my $bug = '';
1432: my $help = '';
1433: # Crumb Symbol
1434: my $crumbsymbol = '»';
1435: # The last breadcrumb does not have a link, so handle it separately.
1436: my $last = pop(@Crumbs);
1437: #
1438: # The first one should be the course or a menu link
1439: if (!defined($menulink)) { $menulink=1; }
1440: if ($menulink) {
1441: my $description = 'Menu';
1442: my $no_mt_descr = 0;
1443: if ((exists($env{'request.course.id'})) &&
1444: ($env{'request.course.id'} ne '') &&
1445: ($env{'course.'.$env{'request.course.id'}.'.description'} ne '')) {
1446: $description =
1447: $env{'course.'.$env{'request.course.id'}.'.description'};
1448: $no_mt_descr = 1;
1449: }
1450: $menulink = { href =>'/adm/menu',
1451: title =>'Go to main menu',
1452: target =>'_top',
1453: text =>$description,
1454: no_mt =>$no_mt_descr, };
1455: if($last) {
1456: #$last set, so we have some crumbs
1457: unshift(@Crumbs,$menulink);
1458: } else {
1459: #only menulink crumb present
1460: $last = $menulink;
1461: }
1462: }
1463: my $links;
1464: if ((&show_return_link) && (!$CourseBreadcrumbs)) {
1465: my $alttext = &mt('Go Back');
1466: $links=&htmltag( 'a',"<img src='/res/adm/pages/reload.png' border='0' style='vertical-align:middle;' alt='$alttext' />",
1467: { href => '/adm/flip?postdata=return:',
1468: title => &mt("Back to most recent content resource") });
1469: $links=&htmltag('li',$links);
1470: }
1471: $links.= join "",
1472: map {
1473: $faq = $_->{'faq'} if (exists($_->{'faq'}));
1474: $bug = $_->{'bug'} if (exists($_->{'bug'}));
1475: $help = $_->{'help'} if (exists($_->{'help'}));
1476:
1477: my $result = $_->{no_mt} ? $_->{text} : &mt($_->{text});
1478:
1479: if ($_->{href}){
1480: $result = &htmltag( 'a', $result,
1481: { href => $_->{href},
1482: title => $_->{no_mt} ? $_->{title} : &mt($_->{title}),
1483: target => $_->{target}, });
1484: }
1485:
1486: $result = &htmltag( 'li', "$result $crumbsymbol");
1487: } @Crumbs;
1488:
1489: #should the last Element be translated?
1490:
1491: my $lasttext = $last->{'no_mt'} ? $last->{'text'}
1492: : mt( $last->{'text'} );
1493:
1494: # last breadcrumb is the first order heading of a page
1495: # for course breadcrumbs it's just bold
1496: $links .= &htmltag( 'li', htmltag($CourseBreadcrumbs ? 'b' : 'h1',
1497: $lasttext), {title => $lasttext});
1498:
1499: my $icons = '';
1500: $faq = $last->{'faq'} if (exists($last->{'faq'}));
1501: $bug = $last->{'bug'} if (exists($last->{'bug'}));
1502: $help = $last->{'help'} if (exists($last->{'help'}));
1503: $component_help=($component_help?$component_help:$help);
1504: # if ($faq ne '') {
1505: # $icons .= &Apache::loncommon::help_open_faq($faq);
1506: # }
1507: # if ($bug ne '') {
1508: # $icons .= &Apache::loncommon::help_open_bug($bug);
1509: # }
1510: if ($faq ne '' || $component_help ne '' || $bug ne '') {
1511: $icons .= &Apache::loncommon::help_open_menu($component,
1512: $component_help,
1513: $faq,$bug);
1514: }
1515: #
1516:
1517:
1518: unless ($CourseBreadcrumbs) {
1519: $links = &htmltag('ol', $links, { id => "LC_MenuBreadcrumbs" });
1520: } else {
1521: $links = &htmltag('ul', $links, { class => "LC_CourseBreadcrumbs" });
1522: }
1523:
1524: if ($component) {
1525: $links = &htmltag('span',
1526: ( $no_mt ? $component : mt($component) ).
1527: ( $icons ? $icons : '' ),
1528: { class => 'LC_breadcrumbs_component' } )
1529: .$links;
1530: }
1531:
1532: &render_tools(\$links);
1533: $links = &htmltag('div', $links,
1534: { id => "LC_breadcrumbs" }) unless ($CourseBreadcrumbs) ;
1535: &render_advtools(\$links);
1536:
1537: # Return the @Crumbs stack to what we started with
1538: push(@Crumbs,$last);
1539: shift(@Crumbs);
1540: # Return the breadcrumb's line
1541: return "$links";
1542: }
1543:
1544: sub clear_breadcrumbs {
1545: undef(@Crumbs);
1546: undef(%tools);
1547: }
1548:
1549: sub add_breadcrumb {
1550: push(@Crumbs,@_);
1551: }
1552:
1553: =item add_breadcrumb_tool($category, $html)
1554:
1555: Adds $html to $category of the breadcrumb toolbar container.
1556:
1557: $html is usually a link to a page that invokes a function on the currently
1558: displayed data (e.g. print when viewing a problem)
1559:
1560: Currently there are 3 possible values for $category:
1561:
1562: =over
1563:
1564: =item navigation
1565: left of breadcrumbs line
1566:
1567: =item tools
1568: right of breadcrumbs line
1569:
1570: =item advtools
1571: advanced tools shown in a separate box below breadcrumbs line
1572:
1573: =back
1574:
1575: returns: nothing
1576:
1577: =cut
1578:
1579: sub add_breadcrumb_tool {
1580: my ($category, @html) = @_;
1581: return unless @html;
1582: if (!keys(%tools)) {
1583: %tools = ( navigation => [], tools => [], advtools => []);
1584: }
1585:
1586: #this cleans data received from lonmenu::innerregister
1587: @html = grep {defined $_ && $_ ne ''} @html;
1588: for (@html) {
1589: s/align="(right|left)"//;
1590: # s/<span.*?\/span>// if $category ne 'advtools';
1591: }
1592:
1593: push @{$tools{$category}}, @html;
1594: }
1595:
1596: =item clear_breadcrumb_tools()
1597:
1598: Clears the breadcrumb toolbar container.
1599:
1600: returns: nothing
1601:
1602: =cut
1603:
1604: sub clear_breadcrumb_tools {
1605: undef(%tools);
1606: }
1607:
1608: =item render_tools(\$breadcrumbs)
1609:
1610: Creates html for breadcrumb tools (categories navigation and tools) and inserts
1611: \$breadcrumbs at the correct position.
1612:
1613: input: \$breadcrumbs - a reference to the string containing prepared
1614: breadcrumbs.
1615:
1616: returns: nothing
1617: =cut
1618:
1619: #TODO might split this in separate functions for each category
1620: sub render_tools {
1621: my ($breadcrumbs) = @_;
1622: return unless (keys(%tools));
1623:
1624: my $navigation = list_from_array($tools{navigation},
1625: { listattr => { class=>"LC_breadcrumb_tools_navigation" } });
1626: my $tools = list_from_array($tools{tools},
1627: { listattr => { class=>"LC_breadcrumb_tools_tools" } });
1628: $$breadcrumbs = list_from_array([$navigation, $tools, $$breadcrumbs],
1629: { listattr => { class=>'LC_breadcrumb_tools_outerlist' } });
1630: }
1631:
1632: =item render_advtools(\$breadcrumbs)
1633:
1634: Creates html for advanced tools (category advtools) and inserts \$breadcrumbs
1635: at the correct position.
1636:
1637: input: \$breadcrumbs - a reference to the string containing prepared
1638: breadcrumbs (after render_tools call).
1639:
1640: returns: nothing
1641: =cut
1642:
1643: sub render_advtools {
1644: my ($breadcrumbs) = @_;
1645: return unless (defined $tools{'advtools'})
1646: and (scalar(@{$tools{'advtools'}}) > 0);
1647:
1648: $$breadcrumbs .= Apache::loncommon::head_subbox(
1649: funclist_from_array($tools{'advtools'}) );
1650: }
1651:
1652: } # End of scope for @Crumbs
1653:
1654: ############################################################
1655: ############################################################
1656:
1657: # Nested table routines.
1658: #
1659: # Routines to display form items in a multi-row table with 2 columns.
1660: # Uses nested tables to divide form elements into segments.
1661: # For examples of use see loncom/interface/lonnotify.pm
1662: #
1663: # Can be used in following order: ...
1664: # &start_pick_box()
1665: # row1
1666: # row2
1667: # row3 ... etc.
1668: # &submit_row()
1669: # &end_pick_box()
1670: #
1671: # where row1, row 2 etc. are chosen from &role_select_row,&course_select_row,
1672: # &status_select_row and &email_default_row
1673: #
1674: # Can also be used in following order:
1675: #
1676: # &start_pick_box()
1677: # &row_title()
1678: # &row_closure()
1679: # &row_title()
1680: # &row_closure() ... etc.
1681: # &submit_row()
1682: # &end_pick_box()
1683: #
1684: # In general a &submit_row() call should proceed the call to &end_pick_box(),
1685: # as this routine adds a button for form submission.
1686: # &submit_row() does not require a &row_closure after it.
1687: #
1688: # &start_pick_box() creates a bounding table with 1-pixel wide black border.
1689: # rows should be placed between calls to &start_pick_box() and &end_pick_box.
1690: #
1691: # &row_title() adds a title in the left column for each segment.
1692: # &row_closure() closes a row with a 1-pixel wide black line.
1693: #
1694: # &role_select_row() provides a select box from which to choose 1 or more roles
1695: # &course_select_row provides ways of picking groups of courses
1696: # radio buttons: all, by category or by picking from a course picker pop-up
1697: # note: by category option is only displayed if a domain has implemented
1698: # selection by year, semester, department, number etc.
1699: #
1700: # &status_select_row() provides a select box from which to choose 1 or more
1701: # access types (current access, prior access, and future access)
1702: #
1703: # &email_default_row() provides text boxes for default e-mail suffixes for
1704: # different authentication types in a domain.
1705: #
1706: # &row_title() and &row_closure() are called internally by the &*_select_row
1707: # routines, but can also be called directly to start and end rows which have
1708: # needs that are not accommodated by the *_select_row() routines.
1709:
1710: { # Start: row_count block for pick_box
1711: my @row_count;
1712:
1713: sub start_pick_box {
1714: my ($css_class) = @_;
1715: if (defined($css_class)) {
1716: $css_class = 'class="'.$css_class.'"';
1717: } else {
1718: $css_class= 'class="LC_pick_box"';
1719: }
1720: unshift(@row_count,0);
1721: my $output = <<"END";
1722: <table $css_class>
1723: END
1724: return $output;
1725: }
1726:
1727: sub end_pick_box {
1728: shift(@row_count);
1729: my $output = <<"END";
1730: </table>
1731: END
1732: return $output;
1733: }
1734:
1735: sub row_headline {
1736: my $output = <<"END";
1737: <tr><td colspan="2">
1738: END
1739: return $output;
1740: }
1741:
1742: sub row_title {
1743: my ($title,$css_title_class,$css_value_class, $css_value_furtherAttributes) = @_;
1744: $row_count[0]++;
1745: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1746: $css_title_class ||= 'LC_pick_box_title';
1747: $css_title_class = 'class="'.$css_title_class.'"';
1748:
1749: $css_value_class ||= 'LC_pick_box_value';
1750:
1751: if ($title ne '') {
1752: $title .= ':';
1753: }
1754: my $output = <<"ENDONE";
1755: <tr class="LC_pick_box_row" $css_value_furtherAttributes>
1756: <td $css_title_class>
1757: $title
1758: </td>
1759: <td class="$css_value_class $css_class">
1760: ENDONE
1761: return $output;
1762: }
1763:
1764: sub row_closure {
1765: my ($no_separator) =@_;
1766: my $output = <<"ENDTWO";
1767: </td>
1768: </tr>
1769: ENDTWO
1770: if (!$no_separator) {
1771: $output .= <<"ENDTWO";
1772: <tr>
1773: <td colspan="2" class="LC_pick_box_separator">
1774: </td>
1775: </tr>
1776: ENDTWO
1777: }
1778: return $output;
1779: }
1780:
1781: } # End: row_count block for pick_box
1782:
1783: sub role_select_row {
1784: my ($roles,$title,$css_class,$show_separate_custom,$cdom,$cnum) = @_;
1785: my $crstype = 'Course';
1786: if ($cdom ne '' && $cnum ne '') {
1787: $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
1788: }
1789: my $output;
1790: if (defined($title)) {
1791: $output = &row_title($title,$css_class);
1792: }
1793: $output .= qq|
1794: <select name="roles" multiple="multiple">\n|;
1795: foreach my $role (@$roles) {
1796: my $plrole;
1797: if ($role eq 'ow') {
1798: $plrole = &mt('Course Owner');
1799: } elsif ($role eq 'cr') {
1800: if ($show_separate_custom) {
1801: if ($cdom ne '' && $cnum ne '') {
1802: my %course_customroles = &course_custom_roles($cdom,$cnum);
1803: foreach my $crrole (sort(keys(%course_customroles))) {
1804: my ($plcrrole) = ($crrole =~ m|^cr/[^/]+/[^/]+/(.+)$|);
1805: $output .= ' <option value="'.$crrole.'">'.$plcrrole.
1806: '</option>';
1807: }
1808: }
1809: } else {
1810: $plrole = &mt('Custom Role');
1811: }
1812: } else {
1813: $plrole=&Apache::lonnet::plaintext($role,$crstype);
1814: }
1815: if (($role ne 'cr') || (!$show_separate_custom)) {
1816: $output .= ' <option value="'.$role.'">'.$plrole.'</option>';
1817: }
1818: }
1819: $output .= qq| </select>\n|;
1820: if (defined($title)) {
1821: $output .= &row_closure();
1822: }
1823: return $output;
1824: }
1825:
1826: sub course_select_row {
1827: my ($title,$formname,$totcodes,$codetitles,$idlist,$idlist_titles,
1828: $css_class,$crstype,$standardnames) = @_;
1829: my $output = &row_title($title,$css_class);
1830: $output .= &course_selection($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype,$standardnames);
1831: $output .= &row_closure();
1832: return $output;
1833: }
1834:
1835: sub course_selection {
1836: my ($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype,$standardnames) = @_;
1837: my $output = qq|
1838: <script type="text/javascript">
1839: // <![CDATA[
1840: function coursePick (formname) {
1841: for (var i=0; i<formname.coursepick.length; i++) {
1842: if (formname.coursepick[i].value == 'category') {
1843: courseSet('');
1844: }
1845: if (!formname.coursepick[i].checked) {
1846: if (formname.coursepick[i].value == 'specific') {
1847: formname.coursetotal.value = 0;
1848: formname.courselist = '';
1849: }
1850: }
1851: }
1852: }
1853: function setPick (formname) {
1854: for (var i=0; i<formname.coursepick.length; i++) {
1855: if (formname.coursepick[i].value == 'category') {
1856: formname.coursepick[i].checked = true;
1857: }
1858: formname.coursetotal.value = 0;
1859: formname.courselist = '';
1860: }
1861: }
1862: // ]]>
1863: </script>
1864: |;
1865:
1866: my ($allcrs,$pickspec);
1867: if ($crstype eq 'Community') {
1868: $allcrs = &mt('All communities');
1869: $pickspec = &mt('Pick specific communities:');
1870: } else {
1871: $allcrs = &mt('All courses');
1872: $pickspec = &mt('Pick specific course(s):');
1873: }
1874:
1875: my $courseform='<b>'.&Apache::loncommon::selectcourse_link
1876: ($formname,'pickcourse','pickdomain','coursedesc','',1,$crstype).'</b>';
1877: $output .= '<input type="radio" name="coursepick" value="all" onclick="coursePick(this.form)" />'.$allcrs.'<br />';
1878: if ($totcodes > 0) {
1879: my $numtitles = @$codetitles;
1880: if ($numtitles > 0) {
1881: $output .= '<input type="radio" name="coursepick" value="category" onclick="coursePick(this.form);alert('."'".&mt('Choose categories, from left to right')."'".')" />'.&mt('Pick courses by category:').' <br />';
1882: $output .= '<table><tr><td>'.$$codetitles[0].'<br />'."\n".
1883: '<select name="'.$standardnames->[0].
1884: '" onChange="setPick(this.form);courseSet('."'$$codetitles[0]'".')">'."\n".
1885: ' <option value="-1" />Select'."\n";
1886: my @items = ();
1887: my @longitems = ();
1888: if ($$idlist{$$codetitles[0]} =~ /","/) {
1889: @items = split(/","/,$$idlist{$$codetitles[0]});
1890: } else {
1891: $items[0] = $$idlist{$$codetitles[0]};
1892: }
1893: if (defined($$idlist_titles{$$codetitles[0]})) {
1894: if ($$idlist_titles{$$codetitles[0]} =~ /","/) {
1895: @longitems = split(/","/,$$idlist_titles{$$codetitles[0]});
1896: } else {
1897: $longitems[0] = $$idlist_titles{$$codetitles[0]};
1898: }
1899: for (my $i=0; $i<@longitems; $i++) {
1900: if ($longitems[$i] eq '') {
1901: $longitems[$i] = $items[$i];
1902: }
1903: }
1904: } else {
1905: @longitems = @items;
1906: }
1907: for (my $i=0; $i<@items; $i++) {
1908: $output .= ' <option value="'.$items[$i].'">'.$longitems[$i].'</option>';
1909: }
1910: $output .= '</select></td>';
1911: for (my $i=1; $i<$numtitles; $i++) {
1912: $output .= '<td>'.$$codetitles[$i].'<br />'."\n".
1913: '<select name="'.$standardnames->[$i].
1914: '" onChange="courseSet('."'$$codetitles[$i]'".')">'."\n".
1915: '<option value="-1"><-Pick '.$$codetitles[$i-1].'</option>'."\n".
1916: '</select>'."\n".
1917: '</td>';
1918: }
1919: $output .= '</tr></table><br />';
1920: }
1921: }
1922: $output .= '<input type="radio" name="coursepick" value="specific" onclick="coursePick(this.form);opencrsbrowser('."'".$formname."','dccourse','dcdomain','coursedesc','','1','$crstype'".')" />'.$pickspec.' '.$courseform.' <input type="text" value="0" size="4" name="coursetotal" /><input type="hidden" name="courselist" value="" />selected.<br />'."\n";
1923: return $output;
1924: }
1925:
1926: sub status_select_row {
1927: my ($types,$title,$css_class) = @_;
1928: my $output;
1929: if (defined($title)) {
1930: $output = &row_title($title,$css_class,'LC_pick_box_select');
1931: }
1932: $output .= qq|
1933: <select name="types" multiple="multiple">\n|;
1934: foreach my $status_type (sort(keys(%{$types}))) {
1935: $output .= ' <option value="'.$status_type.'">'.$$types{$status_type}.'</option>';
1936: }
1937: $output .= qq| </select>\n|;
1938: if (defined($title)) {
1939: $output .= &row_closure();
1940: }
1941: return $output;
1942: }
1943:
1944: sub email_default_row {
1945: my ($authtypes,$title,$descrip,$css_class) = @_;
1946: my $output = &row_title($title,$css_class);
1947: $output .= $descrip.
1948: &Apache::loncommon::start_data_table().
1949: &Apache::loncommon::start_data_table_header_row().
1950: '<th>'.&mt('Authentication Method').'</th>'.
1951: '<th align="right">'.&mt('Username -> e-mail conversion').'</th>'."\n".
1952: &Apache::loncommon::end_data_table_header_row();
1953: my $rownum = 0;
1954: foreach my $auth (sort(keys(%{$authtypes}))) {
1955: my ($userentry,$size);
1956: if ($auth =~ /^krb/) {
1957: $userentry = '';
1958: $size = 25;
1959: } else {
1960: $userentry = 'username@';
1961: $size = 15;
1962: }
1963: $output .= &Apache::loncommon::start_data_table_row().
1964: '<td> '.$$authtypes{$auth}.'</td>'.
1965: '<td align="right">'.$userentry.
1966: '<input type="text" name="'.$auth.'" size="'.$size.'" /></td>'.
1967: &Apache::loncommon::end_data_table_row();
1968: }
1969: $output .= &Apache::loncommon::end_data_table();
1970: $output .= &row_closure();
1971: return $output;
1972: }
1973:
1974:
1975: sub submit_row {
1976: my ($title,$cmd,$submit_text,$css_class) = @_;
1977: my $output = &row_title($title,$css_class,'LC_pick_box_submit');
1978: $output .= qq|
1979: <br />
1980: <input type="hidden" name="command" value="$cmd" />
1981: <input type="submit" value="$submit_text"/>
1982: <br /><br />
1983: \n|;
1984: return $output;
1985: }
1986:
1987: sub course_custom_roles {
1988: my ($cdom,$cnum) = @_;
1989: my %returnhash=();
1990: my %coursepersonnel=&Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
1991: foreach my $person (sort(keys(%coursepersonnel))) {
1992: my ($role) = ($person =~ /^([^:]+):/);
1993: my ($end,$start) = split(/:/,$coursepersonnel{$person});
1994: if ($end == -1 && $start == -1) {
1995: next;
1996: }
1997: if ($role =~ m|^cr/[^/]+/[^/]+/[^/]|) {
1998: $returnhash{$role} ++;
1999: }
2000: }
2001: return %returnhash;
2002: }
2003:
2004:
2005: sub resource_info_box {
2006: my ($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp)=@_;
2007: my $return='';
2008: if ($stuvcurrent ne '') {
2009: $return = '<div class="LC_left_float">';
2010: }
2011: if ($symb) {
2012: $return.=&Apache::loncommon::start_data_table();
2013: my ($map,$id,$resource)=&Apache::lonnet::decode_symb($symb);
2014: my $folder=&Apache::lonnet::gettitle($map);
2015: $return.=&Apache::loncommon::start_data_table_row().
2016: '<th align="left">'.&mt('Folder:').'</th><td>'.$folder.'</td>'.
2017: &Apache::loncommon::end_data_table_row();
2018: unless ($onlyfolderflag) {
2019: $return.=&Apache::loncommon::start_data_table_row().
2020: '<th align="left">'.&mt('Resource:').'</th><td>'.&Apache::lonnet::gettitle($symb).'</td>'.
2021: &Apache::loncommon::end_data_table_row();
2022: }
2023: if ($stuvcurrent ne '') {
2024: $return .= &Apache::loncommon::start_data_table_row().
2025: '<th align="left">'.&mt("Student's current version:").'</th><td>'.$stuvcurrent.'</td>'.
2026: &Apache::loncommon::end_data_table_row();
2027: }
2028: if ($stuvdisp ne '') {
2029: $return .= &Apache::loncommon::start_data_table_row().
2030: '<th align="left">'.&mt("Student's version displayed:").'</th><td>'.$stuvdisp.'</td>'.
2031: &Apache::loncommon::end_data_table_row();
2032: }
2033: $return.=&Apache::loncommon::end_data_table();
2034: } else {
2035: $return='<p><span class="LC_error">'.&mt('No context provided.').'</span></p>';
2036: }
2037: if ($stuvcurrent ne '') {
2038: $return .= '</div>';
2039: }
2040: return $return;
2041: }
2042:
2043: ##############################################
2044: ##############################################
2045:
2046: # topic_bar
2047: #
2048: # Generates a div containing an (optional) number with a white background followed by a
2049: # title with a background color defined in the corresponding CSS: LC_topic_bar
2050: # Inputs:
2051: # 1. number to display.
2052: # If input for number is empty only the title will be displayed.
2053: # 2. title text to display.
2054: # Outputs - a scalar containing html mark-up for the div.
2055:
2056: sub topic_bar {
2057: my ($num,$title) = @_;
2058: my $number = '';
2059: if ($num ne '') {
2060: $number = '<span>'.$num.'</span>';
2061: }
2062: return '<div class="LC_topic_bar">'.$number.$title.'</div>';
2063: }
2064:
2065: ##############################################
2066: ##############################################
2067: # echo_form_input
2068: #
2069: # Generates html markup to add form elements from the referrer page
2070: # as hidden form elements (values encoded) in the new page.
2071: #
2072: # Intended to support two types of use
2073: # (a) to allow backing up to earlier pages in a multi-page
2074: # form submission process using a breadcrumb trail.
2075: #
2076: # (b) to allow the current page to be reloaded with form elements
2077: # set on previous page to remain unchanged. An example would
2078: # be where the a page containing a dynamically-built table of data is
2079: # is to be redisplayed, with only the sort order of the data changed.
2080: #
2081: # Inputs:
2082: # 1. Reference to array of form elements in the submitted form on
2083: # the referrer page which are to be excluded from the echoed elements.
2084: #
2085: # 2. Reference to array of regular expressions, which if matched in the
2086: # name of the form element n the referrer page will be omitted from echo.
2087: #
2088: # Outputs: A scalar containing the html markup for the echoed form
2089: # elements (all as hidden elements, with values encoded).
2090:
2091:
2092: sub echo_form_input {
2093: my ($excluded,$regexps) = @_;
2094: my $output = '';
2095: foreach my $key (keys(%env)) {
2096: if ($key =~ /^form\.(.+)$/) {
2097: my $name = $1;
2098: my $match = 0;
2099: if (ref($excluded) eq 'ARRAY') {
2100: next if (grep(/^\Q$name\E$/,@{$excluded}));
2101: }
2102: if (ref($regexps) eq 'ARRAY') {
2103: if (@{$regexps} > 0) {
2104: foreach my $regexp (@{$regexps}) {
2105: if ($name =~ /$regexp/) {
2106: $match = 1;
2107: last;
2108: }
2109: }
2110: }
2111: }
2112: next if ($match);
2113: if (ref($env{$key}) eq 'ARRAY') {
2114: foreach my $value (@{$env{$key}}) {
2115: $value = &HTML::Entities::encode($value,'<>&"');
2116: $output .= '<input type="hidden" name="'.$name.
2117: '" value="'.$value.'" />'."\n";
2118: }
2119: } else {
2120: my $value = &HTML::Entities::encode($env{$key},'<>&"');
2121: $output .= '<input type="hidden" name="'.$name.
2122: '" value="'.$value.'" />'."\n";
2123: }
2124: }
2125: }
2126: return $output;
2127: }
2128:
2129: ##############################################
2130: ##############################################
2131: # set_form_elements
2132: #
2133: # Generates javascript to set form elements to values based on
2134: # corresponding values for the same form elements when the page was
2135: # previously submitted.
2136: #
2137: # Last submission values are read from hidden form elements in referring
2138: # page which have the same name, i.e., generated by &echo_form_input().
2139: #
2140: # Intended to be called by onload event.
2141: #
2142: # Inputs:
2143: # (a) Reference to hash of echoed form elements to be set.
2144: #
2145: # In the hash, keys are the form element names, and the values are the
2146: # element type (selectbox, radio, checkbox or text -for textbox, textarea or
2147: # hidden).
2148: #
2149: # (b) Optional reference to hash of stored elements to be set.
2150: #
2151: # If the page being displayed is a page which permits modification of
2152: # previously stored data, e.g., the first page in a multi-page submission,
2153: # then if stored is supplied, form elements will be set to the last stored
2154: # values. If user supplied values are also available for the same elements
2155: # these will replace the stored values.
2156: #
2157: # Output:
2158: #
2159: # javascript function - set_form_elements() which sets form elements,
2160: # expects an argument: formname - the name of the form according to
2161: # the DOM, e.g., document.compose
2162:
2163: sub set_form_elements {
2164: my ($elements,$stored) = @_;
2165: my %values;
2166: my $output .= 'function setFormElements(courseForm) {
2167: ';
2168: if (defined($stored)) {
2169: foreach my $name (keys(%{$stored})) {
2170: if (exists($$elements{$name})) {
2171: if (ref($$stored{$name}) eq 'ARRAY') {
2172: $values{$name} = $$stored{$name};
2173: } else {
2174: @{$values{$name}} = ($$stored{$name});
2175: }
2176: }
2177: }
2178: }
2179:
2180: foreach my $key (keys(%env)) {
2181: if ($key =~ /^form\.(.+)$/) {
2182: my $name = $1;
2183: if (exists($$elements{$name})) {
2184: @{$values{$name}} = &Apache::loncommon::get_env_multiple($key);
2185: }
2186: }
2187: }
2188:
2189: foreach my $name (keys(%values)) {
2190: for (my $i=0; $i<@{$values{$name}}; $i++) {
2191: $values{$name}[$i] = &HTML::Entities::decode($values{$name}[$i],'<>&"');
2192: $values{$name}[$i] =~ s/([\r\n\f]+)/\\n/g;
2193: $values{$name}[$i] =~ s/"/\\"/g;
2194: }
2195: if (($$elements{$name} eq 'text') || ($$elements{$name} eq 'hidden')) {
2196: my $numvalues = @{$values{$name}};
2197: if ($numvalues > 1) {
2198: my $valuestring = join('","',@{$values{$name}});
2199: $output .= qq|
2200: var textvalues = new Array ("$valuestring");
2201: var total = courseForm.elements['$name'].length;
2202: if (total > $numvalues) {
2203: total = $numvalues;
2204: }
2205: for (var i=0; i<total; i++) {
2206: courseForm.elements['$name']\[i].value = textvalues[i];
2207: }
2208: |;
2209: } else {
2210: $output .= qq|
2211: courseForm.elements['$name'].value = "$values{$name}[0]";
2212: |;
2213: }
2214: } else {
2215: $output .= qq|
2216: var elementLength = courseForm.elements['$name'].length;
2217: if (elementLength==undefined) {
2218: |;
2219: foreach my $value (@{$values{$name}}) {
2220: if ($$elements{$name} eq 'selectbox') {
2221: $output .= qq|
2222: if (courseForm.elements['$name'].options[0].value == "$value") {
2223: courseForm.elements['$name'].options[0].selected = true;
2224: }|;
2225: } elsif (($$elements{$name} eq 'radio') ||
2226: ($$elements{$name} eq 'checkbox')) {
2227: $output .= qq|
2228: if (courseForm.elements['$name'].value == "$value") {
2229: courseForm.elements['$name'].checked = true;
2230: } else {
2231: courseForm.elements['$name'].checked = false;
2232: }|;
2233: }
2234: }
2235: $output .= qq|
2236: }
2237: else {
2238: for (var i=0; i<courseForm.elements['$name'].length; i++) {
2239: |;
2240: if ($$elements{$name} eq 'selectbox') {
2241: $output .= qq|
2242: courseForm.elements['$name'].options[i].selected = false;|;
2243: } elsif (($$elements{$name} eq 'radio') ||
2244: ($$elements{$name} eq 'checkbox')) {
2245: $output .= qq|
2246: courseForm.elements['$name']\[i].checked = false;|;
2247: }
2248: $output .= qq|
2249: }
2250: for (var j=0; j<courseForm.elements['$name'].length; j++) {
2251: |;
2252: foreach my $value (@{$values{$name}}) {
2253: if ($$elements{$name} eq 'selectbox') {
2254: $output .= qq|
2255: if (courseForm.elements['$name'].options[j].value == "$value") {
2256: courseForm.elements['$name'].options[j].selected = true;
2257: }|;
2258: } elsif (($$elements{$name} eq 'radio') ||
2259: ($$elements{$name} eq 'checkbox')) {
2260: $output .= qq|
2261: if (courseForm.elements['$name']\[j].value == "$value") {
2262: courseForm.elements['$name']\[j].checked = true;
2263: }|;
2264: }
2265: }
2266: $output .= qq|
2267: }
2268: }
2269: |;
2270: }
2271: }
2272: $output .= "
2273: return;
2274: }\n";
2275: return $output;
2276: }
2277:
2278: ##############################################
2279: ##############################################
2280:
2281: sub file_submissionchk_js {
2282: my ($turninpaths,$multiples) = @_;
2283: my $overwritewarn = &mt('File(s) you uploaded for your submission will overwrite existing file(s) submitted for this item').'\\n'.
2284: &mt('Continue submission and overwrite the file(s)?');
2285: my $delfilewarn = &mt('You have indicated you wish to remove some files previously included in your submission.').'\\n'.
2286: &mt('Continue submission with these files removed?');
2287: my ($turninpathtext,$multtext,$arrayindexofjs);
2288: if (ref($turninpaths) eq 'HASH') {
2289: foreach my $key (sort(keys(%{$turninpaths}))) {
2290: $turninpathtext .= " if (prefix == '$key') {\n".
2291: " return '$turninpaths->{$key}';\n".
2292: " }\n";
2293: }
2294: }
2295: $turninpathtext .= " return '';\n";
2296: if (ref($multiples) eq 'HASH') {
2297: foreach my $key (sort(keys(%{$multiples}))) {
2298: $multtext .= " if (prefix == '$key') {\n".
2299: " return '$multiples->{$key}';\n".
2300: " }\n";
2301: }
2302: }
2303: $multtext .= " return '';\n";
2304:
2305: $arrayindexofjs = &Apache::loncommon::javascript_array_indexof();
2306: return <<"ENDSCRIPT";
2307: <script type="text/javascript">
2308: // <![CDATA[
2309:
2310: function file_submission_check(formname,path,multiresp) {
2311: var elemnum = formname.elements.length;
2312: if (elemnum == 0) {
2313: return true;
2314: }
2315: var alloverwrites = [];
2316: var alldelconfirm = [];
2317: var result = [];
2318: var submitter;
2319: var subprefix;
2320: var allsub = getIndexByName(formname,'all_submit');
2321: if (allsub == -1) {
2322: var idx = getIndexByName(formname,'submitted');
2323: if (idx != -1) {
2324: var subval = String(formname.elements[idx].value);
2325: submitter = subval.replace(/^part_/,'');
2326: result = overwritten_check(formname,path,multiresp,submitter);
2327: alloverwrites.push.apply(alloverwrites,result['overwrite']);
2328: alldelconfirm.push.apply(alldelconfirm,result['delete']);
2329: }
2330: } else {
2331: if (formname.elements[allsub].type == 'submit') {
2332: var partsub = /^\\d+\\.\\d+_submit_.+\$/;
2333: var allprefixes = [];
2334: var allparts = [];
2335: for (var i=0; i<formname.elements.length; i++) {
2336: if (formname.elements[i].type == 'submit') {
2337: var elemname = formname.elements[i].name;
2338: var subname = String(elemname);
2339: var savesub = String(elemname);
2340: if (partsub.test(subname)) {
2341: var prefix = subname.replace(/_submit_.+\$/,'');
2342: if (allprefixes.indexOf(prefix) == -1) {
2343: allprefixes.push(prefix);
2344: allparts[prefix] = [];
2345: }
2346: var part = savesub.replace(/^\\d+\\.\\d+_submit_/,'');
2347: allparts[prefix].push(part);
2348: }
2349: }
2350: }
2351: for (var k=0; k<allprefixes.length; k++) {
2352: var idx = getIndexByName(formname,allprefixes[k]+'_submitted');
2353: if (idx > -1) {
2354: if (formname.elements[idx].value != 'yes') {
2355: submitterval = formname.elements[idx].value;
2356: submitter = submitterval.replace(/^part_/,'');
2357: subprefix = allprefixes[k];
2358: result = overwritten_check(formname,path,multiresp,submitter,subprefix);
2359: alloverwrites.push.apply(alloverwrites,result['overwrite']);
2360: alldelconfirm.push.apply(alldelconfirm,result['delete']);
2361: break;
2362: }
2363: }
2364: }
2365: if (submitter == '' || submitter == undefined) {
2366: for (var m=0; m<allprefixes.length; m++) {
2367: for (var n=0; n<allparts[allprefixes[m]].length; n++) {
2368: var result = overwritten_check(formname,path,multiresp,allparts[allprefixes[m]][n],allprefixes[m]);
2369: alloverwrites.push.apply(alloverwrites,result['overwrite']);
2370: alldelconfirm.push.apply(alldelconfirm,result['delete']);
2371: }
2372: }
2373: }
2374: }
2375: }
2376: if (alloverwrites.length > 0) {
2377: if (!confirm("$overwritewarn")) {
2378: for (var n=0; n<alloverwrites.length; n++) {
2379: formname.elements[alloverwrites[n]].value = "";
2380: }
2381: return false;
2382: }
2383: }
2384: if (alldelconfirm.length > 0) {
2385: if (!confirm("$delfilewarn")) {
2386: for (var p=0; p<alldelconfirm.length; p++) {
2387: formname.elements[alldelconfirm[p]].checked = false;
2388: }
2389: return false;
2390: }
2391: }
2392: return true;
2393: }
2394:
2395: function getIndexByName(formname,item) {
2396: for (var i=0;i<formname.elements.length;i++) {
2397: if (formname.elements[i].name == item) {
2398: return i;
2399: }
2400: }
2401: return -1;
2402: }
2403:
2404: function overwritten_check(formname,path,multiresp,part,prefix) {
2405: var result = [];
2406: result['overwrite'] = [];
2407: result['delete'] = [];
2408: var elemnum = formname.elements.length;
2409: if (elemnum == 0) {
2410: return result;
2411: }
2412: var uploadstr;
2413: var deletestr;
2414: if ((prefix != undefined) && (prefix != '')) {
2415: var prepend = prefix+'_';
2416: uploadstr = new RegExp("^"+prepend+"HWFILE"+part+".+\$");
2417: deletestr = new RegExp("^"+prepend+"HWFILE"+part+".+_\\\\d+_delete\$");
2418: multiresp = check_for_multiples(prepend);
2419: path = check_for_turninpath(prepend);
2420: } else {
2421: uploadstr = new RegExp("^HWFILE"+part+".+\$");
2422: deletestr = new RegExp("^HWFILE"+part+".+_\\\\d+_delete\$");
2423: }
2424: var alluploads = [];
2425: var allchecked = [];
2426: var allskipdel = [];
2427: var fnametrim = /[^\\/\\\\]+\$/;
2428: for (var i=0; i<formname.elements.length; i++) {
2429: var id = formname.elements[i].id;
2430: if (id != '') {
2431: if (uploadstr.test(id)) {
2432: if (formname.elements[i].type == 'file') {
2433: alluploads.push(id);
2434: } else {
2435: if (deletestr.test(id)) {
2436: if (formname.elements[i].type == 'checkbox') {
2437: if (formname.elements[i].checked) {
2438: allchecked.push(id);
2439: }
2440: }
2441: }
2442: }
2443: }
2444: }
2445: }
2446: for (var j=0; j<alluploads.length; j++) {
2447: var delstr = new RegExp("^"+alluploads[j]+"_\\\\d+_delete\$");
2448: var delboxes = [];
2449: for (var k=0; k<formname.elements.length; k++) {
2450: var id = formname.elements[k].id;
2451: if ((id != '') && (id != undefined)) {
2452: if (delstr.test(id)) {
2453: if (formname.elements[k].type == 'checkbox') {
2454: delboxes.push(id);
2455: }
2456: }
2457: }
2458: }
2459: if (delboxes.length > 0) {
2460: if ((formname.elements[alluploads[j]].value != undefined) &&
2461: (formname.elements[alluploads[j]].value != '')) {
2462: var filepath = formname.elements[alluploads[j]].value;
2463: var newfilename = fnametrim.exec(filepath);
2464: if (newfilename != null) {
2465: var filename = String(newfilename);
2466: var nospaces = filename.replace(/\\s+/g,'_');
2467: var nospecials = nospaces.replace(/[^\\/\\w\\.\\-]/g,'');
2468: var cleanfilename = nospecials.replace(/\\.(\\d+\\.)/g,"_\$1");
2469: if (cleanfilename != '') {
2470: var fullpath = path+"/"+cleanfilename;
2471: if (multiresp == 1) {
2472: var partid = String(alluploads[i]);
2473: var subdir = partid.replace(/^\\d*.?\\d*_?HWFILE/,'');
2474: if (subdir != "" && subdir != undefined) {
2475: fullpath = path+"/"+subdir+"/"+cleanfilename;
2476: }
2477: }
2478: for (var m=0; m<delboxes.length; m++) {
2479: if (fullpath == formname.elements[delboxes[m]].value) {
2480: if (formname.elements[delboxes[m]].checked) {
2481: allskipdel.push(delboxes[m]);
2482: } else {
2483: result['overwrite'].push(alluploads[j]);
2484: }
2485: break;
2486: }
2487: }
2488: }
2489: }
2490: }
2491: }
2492: }
2493: if (allchecked.length > 0) {
2494: if (allskipdel.length > 0) {
2495: for (var n=0; n<allchecked.length; n++) {
2496: if (allskipdel.indexOf(allchecked[n]) == -1) {
2497: result['delete'].push(allchecked[n]);
2498: }
2499: }
2500: } else {
2501: result['delete'].push.apply(result['delete'],allchecked);
2502: }
2503: }
2504: return result;
2505: }
2506:
2507: function check_for_multiples(prefix) {
2508: $multtext
2509: }
2510:
2511: function check_for_turninpath(prefix) {
2512: $turninpathtext
2513: }
2514:
2515: // ]]>
2516: </script>
2517:
2518: $arrayindexofjs
2519:
2520: ENDSCRIPT
2521: }
2522:
2523: ##############################################
2524: ##############################################
2525:
2526: # javascript_valid_email
2527: #
2528: # Generates javascript to validate an e-mail address.
2529: # Returns a javascript function which accetps a form field as argumnent, and
2530: # returns false if field.value does not satisfy two regular expression matches
2531: # for a valid e-mail address. Backwards compatible with old browsers without
2532: # support for javascript RegExp (just checks for @ in field.value in this case).
2533:
2534: sub javascript_valid_email {
2535: my $scripttag .= <<'END';
2536: function validmail(field) {
2537: var str = field.value;
2538: if (window.RegExp) {
2539: var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
2540: var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$"; //"
2541: var reg1 = new RegExp(reg1str);
2542: var reg2 = new RegExp(reg2str);
2543: if (!reg1.test(str) && reg2.test(str)) {
2544: return true;
2545: }
2546: return false;
2547: }
2548: else
2549: {
2550: if(str.indexOf("@") >= 0) {
2551: return true;
2552: }
2553: return false;
2554: }
2555: }
2556: END
2557: return $scripttag;
2558: }
2559:
2560:
2561: # USAGE: htmltag(element, content, {attribute => value,...});
2562: #
2563: # EXAMPLES:
2564: # - htmltag('a', 'this is an anchor', {href => 'www.example.com',
2565: # title => 'this is a title'})
2566: #
2567: # - You might want to set up needed tags like:
2568: #
2569: # my $h3 = sub { return htmltag( "h3", @_ ) };
2570: #
2571: # ... and use them: $h3->("This is a headline")
2572: #
2573: # - To set up a couple of tags, see sub inittags
2574: #
2575: # NOTES:
2576: # - Empty elements, such as <br/> are correctly terminated,
2577: # i.e. htmltag('br') returns <br/>
2578: # - Empty attributes (title="") are filtered out.
2579: # - The function will not check for deprecated attributes.
2580: #
2581: # OUTPUT: content enclosed in xhtml conform tags
2582: sub htmltag{
2583: return
2584: qq|<$_[0]|
2585: . join( '', map { qq| $_="${$_[2]}{$_}"| if ${$_[2]}{$_} } keys %{ $_[2] } )
2586: . ($_[1] ? qq|>$_[1]</$_[0]>| : qq|/>|). "\n";
2587: };
2588:
2589:
2590: # USAGE: inittags(@tags);
2591: #
2592: # EXAMPLES:
2593: # - my ($h1, $h2, $h3) = inittags( qw( h1 h2 h3 ) )
2594: # $h1->("This is a headline") #Returns: <h1>This is a headline</h1>
2595: #
2596: # NOTES: See sub htmltag for further information.
2597: #
2598: # OUTPUT: List of subroutines.
2599: sub inittags {
2600: my @tags = @_;
2601: return map { my $tag = $_;
2602: sub { return htmltag( $tag, @_ ) }
2603: } @tags;
2604: }
2605:
2606:
2607: # USAGE: scripttag(scriptcode, [start|end|both]);
2608: #
2609: # EXAMPLES:
2610: # - scripttag("alert('Hello World!')", 'both')
2611: # returns:
2612: # <script type="text/javascript">
2613: # // BEGIN LON-CAPA Internal
2614: # alert(Hello World!')
2615: # // END LON-CAPA Internal
2616: # </script>
2617: #
2618: # NOTES:
2619: # - works currently only for javascripts
2620: #
2621: # OUTPUT:
2622: # Scriptcode properly enclosed in <script> and CDATA tags (and LC
2623: # Internal markers if 2nd argument is given)
2624: sub scripttag {
2625: my ( $content, $marker ) = @_;
2626: return unless defined $content;
2627:
2628: my $begin = "\n// BEGIN LON-CAPA Internal\n";
2629: my $end = "\n// END LON-CAPA Internal\n";
2630:
2631: if ($marker) {
2632: $content = $begin . $content if $marker eq 'start' or $marker eq 'both';
2633: $content .= $end if $marker eq 'end' or $marker eq 'both';
2634: }
2635:
2636: $content = "\n// <![CDATA[\n$content\n// ]]>\n";
2637:
2638: return htmltag('script', $content, {type => 'text/javascript'});
2639: };
2640:
2641:
2642: =item list_from_array( \@array, { listattr =>{}, itemattr =>{} } )
2643:
2644: Constructs a XHTML list from \@array.
2645:
2646: input:
2647:
2648: =over
2649:
2650: =item \@array
2651:
2652: A reference to the array containing text that will be wrapped in <li></li> tags.
2653:
2654: =item { listattr => {}, itemattr =>{} }
2655:
2656: Attributes for <ul> and <li> passed in as hash references.
2657: See htmltag() for more details.
2658:
2659: =back
2660:
2661: returns: XHTML list as String.
2662:
2663: =cut
2664:
2665: # \@items, {listattr => { class => 'abc', id => 'xyx' }, itemattr => {class => 'abc', id => 'xyx'}}
2666: sub list_from_array {
2667: my ($items, $args) = @_;
2668: return unless (ref($items) eq 'ARRAY');
2669: return unless scalar @$items;
2670: my ($ul, $li) = inittags( qw(ul li) );
2671: my $listitems = join '', map { $li->($_, $args->{itemattr}) } @$items;
2672: return $ul->( $listitems, $args->{listattr} );
2673: }
2674:
2675:
2676: ##############################################
2677: ##############################################
2678:
2679: # generate_menu
2680: #
2681: # Generates html markup for a menu.
2682: #
2683: # Inputs:
2684: # An array of following structure:
2685: # ({ categorytitle => 'Categorytitle',
2686: # items => [
2687: # {
2688: # linktext => 'Text to be displayed',
2689: # url => 'URL the link is pointing to, i.e. /adm/site?action=dosomething',
2690: # permission => 'Contains permissions as returned from lonnet::allowed(),
2691: # must evaluate to true in order to activate the link',
2692: # icon => 'icon filename',
2693: # alttext => 'alt text for the icon',
2694: # help => 'Name of the corresponding helpfile',
2695: # linktitle => 'Description of the link (used for title tag)'
2696: # },
2697: # ...
2698: # ]
2699: # },
2700: # ...
2701: # )
2702: #
2703: # Outputs: A scalar containing the html markup for the menu.
2704:
2705: sub generate_menu {
2706: my @menu = @_;
2707: # subs for specific html elements
2708: my ($h3, $div, $ul, $li, $a, $img) = inittags( qw(h3 div ul li a img) );
2709:
2710: my @categories; # each element represents the entire markup for a category
2711:
2712: foreach my $category (@menu) {
2713: my @links; # contains the links for the current $category
2714: foreach my $link (@{$$category{items}}) {
2715: next unless $$link{permission};
2716:
2717: # create the markup for the current $link and push it into @links.
2718: # each entry consists of an image and a text optionally followed
2719: # by a help link.
2720: my $src;
2721: if ($$link{icon} ne '') {
2722: $src = '/res/adm/pages/'.$$link{icon};
2723: }
2724: push(@links,$li->(
2725: $a->(
2726: $img->("", {
2727: class => "LC_noBorder LC_middle",
2728: src => $src,
2729: alt => mt(defined($$link{alttext}) ?
2730: $$link{alttext} : $$link{linktext})
2731: }), {
2732: href => $$link{url},
2733: title => mt($$link{linktitle})
2734: }).
2735: $a->(mt($$link{linktext}), {
2736: href => $$link{url},
2737: title => mt($$link{linktitle}),
2738: class => "LC_menubuttons_link"
2739: }).
2740: (defined($$link{help}) ?
2741: Apache::loncommon::help_open_topic($$link{help}) : ''),
2742: {class => "LC_menubuttons_inline_text"}));
2743: }
2744:
2745: # wrap categorytitle in <h3>, concatenate with
2746: # joined and in <ul> tags wrapped @links
2747: # and wrap everything in an enclosing <div> and push it into
2748: # @categories
2749: # such that each element looks like:
2750: # <div><h3>title</h3><ul><li>...</li>...</ul></div>
2751: # the category won't be added if there aren't any links
2752: push(@categories,
2753: $div->($h3->(mt($$category{categorytitle}), {class=>"LC_hcell"}).
2754: $ul->(join('' ,@links), {class =>"LC_ListStyleNormal" }),
2755: {class=>"LC_Box LC_400Box"})) if scalar(@links);
2756: }
2757:
2758: # wrap the joined @categories in another <div> (column layout)
2759: return $div->(join('', @categories), {class => "LC_columnSection"});
2760: }
2761:
2762: ##############################################
2763: ##############################################
2764:
2765: =pod
2766:
2767: =item &start_funclist
2768:
2769: Start list of available functions
2770:
2771: Typically used to offer a simple list of available functions
2772: at top or bottom of page.
2773: All available functions/actions for the current page
2774: should be included in this list.
2775:
2776: If the optional headline text is not provided, a default text will be used.
2777:
2778:
2779: Related routines:
2780: =over 4
2781: add_item_funclist
2782: end_funclist
2783: =back
2784:
2785:
2786: Inputs: (optional) headline text
2787:
2788: Returns: HTML code with function list start
2789:
2790: =cut
2791:
2792: ##############################################
2793: ##############################################
2794:
2795: sub start_funclist {
2796: my($legendtext)=@_;
2797: $legendtext=&mt('Functions') if !$legendtext;
2798: return '<ul class="LC_funclist"><li style="font-weight:bold; margin-left:0.8em;">'.$legendtext.'</li>'."\n";
2799: }
2800:
2801:
2802: ##############################################
2803: ##############################################
2804:
2805: =pod
2806:
2807: =item &add_item_funclist
2808:
2809: Adds an item to the list of available functions
2810:
2811: Related routines:
2812: =over 4
2813: start_funclist
2814: end_funclist
2815: =back
2816:
2817: Inputs: content item with text and link to function
2818:
2819: Returns: HTML code with list item for funclist
2820:
2821: =cut
2822:
2823: ##############################################
2824: ##############################################
2825:
2826: sub add_item_funclist {
2827: my($content) = @_;
2828: return '<li>'.$content.'</li>'."\n";
2829: }
2830:
2831: =pod
2832:
2833: =item &end_funclist
2834:
2835: End list of available functions
2836:
2837: Related routines:
2838: =over 4
2839: start_funclist
2840: add_item_funclist
2841: =back
2842:
2843: Inputs: ./.
2844:
2845: Returns: HTML code with function list end
2846: =cut
2847:
2848: sub end_funclist {
2849: return "</ul>\n";
2850: }
2851:
2852: =pod
2853:
2854: =item funclist_from_array( \@array, {legend => 'text for legend'} )
2855:
2856: Constructs a XHTML list from \@array with the first item being visually
2857: highlighted and set to the value of legend or 'Functions' if legend is
2858: empty.
2859:
2860: =over
2861:
2862: =item \@array
2863:
2864: A reference to the array containing text that will be wrapped in <li></li> tags.
2865:
2866: =item { legend => 'text' }
2867:
2868: A string that's used as visually highlighted first item. 'Functions' is used if
2869: it's value evaluates to false.
2870:
2871: =back
2872:
2873: returns: XHTML list as string.
2874:
2875: =back
2876:
2877: =cut
2878:
2879: sub funclist_from_array {
2880: my ($items, $args) = @_;
2881: return unless(ref($items) eq 'ARRAY');
2882: $args->{legend} ||= mt('Functions');
2883: return list_from_array( [$args->{legend}, @$items],
2884: { listattr => {class => 'LC_funclist'} });
2885: }
2886:
2887: 1;
2888:
2889: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>