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