File:
[LON-CAPA] /
loncom /
interface /
lonhtmlcommon.pm
Revision
1.177:
download - view:
text,
annotated -
select for diffs
Mon Jul 28 05:25:59 2008 UTC (16 years ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Separate code used to create button and code used to generate javascript
fired by button click.
- Rename routines as &dragmath_button() and &dragmath_js().
- Only include javascript used to launch DragMath pop-up once in Colorful editor screen.
- Do not include Edit Math button when WYSIWYG is on ("Render Latex" button in pop-up was not writing to textarea in this case) - need to integrate Drag Math into FCKedit for this situation.
- Add contextual help for Edit Math button
- Move "Edit Math" button in "EditXML" mode.
1: # The LearningOnline Network with CAPA
2: # a pile of common html routines
3: #
4: # $Id: lonhtmlcommon.pm,v 1.177 2008/07/28 05:25:59 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 LONCAPA;
64:
65:
66: ##############################################
67: ##############################################
68:
69: =pod
70:
71: =item dragmath_button
72:
73: Creates a button that launches a dragmath popup-window, in which an
74: expression can be edited and pasted as LaTeX into a specified textarea.
75:
76: textarea - Name of the textarea to edit.
77: helpicon - If true, show a help icon to the right of the button.
78:
79: =cut
80:
81: sub dragmath_button {
82: my ($textarea,$helpicon) = @_;
83: my $help_text;
84: if ($helpicon) {
85: $help_text = &Apache::loncommon::help_open_topic('Authoring_Math_Editor');
86: }
87: return <<ENDDRAGMATH;
88: <input type="button" value="Edit Math", onclick="javascript:mathedit('$textarea',document)" />$help_text
89: ENDDRAGMATH
90: }
91:
92: ##############################################
93:
94: =pod
95:
96: =item dragmath_js
97:
98: Javascript used to open pop-up window containing dragmath applet which
99: can be used to paste LaTeX into a textarea.
100:
101: =cut
102:
103: sub dragmath_js {
104: return <<ENDDRAGMATHJS;
105: <script type="text/javascript">
106: function mathedit(textarea, doc) {
107: targetEntry = textarea;
108: targetDoc = doc;
109: newwin = window.open("/adm/dragmath/applet/EditMathPopup.html","","width=565,height=500,resizable");
110: }
111: </script>
112:
113: ENDDRAGMATHJS
114: }
115:
116: ##############################################
117: ##############################################
118:
119: =pod
120:
121: =item authorbombs
122:
123: =cut
124:
125: ##############################################
126: ##############################################
127:
128: sub authorbombs {
129: my $url=shift;
130: $url=&Apache::lonnet::declutter($url);
131: my ($udom,$uname)=($url=~m{^($LONCAPA::domain_re)/($LONCAPA::username_re)/});
132: my %bombs=&Apache::lonmsg::all_url_author_res_msg($uname,$udom);
133: foreach (keys %bombs) {
134: if ($_=~/^$udom\/$uname\//) {
135: return '<a href="/adm/bombs/'.$url.
136: '"><img src="'.&Apache::loncommon::lonhttpdurl('/adm/lonMisc/bomb.gif').'" border="0" /></a>'.
137: &Apache::loncommon::help_open_topic('About_Bombs');
138: }
139: }
140: return '';
141: }
142:
143: ##############################################
144: ##############################################
145:
146: sub recent_filename {
147: my $area=shift;
148: return 'nohist_recent_'.&escape($area);
149: }
150:
151: sub store_recent {
152: my ($area,$name,$value,$freeze)=@_;
153: my $file=&recent_filename($area);
154: my %recent=&Apache::lonnet::dump($file);
155: if (scalar(keys(%recent))>20) {
156: # remove oldest value
157: my $oldest=time();
158: my $delkey='';
159: foreach my $item (keys(%recent)) {
160: my $thistime=(split(/\&/,$recent{$item}))[0];
161: if (($thistime ne "always_include") && ($thistime<$oldest)) {
162: $oldest=$thistime;
163: $delkey=$item;
164: }
165: }
166: &Apache::lonnet::del($file,[$delkey]);
167: }
168: # store new value
169: my $timestamp;
170: if ($freeze) {
171: $timestamp = "always_include";
172: } else {
173: $timestamp = time();
174: }
175: &Apache::lonnet::put($file,{ $name =>
176: $timestamp.'&'.&escape($value) });
177: }
178:
179: sub remove_recent {
180: my ($area,$names)=@_;
181: my $file=&recent_filename($area);
182: return &Apache::lonnet::del($file,$names);
183: }
184:
185: sub select_recent {
186: my ($area,$fieldname,$event)=@_;
187: my %recent=&Apache::lonnet::dump(&recent_filename($area));
188: my $return="\n<select name='$fieldname'".
189: ($event?" onchange='$event'":'').
190: ">\n<option value=''>--- ".&mt('Recent')." ---</option>";
191: foreach my $value (sort(keys(%recent))) {
192: unless ($value =~/^error\:/) {
193: my $escaped = &Apache::loncommon::escape_url($value);
194: &Apache::loncommon::inhibit_menu_check(\$escaped);
195: $return.="\n<option value='$escaped'>".
196: &unescape((split(/\&/,$recent{$value}))[1]).
197: '</option>';
198: }
199: }
200: $return.="\n</select>\n";
201: return $return;
202: }
203:
204: sub get_recent {
205: my ($area, $n) = @_;
206: my %recent=&Apache::lonnet::dump(&recent_filename($area));
207:
208: # Create hash with key as time and recent as value
209: # Begin filling return_hash with any 'always_include' option
210: my %time_hash = ();
211: my %return_hash = ();
212: foreach my $item (keys %recent) {
213: my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
214: if ($thistime eq 'always_include') {
215: $return_hash{$item} = &unescape($thisvalue);
216: $n--;
217: } else {
218: $time_hash{$thistime} = $item;
219: }
220: }
221:
222: # Sort by decreasing time and return key value pairs
223: my $idx = 1;
224: foreach my $item (reverse(sort(keys(%time_hash)))) {
225: $return_hash{$time_hash{$item}} =
226: &unescape((split(/\&/,$recent{$time_hash{$item}}))[1]);
227: if ($n && ($idx++ >= $n)) {last;}
228: }
229:
230: return %return_hash;
231: }
232:
233: sub get_recent_frozen {
234: my ($area) = @_;
235: my %recent=&Apache::lonnet::dump(&recent_filename($area));
236:
237: # Create hash with all 'frozen' items
238: my %return_hash = ();
239: foreach my $item (keys(%recent)) {
240: my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
241: if ($thistime eq 'always_include') {
242: $return_hash{$item} = &unescape($thisvalue);
243: }
244: }
245: return %return_hash;
246: }
247:
248:
249:
250: =pod
251:
252: =item textbox
253:
254: =cut
255:
256: ##############################################
257: ##############################################
258: sub textbox {
259: my ($name,$value,$size,$special) = @_;
260: $size = 40 if (! defined($size));
261: $value = &HTML::Entities::encode($value,'<>&"');
262: my $Str = '<input type="text" name="'.$name.'" size="'.$size.'" '.
263: 'value="'.$value.'" '.$special.' />';
264: return $Str;
265: }
266:
267: ##############################################
268: ##############################################
269:
270: =pod
271:
272: =item checkbox
273:
274: =cut
275:
276: ##############################################
277: ##############################################
278: sub checkbox {
279: my ($name,$checked,$value) = @_;
280: my $Str = '<input type="checkbox" name="'.$name.'" ';
281: if (defined($value)) {
282: $Str .= 'value="'.$value.'"';
283: }
284: if ($checked) {
285: $Str .= ' checked="1"';
286: }
287: $Str .= ' />';
288: return $Str;
289: }
290:
291:
292: =pod
293:
294: =item radiobutton
295:
296: =cut
297:
298: ##############################################
299: ##############################################
300: sub radio {
301: my ($name,$checked,$value) = @_;
302: my $Str = '<input type="radio" name="'.$name.'" ';
303: if (defined($value)) {
304: $Str .= 'value="'.$value.'"';
305: }
306: if ($checked eq $value) {
307: $Str .= ' checked="1"';
308: }
309: $Str .= ' />';
310: return $Str;
311: }
312:
313: ##############################################
314: ##############################################
315:
316: =pod
317:
318: =item &date_setter
319:
320: &date_setter returns html and javascript for a compact date-setting form.
321: To retrieve values from it, use &get_date_from_form().
322:
323: Inputs
324:
325: =over 4
326:
327: =item $dname
328:
329: The name to prepend to the form elements.
330: The form elements defined will be dname_year, dname_month, dname_day,
331: dname_hour, dname_min, and dname_sec.
332:
333: =item $currentvalue
334:
335: The current setting for this time parameter. A unix format time
336: (time in seconds since the beginning of Jan 1st, 1970, GMT.
337: An undefined value is taken to indicate the value is the current time.
338: Also, to be explicit, a value of 'now' also indicates the current time.
339:
340: =item $special
341:
342: Additional html/javascript to be associated with each element in
343: the date_setter. See lonparmset for example usage.
344:
345: =item $includeempty
346:
347: =item $state
348:
349: Specifies the initial state of the form elements. Either 'disabled' or empty.
350: Defaults to empty, which indiciates the form elements are not disabled.
351:
352: =back
353:
354: Bugs
355:
356: The method used to restrict user input will fail in the year 2400.
357:
358: =cut
359:
360: ##############################################
361: ##############################################
362: sub date_setter {
363: my ($formname,$dname,$currentvalue,$special,$includeempty,$state,
364: $no_hh_mm_ss,$defhour,$defmin,$defsec,$nolink) = @_;
365: my $now = time;
366: my $wasdefined=1;
367: if (! defined($state) || $state ne 'disabled') {
368: $state = '';
369: }
370: if (! defined($no_hh_mm_ss)) {
371: $no_hh_mm_ss = 0;
372: }
373: if ($currentvalue eq 'now') {
374: $currentvalue = $now;
375: }
376: if ((!defined($currentvalue)) || ($currentvalue eq '')) {
377: $wasdefined=0;
378: if ($includeempty) {
379: $currentvalue = 0;
380: } else {
381: $currentvalue = $now;
382: }
383: }
384: # other potentially useful values: wkday,yrday,is_daylight_savings
385: my $tzname;
386: my ($sec,$min,$hour,$mday,$month,$year)=('','',undef,'','','');
387: if ($currentvalue) {
388: ($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($currentvalue);
389: }
390: unless ($wasdefined) {
391: ($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($now);
392: if (($defhour) || ($defmin) || ($defsec)) {
393: $sec=($defsec?$defsec:0);
394: $min=($defmin?$defmin:0);
395: $hour=($defhour?$defhour:0);
396: } elsif (!$includeempty) {
397: $sec=0;
398: $min=0;
399: $hour=0;
400: }
401: }
402: my $result = "\n<!-- $dname date setting form -->\n";
403: $result .= <<ENDJS;
404: <script type="text/javascript">
405: function $dname\_checkday() {
406: var day = document.$formname.$dname\_day.value;
407: var month = document.$formname.$dname\_month.value;
408: var year = document.$formname.$dname\_year.value;
409: var valid = true;
410: if (day < 1) {
411: document.$formname.$dname\_day.value = 1;
412: }
413: if (day > 31) {
414: document.$formname.$dname\_day.value = 31;
415: }
416: if ((month == 1) || (month == 3) || (month == 5) ||
417: (month == 7) || (month == 8) || (month == 10) ||
418: (month == 12)) {
419: if (day > 31) {
420: document.$formname.$dname\_day.value = 31;
421: day = 31;
422: }
423: } else if (month == 2 ) {
424: if ((year % 4 == 0) && (year % 100 != 0)) {
425: if (day > 29) {
426: document.$formname.$dname\_day.value = 29;
427: }
428: } else if (day > 29) {
429: document.$formname.$dname\_day.value = 28;
430: }
431: } else if (day > 30) {
432: document.$formname.$dname\_day.value = 30;
433: }
434: }
435:
436: function $dname\_disable() {
437: document.$formname.$dname\_month.disabled=true;
438: document.$formname.$dname\_day.disabled=true;
439: document.$formname.$dname\_year.disabled=true;
440: document.$formname.$dname\_hour.disabled=true;
441: document.$formname.$dname\_minute.disabled=true;
442: document.$formname.$dname\_second.disabled=true;
443: }
444:
445: function $dname\_enable() {
446: document.$formname.$dname\_month.disabled=false;
447: document.$formname.$dname\_day.disabled=false;
448: document.$formname.$dname\_year.disabled=false;
449: document.$formname.$dname\_hour.disabled=false;
450: document.$formname.$dname\_minute.disabled=false;
451: document.$formname.$dname\_second.disabled=false;
452: }
453:
454: function $dname\_opencalendar() {
455: if (! document.$formname.$dname\_month.disabled) {
456: var calwin=window.open(
457: "/adm/announcements?pickdate=yes&formname=$formname&element=$dname&month="+
458: document.$formname.$dname\_month.value+"&year="+
459: document.$formname.$dname\_year.value,
460: "LONCAPAcal",
461: "height=350,width=350,scrollbars=yes,resizable=yes,menubar=no");
462: }
463:
464: }
465: </script>
466: ENDJS
467: $result .= ' <span style="white-space: nowrap;">';
468: my $monthselector = qq{<select name="$dname\_month" $special $state onchange="javascript:$dname\_checkday()" >};
469: # Month
470: my @Months = qw/January February March April May June
471: July August September October November December/;
472: # Pad @Months with a bogus value to make indexing easier
473: unshift(@Months,'If you can read this an error occurred');
474: if ($includeempty) { $monthselector.="<option value=''></option>"; }
475: for(my $m = 1;$m <=$#Months;$m++) {
476: $monthselector .= qq{ <option value="$m" };
477: $monthselector .= "selected " if ($m-1 eq $month);
478: $monthselector .= '> '.&mt($Months[$m]).' </option>';
479: }
480: $monthselector.= ' </select>';
481: # Day
482: my $dayselector = qq{<input type="text" name="$dname\_day" $state value="$mday" size="3" $special onchange="javascript:$dname\_checkday()" />};
483: # Year
484: my $yearselector = qq{<input type="year" name="$dname\_year" $state value="$year" size="5" $special onchange="javascript:$dname\_checkday()" />};
485: #
486: my $hourselector = qq{<select name="$dname\_hour" $special $state >};
487: if ($includeempty) {
488: $hourselector.=qq{<option value=''></option>};
489: }
490: for (my $h = 0;$h<24;$h++) {
491: $hourselector .= qq{<option value="$h" };
492: $hourselector .= "selected " if (defined($hour) && $hour == $h);
493: $hourselector .= ">";
494: my $timest='';
495: if ($h == 0) {
496: $timest .= "12 am";
497: } elsif($h == 12) {
498: $timest .= "12 noon";
499: } elsif($h < 12) {
500: $timest .= "$h am";
501: } else {
502: $timest .= $h-12 ." pm";
503: }
504: $timest=&mt($timest);
505: $hourselector .= $timest." </option>\n";
506: }
507: $hourselector .= " </select>\n";
508: my $minuteselector = qq{<input type="text" name="$dname\_minute" $special $state value="$min" size="3" />};
509: my $secondselector= qq{<input type="text" name="$dname\_second" $special $state value="$sec" size="3" />};
510: my $cal_link;
511: if (!$nolink) {
512: $cal_link = qq{<a href="javascript:$dname\_opencalendar()">};
513: }
514: #
515: my $tzone = ' '.$tzname.' ';
516: if ($no_hh_mm_ss) {
517: $result .= &mt('[_1] [_2] [_3] ',
518: $monthselector,$dayselector,$yearselector).
519: $tzone;
520: if (!$nolink) {
521: $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
522: }
523: } else {
524: $result .= &mt('[_1] [_2] [_3] [_4] [_5]m [_6]s ',
525: $monthselector,$dayselector,$yearselector,
526: $hourselector,$minuteselector,$secondselector).
527: $tzone;
528: if (!$nolink) {
529: $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
530: }
531: }
532: $result .= "</span>\n<!-- end $dname date setting form -->\n";
533: return $result;
534: }
535:
536: sub get_timedates {
537: my ($epoch) = @_;
538: my $dt = DateTime->from_epoch(epoch => $epoch)
539: ->set_time_zone(&Apache::lonlocal::gettimezone());
540: my $tzname = $dt->time_zone_short_name();
541: my $sec = $dt->second;
542: my $min = $dt->minute;
543: my $hour = $dt->hour;
544: my $mday = $dt->day;
545: my $month = $dt->month;
546: if ($month) {
547: $month --;
548: }
549: my $year = $dt->year;
550: return ($tzname,$sec,$min,$hour,$mday,$month,$year);
551: }
552:
553: sub build_url {
554: my ($base, $fields)=@_;
555: my $url;
556: $url = $base.'?';
557: foreach my $key (keys(%$fields)) {
558: $url.=&escape($key).'='.&escape($$fields{$key}).'&';
559: }
560: $url =~ s/&$//;
561: return $url;
562: }
563:
564:
565: ##############################################
566: ##############################################
567:
568: =pod
569:
570: =item &get_date_from_form
571:
572: get_date_from_form retrieves the date specified in an &date_setter form.
573:
574: Inputs:
575:
576: =over 4
577:
578: =item $dname
579:
580: The name passed to &datesetter, which prefixes the form elements.
581:
582: =item $defaulttime
583:
584: The unix time to use as the default in case of poor inputs.
585:
586: =back
587:
588: Returns: Unix time represented in the form.
589:
590: =cut
591:
592: ##############################################
593: ##############################################
594: sub get_date_from_form {
595: my ($dname) = @_;
596: my ($sec,$min,$hour,$day,$month,$year);
597: #
598: if (defined($env{'form.'.$dname.'_second'})) {
599: my $tmpsec = $env{'form.'.$dname.'_second'};
600: if (($tmpsec =~ /^\d+$/) && ($tmpsec >= 0) && ($tmpsec < 60)) {
601: $sec = $tmpsec;
602: }
603: if (!defined($tmpsec) || $tmpsec eq '') { $sec = 0; }
604: } else {
605: $sec = 0;
606: }
607: if (defined($env{'form.'.$dname.'_minute'})) {
608: my $tmpmin = $env{'form.'.$dname.'_minute'};
609: if (($tmpmin =~ /^\d+$/) && ($tmpmin >= 0) && ($tmpmin < 60)) {
610: $min = $tmpmin;
611: }
612: if (!defined($tmpmin) || $tmpmin eq '') { $min = 0; }
613: } else {
614: $min = 0;
615: }
616: if (defined($env{'form.'.$dname.'_hour'})) {
617: my $tmphour = $env{'form.'.$dname.'_hour'};
618: if (($tmphour =~ /^\d+$/) && ($tmphour >= 0) && ($tmphour < 24)) {
619: $hour = $tmphour;
620: }
621: } else {
622: $hour = 0;
623: }
624: if (defined($env{'form.'.$dname.'_day'})) {
625: my $tmpday = $env{'form.'.$dname.'_day'};
626: if (($tmpday =~ /^\d+$/) && ($tmpday > 0) && ($tmpday < 32)) {
627: $day = $tmpday;
628: }
629: }
630: if (defined($env{'form.'.$dname.'_month'})) {
631: my $tmpmonth = $env{'form.'.$dname.'_month'};
632: if (($tmpmonth =~ /^\d+$/) && ($tmpmonth > 0) && ($tmpmonth < 13)) {
633: $month = $tmpmonth;
634: }
635: }
636: if (defined($env{'form.'.$dname.'_year'})) {
637: my $tmpyear = $env{'form.'.$dname.'_year'};
638: if (($tmpyear =~ /^\d+$/) && ($tmpyear >= 1970)) {
639: $year = $tmpyear;
640: }
641: }
642: if (($year<1970) || ($year>2037)) { return undef; }
643: if (defined($sec) && defined($min) && defined($hour) &&
644: defined($day) && defined($month) && defined($year)) {
645: my $timezone = &Apache::lonlocal::gettimezone();
646: my $dt = DateTime->new( year => $year,
647: month => $month,
648: day => $day,
649: hour => $hour,
650: minute => $min,
651: second => $sec,
652: time_zone => $timezone,
653: );
654: my $epoch_time = $dt->epoch;
655: if ($epoch_time ne '') {
656: return $epoch_time;
657: } else {
658: return undef;
659: }
660: } else {
661: return undef;
662: }
663: }
664:
665: ##############################################
666: ##############################################
667:
668: =pod
669:
670: =item &pjump_javascript_definition()
671:
672: Returns javascript defining the 'pjump' function, which opens up a
673: parameter setting wizard.
674:
675: =cut
676:
677: ##############################################
678: ##############################################
679: sub pjump_javascript_definition {
680: my $Str = <<END;
681: function pjump(type,dis,value,marker,ret,call,hour,min,sec) {
682: parmwin=window.open("/adm/rat/parameter.html?type="+escape(type)
683: +"&value="+escape(value)+"&marker="+escape(marker)
684: +"&return="+escape(ret)
685: +"&call="+escape(call)+"&name="+escape(dis)
686: +"&defhour="+escape(hour)+"&defmin="+escape(min)
687: +"&defsec="+escape(sec),"LONCAPAparms",
688: "height=350,width=350,scrollbars=no,menubar=no");
689: }
690: END
691: return $Str;
692: }
693:
694: ##############################################
695: ##############################################
696:
697: =pod
698:
699: =item &javascript_nothing()
700:
701: Return an appropriate null for the users browser. This is used
702: as the first arguement for window.open calls when you want a blank
703: window that you can then write to.
704:
705: =cut
706:
707: ##############################################
708: ##############################################
709: sub javascript_nothing {
710: # mozilla and other browsers work with "''", but IE on mac does not.
711: my $nothing = "''";
712: my $user_browser;
713: my $user_os;
714: $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
715: $user_os = $env{'browser.os'} if (exists($env{'browser.os'}));
716: if (! defined($user_browser) || ! defined($user_os)) {
717: (undef,$user_browser,undef,undef,undef,$user_os) =
718: &Apache::loncommon::decode_user_agent();
719: }
720: if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
721: $nothing = "'javascript:void(0);'";
722: }
723: return $nothing;
724: }
725:
726: ##############################################
727: ##############################################
728: sub javascript_docopen {
729: my ($mimetype) = @_;
730: $mimetype ||= 'text/html';
731: # safari does not understand document.open() and loads "text/html"
732: my $nothing = "''";
733: my $user_browser;
734: my $user_os;
735: $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
736: $user_os = $env{'browser.os'} if (exists($env{'browser.os'}));
737: if (! defined($user_browser) || ! defined($user_os)) {
738: (undef,$user_browser,undef,undef,undef,$user_os) =
739: &Apache::loncommon::decode_user_agent();
740: }
741: if ($user_browser eq 'safari' && $user_os =~ 'mac') {
742: $nothing = "document.clear()";
743: } else {
744: $nothing = "document.open('$mimetype','replace')";
745: }
746: return $nothing;
747: }
748:
749:
750: ##############################################
751: ##############################################
752:
753: =pod
754:
755: =item &StatusOptions()
756:
757: Returns html for a selection box which allows the user to choose the
758: enrollment status of students. The selection box name is 'Status'.
759:
760: Inputs:
761:
762: $status: the currently selected status. If undefined the value of
763: $env{'form.Status'} is taken. If that is undefined, a value of 'Active'
764: is used.
765:
766: $formname: The name of the form. If defined the onchange attribute of
767: the selection box is set to document.$formname.submit().
768:
769: $size: the size (number of lines) of the selection box.
770:
771: $onchange: javascript to use when the value is changed. Enclosed in
772: double quotes, ""s, not single quotes.
773:
774: Returns: a perl string as described.
775:
776: =cut
777:
778: ##############################################
779: ##############################################
780: sub StatusOptions {
781: my ($status, $formName,$size,$onchange,$mult)=@_;
782: $size = 1 if (!defined($size));
783: if (! defined($status)) {
784: $status = 'Active';
785: $status = $env{'form.Status'} if (exists($env{'form.Status'}));
786: }
787:
788: my $Str = '';
789: $Str .= '<select name="Status"';
790: if (defined($mult)){
791: $Str .= ' multiple="multiple" ';
792: }
793: if(defined($formName) && $formName ne '' && ! defined($onchange)) {
794: $Str .= ' onchange="document.'.$formName.'.submit()"';
795: }
796: if (defined($onchange)) {
797: $Str .= ' onchange="'.$onchange.'"';
798: }
799: $Str .= ' size="'.$size.'" ';
800: $Str .= '>'."\n";
801: foreach my $type (['Active', &mt('Currently Has Access')],
802: ['Future', &mt('Will Have Future Access')],
803: ['Expired', &mt('Previously Had Access')],
804: ['Any', &mt('Any Access Status')]) {
805: my ($name,$label) = @$type;
806: $Str .= '<option value="'.$name.'" ';
807: if ($status eq $name) {
808: $Str .= 'selected="selected" ';
809: }
810: $Str .= '>'.$label.'</option>'."\n";
811: }
812:
813: $Str .= '</select>'."\n";
814: }
815:
816: ########################################################
817: ########################################################
818:
819: =pod
820:
821: =item Progess Window Handling Routines
822:
823: These routines handle the creation, update, increment, and closure of
824: progress windows. The progress window reports to the user the number
825: of items completed and an estimate of the time required to complete the rest.
826:
827: =over 4
828:
829:
830: =item &Create_PrgWin
831:
832: Writes javascript to the client to open a progress window and returns a
833: data structure used for bookkeeping.
834:
835: Inputs
836:
837: =over 4
838:
839: =item $r Apache request
840:
841: =item $title The title of the progress window
842:
843: =item $heading A description (usually 1 line) of the process being initiated.
844:
845: =item $number_to_do The total number of items being processed.
846:
847: =item $type Either 'popup' or 'inline' (popup is assumed if nothing is
848: specified)
849:
850: =item $width Specify the width in charaters of the input field.
851:
852: =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
853:
854: =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
855:
856: =back
857:
858: Returns a hash containing the progress state data structure.
859:
860:
861: =item &Update_PrgWin
862:
863: Updates the text in the progress indicator. Does not increment the count.
864: See &Increment_PrgWin.
865:
866: Inputs:
867:
868: =over 4
869:
870: =item $r Apache request
871:
872: =item $prog_state Pointer to the data structure returned by &Create_PrgWin
873:
874: =item $displaystring The string to write to the status indicator
875:
876: =back
877:
878: Returns: none
879:
880:
881: =item Increment_PrgWin
882:
883: Increment the count of items completed for the progress window by 1.
884:
885: Inputs:
886:
887: =over 4
888:
889: =item $r Apache request
890:
891: =item $prog_state Pointer to the data structure returned by Create_PrgWin
892:
893: =item $extraInfo A description of the items being iterated over. Typically
894: 'student'.
895:
896: =back
897:
898: Returns: none
899:
900:
901: =item Close_PrgWin
902:
903: Closes the progress window.
904:
905: Inputs:
906:
907: =over 4
908:
909: =item $r Apache request
910:
911: =item $prog_state Pointer to the data structure returned by Create_PrgWin
912:
913: =back
914:
915: Returns: none
916:
917: =back
918:
919: =cut
920:
921: ########################################################
922: ########################################################
923:
924: my $uniq=0;
925: sub get_uniq_name {
926: $uniq++;
927: return 'uniquename'.$uniq;
928: }
929:
930: # Create progress
931: sub Create_PrgWin {
932: my ($r, $title, $heading, $number_to_do,$type,$width,$formname,
933: $inputname)=@_;
934: if (!defined($type)) { $type='popup'; }
935: if (!defined($width)) { $width=55; }
936: my %prog_state;
937: $prog_state{'type'}=$type;
938: if ($type eq 'popup') {
939: $prog_state{'window'}='popwin';
940: my $start_page =
941: &Apache::loncommon::start_page($title,undef,
942: {'only_body' => 1,
943: 'bgcolor' => '#88DDFF',
944: 'js_ready' => 1});
945: my $end_page = &Apache::loncommon::end_page({'js_ready' => 1});
946:
947: #the whole function called through timeout is due to issues
948: #in mozilla Read BUG #2665 if you want to know the whole story
949: &r_print($r,'<script type="text/javascript">'.
950: "var popwin;
951: function openpopwin () {
952: popwin=open(\'\',\'popwin\',\'width=400,height=100\');".
953: "popwin.document.writeln(\'".$start_page.
954: "<h4>".&mt("$heading")."<\/h4>".
955: "<form action= \"\" name=\"popremain\" method=\"post\">".
956: '<input type="text" size="'.$width.'" name="remaining" value="'.
957: &mt('Starting').'" /><\\/form>'.$end_page.
958: "\');".
959: "popwin.document.close();}".
960: "\nwindow.setTimeout(openpopwin,0)</script>");
961: $prog_state{'formname'}='popremain';
962: $prog_state{'inputname'}="remaining";
963: } elsif ($type eq 'inline') {
964: $prog_state{'window'}='window';
965: if (!$formname) {
966: $prog_state{'formname'}=&get_uniq_name();
967: &r_print($r,'<form action="" name="'.$prog_state{'formname'}.'">');
968: } else {
969: $prog_state{'formname'}=$formname;
970: }
971: if (!$inputname) {
972: $prog_state{'inputname'}=&get_uniq_name();
973: &r_print($r,&mt("$heading [_1]",' <input type="text" name="'.$prog_state{'inputname'}.'" size="'.$width.'" />'));
974: } else {
975: $prog_state{'inputname'}=$inputname;
976:
977: }
978: if (!$formname) { &r_print($r,'</form>'); }
979: &Update_PrgWin($r,\%prog_state,&mt('Starting'));
980: }
981:
982: $prog_state{'done'}=0;
983: $prog_state{'firststart'}=&Time::HiRes::time();
984: $prog_state{'laststart'}=&Time::HiRes::time();
985: $prog_state{'max'}=$number_to_do;
986:
987: return %prog_state;
988: }
989:
990: # update progress
991: sub Update_PrgWin {
992: my ($r,$prog_state,$displayString)=@_;
993: &r_print($r,'<script type="text/javascript">'.$$prog_state{'window'}.'.document.'.
994: $$prog_state{'formname'}.'.'.
995: $$prog_state{'inputname'}.'.value="'.
996: $displayString.'";</script>');
997: $$prog_state{'laststart'}=&Time::HiRes::time();
998: }
999:
1000: # increment progress state
1001: sub Increment_PrgWin {
1002: my ($r,$prog_state,$extraInfo)=@_;
1003: $$prog_state{'done'}++;
1004: my $time_est= (&Time::HiRes::time() - $$prog_state{'firststart'})/
1005: $$prog_state{'done'} *
1006: ($$prog_state{'max'}-$$prog_state{'done'});
1007: $time_est = int($time_est);
1008: #
1009: my $min = int($time_est/60);
1010: my $sec = $time_est % 60;
1011: #
1012: my $str;
1013: if ($min == 0 && $sec > 1) {
1014: $str = '[_2] seconds';
1015: } elsif ($min == 1 && $sec > 1) {
1016: $str = '1 minute [_2] seconds';
1017: } elsif ($min == 1 && $sec < 2) {
1018: $str = '1 minute';
1019: } elsif ($min < 10 && $sec > 1) {
1020: $str = '[_1] minutes, [_2] seconds';
1021: } elsif ($min >= 10 || $sec < 2) {
1022: $str = '[_1] minutes';
1023: }
1024: $time_est = &mt($str,$min,$sec);
1025: #
1026: my $lasttime = &Time::HiRes::time()-$$prog_state{'laststart'};
1027: if ($lasttime > 9) {
1028: $lasttime = int($lasttime);
1029: } elsif ($lasttime < 0.01) {
1030: $lasttime = 0;
1031: } else {
1032: $lasttime = sprintf("%3.2f",$lasttime);
1033: }
1034: if ($lasttime == 1) {
1035: $lasttime = '('.$lasttime.' '.&mt('second for').' '.$extraInfo.')';
1036: } else {
1037: $lasttime = '('.$lasttime.' '.&mt('seconds for').' '.$extraInfo.')';
1038: }
1039: #
1040: my $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
1041: my $user_os = $env{'browser.os'} if (exists($env{'browser.os'}));
1042: if (! defined($user_browser) || ! defined($user_os)) {
1043: (undef,$user_browser,undef,undef,undef,$user_os) =
1044: &Apache::loncommon::decode_user_agent();
1045: }
1046: if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
1047: $lasttime = '';
1048: }
1049: &r_print($r,'<script>'.$$prog_state{'window'}.'.document.'.
1050: $$prog_state{'formname'}.'.'.
1051: $$prog_state{'inputname'}.'.value="'.
1052: $$prog_state{'done'}.'/'.$$prog_state{'max'}.
1053: ': '.$time_est.' '.&mt('remaining').' '.$lasttime.'";'.'</script>');
1054: $$prog_state{'laststart'}=&Time::HiRes::time();
1055: }
1056:
1057: # close Progress Line
1058: sub Close_PrgWin {
1059: my ($r,$prog_state)=@_;
1060: if ($$prog_state{'type'} eq 'popup') {
1061: &r_print($r,'<script>popwin.close()</script>'."\n");
1062: } elsif ($$prog_state{'type'} eq 'inline') {
1063: &Update_PrgWin($r,$prog_state,&mt('Done'));
1064: }
1065: undef(%$prog_state);
1066: }
1067:
1068: sub r_print {
1069: my ($r,$to_print)=@_;
1070: if ($r) {
1071: $r->print($to_print);
1072: $r->rflush();
1073: } else {
1074: print($to_print);
1075: }
1076: }
1077:
1078: # ------------------------------------------------------- Puts directory header
1079:
1080: sub crumbs {
1081: my ($uri,$target,$prefix,$form,$size,$noformat,$skiplast)=@_;
1082: if (! defined($size)) {
1083: $size = '+2';
1084: }
1085: if ($target) {
1086: $target = ' target="'.
1087: &Apache::loncommon::escape_single($target).'"';
1088: }
1089: my $output='';
1090: unless ($noformat) { $output.='<br /><tt><b>'; }
1091: $output.='<font size="'.$size.'">'.$prefix.'/';
1092: if ($env{'user.adv'}) {
1093: my $path=$prefix.'/';
1094: foreach my $dir (split('/',$uri)) {
1095: if (! $dir) { next; }
1096: $path .= $dir;
1097: if ($path eq $uri) {
1098: if ($skiplast) {
1099: $output.=$dir;
1100: last;
1101: }
1102: } else {
1103: $path.='/';
1104: }
1105: my $href_path = &HTML::Entities::encode($path,'<>&"');
1106: &Apache::loncommon::inhibit_menu_check(\$href_path);
1107: if ($form) {
1108: my $href = 'javascript:'.$form.".action='".$href_path."';".$form.'.submit();';
1109: $output.=qq{<a href="$href" $target>$dir</a>/};
1110: } else {
1111: $output.=qq{<a href="$href_path" $target>$dir</a>/};
1112: }
1113: }
1114: } else {
1115: foreach my $dir (split('/',$uri)) {
1116: if (! $dir) { next; }
1117: $output.=$dir.'/';
1118: }
1119: }
1120: if ($uri !~ m|/$|) { $output=~s|/$||; }
1121: return $output.'</font>'.($noformat?'':'</b></tt><br />');
1122: }
1123:
1124: # --------------------- A function that generates a window for the spellchecker
1125:
1126: sub spellheader {
1127: my $start_page=
1128: &Apache::loncommon::start_page('Speller Suggestions',undef,
1129: {'only_body' => 1,
1130: 'js_ready' => 1,
1131: 'bgcolor' => '#DDDDDD',
1132: 'add_entries' => {
1133: 'onload' =>
1134: 'document.forms.spellcheckform.submit()',
1135: }
1136: });
1137: my $end_page=
1138: &Apache::loncommon::end_page({'js_ready' => 1});
1139:
1140: my $nothing=&javascript_nothing();
1141: return (<<ENDCHECK);
1142: <script type="text/javascript">
1143: //<!-- BEGIN LON-CAPA Internal
1144: var checkwin;
1145:
1146: function spellcheckerwindow(string) {
1147: var esc_string = string.replace(/\"/g,'"');
1148: checkwin=window.open($nothing,'spellcheckwin','height=320,width=280,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no');
1149: checkwin.document.writeln('$start_page<form name="spellcheckform" action="/adm/spellcheck" method="post"><input type="hidden" name="text" value="'+esc_string+'" /><\\/form>$end_page');
1150: checkwin.document.close();
1151: }
1152: // END LON-CAPA Internal -->
1153: </script>
1154: ENDCHECK
1155: }
1156:
1157: # ---------------------------------- Generate link to spell checker for a field
1158:
1159: sub spelllink {
1160: my ($form,$field)=@_;
1161: my $linktext=&mt('Check Spelling');
1162: return (<<ENDLINK);
1163: <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>
1164: ENDLINK
1165: }
1166:
1167: # ------------------------------------------------- Output headers for HTMLArea
1168:
1169: {
1170: my @htmlareafields;
1171: sub init_htmlareafields {
1172: undef(@htmlareafields);
1173: }
1174:
1175: sub add_htmlareafields {
1176: my (@newfields) = @_;
1177: push(@htmlareafields,@newfields);
1178: }
1179:
1180: sub get_htmlareafields {
1181: return @htmlareafields;
1182: }
1183: }
1184:
1185: sub htmlareaheaders {
1186: return if (&htmlareablocked());
1187: return if (!&htmlareabrowser());
1188: return (<<ENDHEADERS);
1189: <script type="text/javascript" src="/fckeditor/fckeditor.js"></script>
1190: ENDHEADERS
1191: }
1192:
1193: # ----------------------------------------------------------------- Preferences
1194:
1195: sub disablelink {
1196: my @fields=@_;
1197: if (defined($#fields)) {
1198: unless ($#fields>=0) { return ''; }
1199: }
1200: return '<a href="'.&HTML::Entities::encode('/adm/preferences?action=set_wysiwyg&wysiwyg=off&returnurl=','<>&"').&escape($ENV{'REQUEST_URI'}).'">'.&mt('Disable WYSIWYG Editor').'</a>';
1201: }
1202:
1203: sub enablelink {
1204: my @fields=@_;
1205: if (defined($#fields)) {
1206: unless ($#fields>=0) { return ''; }
1207: }
1208: return '<a href="'.&HTML::Entities::encode('/adm/preferences?action=set_wysiwyg&wysiwyg=on&returnurl=','<>&"').&escape($ENV{'REQUEST_URI'}).'">'.&mt('Enable WYSIWYG Editor').'</a>';
1209: }
1210:
1211: # ------------------------------------------------- lang to use in html editor
1212: sub htmlarea_lang {
1213: my $lang='en';
1214: if (&mt('htmlarea_lang') ne 'htmlarea_lang') {
1215: $lang=&mt('htmlarea_lang');
1216: }
1217: return $lang;
1218: }
1219:
1220: # ----------------------------------------- Script to activate only some fields
1221:
1222: sub htmlareaselectactive {
1223: my @fields=@_;
1224: unless (&htmlareabrowser()) { return ''; }
1225: if (&htmlareablocked()) { return '<br />'.&enablelink(@fields); }
1226: my $output='<script type="text/javascript" defer="1">';
1227: my $lang = &htmlarea_lang();
1228: foreach my $field (@fields) {
1229: $output.="
1230: {
1231: var oFCKeditor = new FCKeditor('$field');
1232: oFCKeditor.Config['CustomConfigurationsPath'] =
1233: '/fckeditor/loncapaconfig.js';
1234: oFCKeditor.ReplaceTextarea();
1235: oFCKeditor.Config['AutoDetectLanguage'] = false;
1236: oFCKeditor.Config['DefaultLanguage'] = '$lang';
1237: }";
1238: }
1239: $output.="\nwindow.status='Activated Editfields';\n</script><br />".
1240: &disablelink(@fields);
1241: return $output;
1242: }
1243:
1244: # --------------------------------------------------------------------- Blocked
1245:
1246: sub htmlareablocked {
1247: unless ($env{'environment.wysiwygeditor'} eq 'on') { return 1; }
1248: return 0;
1249: }
1250:
1251: # ---------------------------------------- Browser capable of running HTMLArea?
1252:
1253: sub htmlareabrowser {
1254: return 1;
1255: }
1256:
1257: ############################################################
1258: ############################################################
1259:
1260: =pod
1261:
1262: =item breadcrumbs
1263:
1264: Compiles the previously registered breadcrumbs into an series of links.
1265: FAQ and BUG links will be placed on the left side of the table if they
1266: are defined for the last registered breadcrumb.
1267: Additionally supports a 'component', which will be displayed on the
1268: right side of the table (without a link).
1269: A link to help for the component will be included if one is specified.
1270:
1271: All inputs can be undef without problems.
1272:
1273: Inputs: $component (the large text on the right side of the table),
1274: $component_help
1275: $menulink (boolean, controls whether to include a link to /adm/menu)
1276: $helplink (if 'nohelp' don't include the orange help link)
1277: $css_class (optional name for the class to apply to the table for CSS)
1278: Returns a string containing breadcrumbs for the current page.
1279:
1280: =item clear_breadcrumbs
1281:
1282: Clears the previously stored breadcrumbs.
1283:
1284: =item add_breadcrumb
1285:
1286: Pushes a breadcrumb on the stack of crumbs.
1287:
1288: input: $breadcrumb, a hash reference. The keys 'href','title', and 'text'
1289: are required. If present the keys 'faq' and 'bug' will be used to provide
1290: links to the FAQ and bug sites. If the key 'no_mt' is present the 'title'
1291: and 'text' values won't be sent through &mt()
1292:
1293: returns: nothing
1294:
1295: =cut
1296:
1297: ############################################################
1298: ############################################################
1299: {
1300: my @Crumbs;
1301:
1302: sub breadcrumbs {
1303: my ($component,$component_help,$menulink,$helplink,$css_class) = @_;
1304: #
1305: $css_class ||= 'LC_breadcrumbs';
1306: my $Str = "\n".'<table class="'.$css_class.'"><tr><td>';
1307: #
1308: # Make the faq and bug data cascade
1309: my $faq = '';
1310: my $bug = '';
1311: my $help='';
1312: # The last breadcrumb does not have a link, so handle it separately.
1313: my $last = pop(@Crumbs);
1314: #
1315: # The first one should be the course or a menu link
1316: if (!defined($menulink)) { $menulink=1; }
1317: if ($menulink) {
1318: my $description = 'Menu';
1319: my $no_mt_descr = 0;
1320: if (exists($env{'request.course.id'}) &&
1321: $env{'request.course.id'} ne '') {
1322: $description =
1323: $env{'course.'.$env{'request.course.id'}.'.description'};
1324: $no_mt_descr = 1;
1325: }
1326: unshift(@Crumbs,{
1327: href =>'/adm/menu',
1328: title =>'Go to main menu',
1329: target =>'_top',
1330: text =>$description,
1331: no_mt =>$no_mt_descr,
1332: });
1333: }
1334: my $links .=
1335: join('->',
1336: map {
1337: $faq = $_->{'faq'} if (exists($_->{'faq'}));
1338: $bug = $_->{'bug'} if (exists($_->{'bug'}));
1339: $help = $_->{'help'} if (exists($_->{'help'}));
1340: my $result = '<a href="'.$_->{'href'}.'" ';
1341: if (defined($_->{'target'}) && $_->{'target'} ne '') {
1342: $result .= 'target="'.$_->{'target'}.'" ';
1343: }
1344: if ($_->{'no_mt'}) {
1345: $result .='title="'.$_->{'title'}.'">'.
1346: $_->{'text'}.'</a>';
1347: } else {
1348: $result .='title="'.&mt($_->{'title'}).'">'.
1349: &mt($_->{'text'}).'</a>';
1350: }
1351: $result;
1352: } @Crumbs
1353: );
1354: $links .= '->' if ($links ne '');
1355: if ($last->{'no_mt'}) {
1356: $links .= '<b>'.$last->{'text'}.'</b>';
1357: } else {
1358: $links .= '<b>'.&mt($last->{'text'}).'</b>';
1359: }
1360: #
1361: my $icons = '';
1362: $faq = $last->{'faq'} if (exists($last->{'faq'}));
1363: $bug = $last->{'bug'} if (exists($last->{'bug'}));
1364: $help = $last->{'help'} if (exists($last->{'help'}));
1365: $component_help=($component_help?$component_help:$help);
1366: # if ($faq ne '') {
1367: # $icons .= &Apache::loncommon::help_open_faq($faq);
1368: # }
1369: # if ($bug ne '') {
1370: # $icons .= &Apache::loncommon::help_open_bug($bug);
1371: # }
1372: if ($faq ne '' || $component_help ne '' || $bug ne '') {
1373: $icons .= &Apache::loncommon::help_open_menu($component,
1374: $component_help,
1375: $faq,$bug);
1376: }
1377: #
1378: $Str .= $links.'</td>';
1379: #
1380: if (defined($component)) {
1381: $Str .= '<td class="'.$css_class.'_component">'.
1382: &mt($component);
1383: if ($icons ne '') {
1384: $Str .= ' '.$icons;
1385: }
1386: $Str .= '</td>';
1387: }
1388: $Str .= '</tr></table>'."\n";
1389: #
1390: # Return the @Crumbs stack to what we started with
1391: push(@Crumbs,$last);
1392: shift(@Crumbs);
1393: #
1394: return $Str;
1395: }
1396:
1397: sub clear_breadcrumbs {
1398: undef(@Crumbs);
1399: }
1400:
1401: sub add_breadcrumb {
1402: push (@Crumbs,@_);
1403: }
1404:
1405: } # End of scope for @Crumbs
1406:
1407: ############################################################
1408: ############################################################
1409:
1410: # Nested table routines.
1411: #
1412: # Routines to display form items in a multi-row table with 2 columns.
1413: # Uses nested tables to divide form elements into segments.
1414: # For examples of use see loncom/interface/lonnotify.pm
1415: #
1416: # Can be used in following order: ...
1417: # &start_pick_box()
1418: # row1
1419: # row2
1420: # row3 ... etc.
1421: # &submit_row()
1422: # &end_pick_box()
1423: #
1424: # where row1, row 2 etc. are chosen from &role_select_row,&course_select_row,
1425: # &status_select_row and &email_default_row
1426: #
1427: # Can also be used in following order:
1428: #
1429: # &start_pick_box()
1430: # &row_title()
1431: # &row_closure()
1432: # &row_title()
1433: # &row_closure() ... etc.
1434: # &submit_row()
1435: # &end_pick_box()
1436: #
1437: # In general a &submit_row() call should proceed the call to &end_pick_box(),
1438: # as this routine adds a button for form submission.
1439: # &submit_row() does not require a &row_closure after it.
1440: #
1441: # &start_pick_box() creates a bounding table with 1-pixel wide black border.
1442: # rows should be placed between calls to &start_pick_box() and &end_pick_box.
1443: #
1444: # &row_title() adds a title in the left column for each segment.
1445: # &row_closure() closes a row with a 1-pixel wide black line.
1446: #
1447: # &role_select_row() provides a select box from which to choose 1 or more roles
1448: # &course_select_row provides ways of picking groups of courses
1449: # radio buttons: all, by category or by picking from a course picker pop-up
1450: # note: by category option is only displayed if a domain has implemented
1451: # selection by year, semester, department, number etc.
1452: #
1453: # &status_select_row() provides a select box from which to choose 1 or more
1454: # access types (current access, prior access, and future access)
1455: #
1456: # &email_default_row() provides text boxes for default e-mail suffixes for
1457: # different authentication types in a domain.
1458: #
1459: # &row_title() and &row_closure() are called internally by the &*_select_row
1460: # routines, but can also be called directly to start and end rows which have
1461: # needs that are not accommodated by the *_select_row() routines.
1462:
1463: sub start_pick_box {
1464: my ($css_class) = @_;
1465: if (defined($css_class)) {
1466: $css_class = 'class="'.$css_class.'"';
1467: } else {
1468: $css_class= 'class="LC_pick_box"';
1469: }
1470: my $output = <<"END";
1471: <table $css_class>
1472: END
1473: return $output;
1474: }
1475:
1476: sub end_pick_box {
1477: my $output = <<"END";
1478: </table>
1479: END
1480: return $output;
1481: }
1482:
1483: sub row_title {
1484: my ($title,$css_title_class,$css_value_class) = @_;
1485: $css_title_class ||= 'LC_pick_box_title';
1486: $css_title_class = 'class="'.$css_title_class.'"';
1487:
1488: $css_value_class ||= 'LC_pick_box_value';
1489: $css_value_class = 'class="'.$css_value_class.'"';
1490:
1491: if ($title ne '') {
1492: $title .= ':';
1493: }
1494: my $output = <<"ENDONE";
1495: <tr class="LC_pick_box_row">
1496: <td $css_title_class>
1497: $title
1498: </td>
1499: <td $css_value_class>
1500: ENDONE
1501: return $output;
1502: }
1503:
1504: sub row_closure {
1505: my ($no_separator) =@_;
1506: my $output = <<"ENDTWO";
1507: </td>
1508: </tr>
1509: ENDTWO
1510: if (!$no_separator) {
1511: $output .= <<"ENDTWO";
1512: <tr>
1513: <td colspan="2" class="LC_pick_box_separator">
1514: </td>
1515: </tr>
1516: ENDTWO
1517: }
1518: return $output;
1519: }
1520:
1521: sub role_select_row {
1522: my ($roles,$title,$css_class,$show_separate_custom,$cdom,$cnum) = @_;
1523: my $output;
1524: if (defined($title)) {
1525: $output = &row_title($title,$css_class);
1526: }
1527: $output .= qq|
1528: <select name="roles" multiple >\n|;
1529: foreach my $role (@$roles) {
1530: my $plrole;
1531: if ($role eq 'ow') {
1532: $plrole = &mt('Course Owner');
1533: } elsif ($role eq 'cr') {
1534: if ($show_separate_custom) {
1535: if ($cdom ne '' && $cnum ne '') {
1536: my %course_customroles = &course_custom_roles($cdom,$cnum);
1537: foreach my $crrole (sort(keys(%course_customroles))) {
1538: my ($plcrrole) = ($crrole =~ m|^cr/[^/]+/[^/]+/(.+)$|);
1539: $output .= ' <option value="'.$crrole.'">'.$plcrrole.
1540: '</option>';
1541: }
1542: }
1543: } else {
1544: $plrole = &mt('Custom Role');
1545: }
1546: } else {
1547: $plrole=&Apache::lonnet::plaintext($role);
1548: }
1549: if (($role ne 'cr') || (!$show_separate_custom)) {
1550: $output .= ' <option value="'.$role.'">'.$plrole.'</option>';
1551: }
1552: }
1553: $output .= qq| </select>\n|;
1554: if (defined($title)) {
1555: $output .= &row_closure();
1556: }
1557: return $output;
1558: }
1559:
1560: sub course_select_row {
1561: my ($title,$formname,$totcodes,$codetitles,$idlist,$idlist_titles,
1562: $css_class) = @_;
1563: my $output = &row_title($title,$css_class);
1564: $output .= &course_selection($formname,$totcodes,$codetitles,$idlist,$idlist_titles);
1565: $output .= &row_closure();
1566: return $output;
1567: }
1568:
1569: sub course_selection {
1570: my ($formname,$totcodes,$codetitles,$idlist,$idlist_titles) = @_;
1571: my $output = qq|
1572: <script type="text/javascript">
1573: function coursePick (formname) {
1574: for (var i=0; i<formname.coursepick.length; i++) {
1575: if (formname.coursepick[i].value == 'category') {
1576: courseSet('');
1577: }
1578: if (!formname.coursepick[i].checked) {
1579: if (formname.coursepick[i].value == 'specific') {
1580: formname.coursetotal.value = 0;
1581: formname.courselist = '';
1582: }
1583: }
1584: }
1585: }
1586: function setPick (formname) {
1587: for (var i=0; i<formname.coursepick.length; i++) {
1588: if (formname.coursepick[i].value == 'category') {
1589: formname.coursepick[i].checked = true;
1590: }
1591: formname.coursetotal.value = 0;
1592: formname.courselist = '';
1593: }
1594: }
1595: </script>
1596: |;
1597: my $courseform='<b>'.&Apache::loncommon::selectcourse_link
1598: ($formname,'pickcourse','pickdomain','coursedesc','',1).'</b>';
1599: $output .= '<input type="radio" name="coursepick" value="all" onclick="coursePick(this.form)" />'.&mt('All courses').'<br />';
1600: if ($totcodes > 0) {
1601: my $numtitles = @$codetitles;
1602: if ($numtitles > 0) {
1603: $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 />';
1604: $output .= '<table><tr><td>'.$$codetitles[0].'<br />'."\n".
1605: '<select name="'.$$codetitles[0].
1606: '" onChange="setPick(this.form);courseSet('."'$$codetitles[0]'".')">'."\n".
1607: ' <option value="-1" />Select'."\n";
1608: my @items = ();
1609: my @longitems = ();
1610: if ($$idlist{$$codetitles[0]} =~ /","/) {
1611: @items = split(/","/,$$idlist{$$codetitles[0]});
1612: } else {
1613: $items[0] = $$idlist{$$codetitles[0]};
1614: }
1615: if (defined($$idlist_titles{$$codetitles[0]})) {
1616: if ($$idlist_titles{$$codetitles[0]} =~ /","/) {
1617: @longitems = split(/","/,$$idlist_titles{$$codetitles[0]});
1618: } else {
1619: $longitems[0] = $$idlist_titles{$$codetitles[0]};
1620: }
1621: for (my $i=0; $i<@longitems; $i++) {
1622: if ($longitems[$i] eq '') {
1623: $longitems[$i] = $items[$i];
1624: }
1625: }
1626: } else {
1627: @longitems = @items;
1628: }
1629: for (my $i=0; $i<@items; $i++) {
1630: $output .= ' <option value="'.$items[$i].'">'.$longitems[$i].'</option>';
1631: }
1632: $output .= '</select></td>';
1633: for (my $i=1; $i<$numtitles; $i++) {
1634: $output .= '<td>'.$$codetitles[$i].'<br />'."\n".
1635: '<select name="'.$$codetitles[$i].
1636: '" onChange="courseSet('."'$$codetitles[$i]'".')">'."\n".
1637: '<option value="-1"><-Pick '.$$codetitles[$i-1].'</option>'."\n".
1638: '</select>'."\n".
1639: '</td>';
1640: }
1641: $output .= '</tr></table><br />';
1642: }
1643: }
1644: $output .= '<input type="radio" name="coursepick" value="specific" onclick="coursePick(this.form);opencrsbrowser('."'".$formname."','dccourse','dcdomain','coursedesc','','1'".')" />'.&mt('Pick specific course(s):').' '.$courseform.' <input type="text" value="0" size="4" name="coursetotal" /><input type="hidden" name="courselist" value="" />selected.<br />'."\n";
1645: return $output;
1646: }
1647:
1648: sub status_select_row {
1649: my ($types,$title,$css_class) = @_;
1650: my $output;
1651: if (defined($title)) {
1652: $output = &row_title($title,$css_class,'LC_pick_box_select');
1653: }
1654: $output .= qq|
1655: <select name="types" multiple>\n|;
1656: foreach my $status_type (sort(keys(%{$types}))) {
1657: $output .= ' <option value="'.$status_type.'">'.$$types{$status_type}.'</option>';
1658: }
1659: $output .= qq| </select>\n|;
1660: if (defined($title)) {
1661: $output .= &row_closure();
1662: }
1663: return $output;
1664: }
1665:
1666: sub email_default_row {
1667: my ($authtypes,$title,$descrip,$css_class) = @_;
1668: my $output = &row_title($title,$css_class);
1669: $output .= $descrip.
1670: &Apache::loncommon::start_data_table().
1671: &Apache::loncommon::start_data_table_header_row().
1672: '<th>'.&mt('Authentication Method').'</th>'.
1673: '<th align="right">'.&mt('Username -> e-mail conversion').'</th>'."\n".
1674: &Apache::loncommon::end_data_table_header_row();
1675: my $rownum = 0;
1676: foreach my $auth (sort(keys(%{$authtypes}))) {
1677: my ($userentry,$size);
1678: if ($auth =~ /^krb/) {
1679: $userentry = '';
1680: $size = 25;
1681: } else {
1682: $userentry = 'username@';
1683: $size = 15;
1684: }
1685: $output .= &Apache::loncommon::start_data_table_row().
1686: '<td> '.$$authtypes{$auth}.'</td>'.
1687: '<td align="right">'.$userentry.
1688: '<input type="text" name="'.$auth.'" size="'.$size.'" /></td>'.
1689: &Apache::loncommon::end_data_table_row();
1690: }
1691: $output .= &Apache::loncommon::end_data_table();
1692: $output .= &row_closure();
1693: return $output;
1694: }
1695:
1696:
1697: sub submit_row {
1698: my ($title,$cmd,$submit_text,$css_class) = @_;
1699: my $output = &row_title($title,$css_class,'LC_pick_box_submit');
1700: $output .= qq|
1701: <br />
1702: <input type="hidden" name="command" value="$cmd" />
1703: <input type="submit" value="$submit_text"/>
1704: <br /><br />
1705: \n|;
1706: return $output;
1707: }
1708:
1709: sub course_custom_roles {
1710: my ($cdom,$cnum) = @_;
1711: my %returnhash=();
1712: my %coursepersonnel=&Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
1713: foreach my $person (sort(keys(%coursepersonnel))) {
1714: my ($role) = ($person =~ /^([^:]+):/);
1715: my ($end,$start) = split(/:/,$coursepersonnel{$person});
1716: if ($end == -1 && $start == -1) {
1717: next;
1718: }
1719: if ($role =~ m|^cr/[^/]+/[^/]+/[^/]|) {
1720: $returnhash{$role} ++;
1721: }
1722: }
1723: return %returnhash;
1724: }
1725:
1726:
1727: ##############################################
1728: ##############################################
1729:
1730: # echo_form_input
1731: #
1732: # Generates html markup to add form elements from the referrer page
1733: # as hidden form elements (values encoded) in the new page.
1734: #
1735: # Intended to support two types of use
1736: # (a) to allow backing up to earlier pages in a multi-page
1737: # form submission process using a breadcrumb trail.
1738: #
1739: # (b) to allow the current page to be reloaded with form elements
1740: # set on previous page to remain unchanged. An example would
1741: # be where the a page containing a dynamically-built table of data is
1742: # is to be redisplayed, with only the sort order of the data changed.
1743: #
1744: # Inputs:
1745: # 1. Reference to array of form elements in the submitted form on
1746: # the referrer page which are to be excluded from the echoed elements.
1747: #
1748: # 2. Reference to array of regular expressions, which if matched in the
1749: # name of the form element n the referrer page will be omitted from echo.
1750: #
1751: # Outputs: A scalar containing the html markup for the echoed form
1752: # elements (all as hidden elements, with values encoded).
1753:
1754:
1755: sub echo_form_input {
1756: my ($excluded,$regexps) = @_;
1757: my $output = '';
1758: foreach my $key (keys(%env)) {
1759: if ($key =~ /^form\.(.+)$/) {
1760: my $name = $1;
1761: my $match = 0;
1762: if ((!@{$excluded}) || (!grep/^$name$/,@{$excluded})) {
1763: if (defined($regexps)) {
1764: if (@{$regexps} > 0) {
1765: foreach my $regexp (@{$regexps}) {
1766: if ($name =~ /\Q$regexp\E/) {
1767: $match = 1;
1768: last;
1769: }
1770: }
1771: }
1772: }
1773: if (!$match) {
1774: if (ref($env{$key})) {
1775: foreach my $value (@{$env{$key}}) {
1776: $value = &HTML::Entities::encode($value,'<>&"');
1777: $output .= '<input type="hidden" name="'.$name.
1778: '" value="'.$value.'" />'."\n";
1779: }
1780: } else {
1781: my $value = &HTML::Entities::encode($env{$key},'<>&"');
1782: $output .= '<input type="hidden" name="'.$name.
1783: '" value="'.$value.'" />'."\n";
1784: }
1785: }
1786: }
1787: }
1788: }
1789: return $output;
1790: }
1791:
1792: ##############################################
1793: ##############################################
1794:
1795: # set_form_elements
1796: #
1797: # Generates javascript to set form elements to values based on
1798: # corresponding values for the same form elements when the page was
1799: # previously submitted.
1800: #
1801: # Last submission values are read from hidden form elements in referring
1802: # page which have the same name, i.e., generated by &echo_form_input().
1803: #
1804: # Intended to be called by onload event.
1805: #
1806: # Inputs:
1807: # (a) Reference to hash of echoed form elements to be set.
1808: #
1809: # In the hash, keys are the form element names, and the values are the
1810: # element type (selectbox, radio, checkbox or text -for textbox, textarea or
1811: # hidden).
1812: #
1813: # (b) Optional reference to hash of stored elements to be set.
1814: #
1815: # If the page being displayed is a page which permits modification of
1816: # previously stored data, e.g., the first page in a multi-page submission,
1817: # then if stored is supplied, form elements will be set to the last stored
1818: # values. If user supplied values are also available for the same elements
1819: # these will replace the stored values.
1820: #
1821: # Output:
1822: #
1823: # javascript function - set_form_elements() which sets form elements,
1824: # expects an argument: formname - the name of the form according to
1825: # the DOM, e.g., document.compose
1826:
1827: sub set_form_elements {
1828: my ($elements,$stored) = @_;
1829: my %values;
1830: my $output .= 'function setFormElements(courseForm) {
1831: ';
1832: if (defined($stored)) {
1833: foreach my $name (keys(%{$stored})) {
1834: if (exists($$elements{$name})) {
1835: if (ref($$stored{$name}) eq 'ARRAY') {
1836: $values{$name} = $$stored{$name};
1837: } else {
1838: @{$values{$name}} = ($$stored{$name});
1839: }
1840: }
1841: }
1842: }
1843:
1844: foreach my $key (keys(%env)) {
1845: if ($key =~ /^form\.(.+)$/) {
1846: my $name = $1;
1847: if (exists($$elements{$name})) {
1848: @{$values{$name}} = &Apache::loncommon::get_env_multiple($key);
1849: }
1850: }
1851: }
1852:
1853: foreach my $name (keys(%values)) {
1854: for (my $i=0; $i<@{$values{$name}}; $i++) {
1855: $values{$name}[$i] = &HTML::Entities::decode($values{$name}[$i],'<>&"');
1856: $values{$name}[$i] =~ s/([\r\n\f]+)/\\n/g;
1857: $values{$name}[$i] =~ s/"/\\"/g;
1858: }
1859: if ($$elements{$name} eq 'text') {
1860: my $numvalues = @{$values{$name}};
1861: if ($numvalues > 1) {
1862: my $valuestring = join('","',@{$values{$name}});
1863: $output .= qq|
1864: var textvalues = new Array ("$valuestring");
1865: var total = courseForm.elements['$name'].length;
1866: if (total > $numvalues) {
1867: total = $numvalues;
1868: }
1869: for (var i=0; i<total; i++) {
1870: courseForm.elements['$name']\[i].value = textvalues[i];
1871: }
1872: |;
1873: } else {
1874: $output .= qq|
1875: courseForm.elements['$name'].value = "$values{$name}[0]";
1876: |;
1877: }
1878: } else {
1879: $output .= qq|
1880: var elementLength = courseForm.elements['$name'].length;
1881: if (elementLength==undefined) {
1882: |;
1883: foreach my $value (@{$values{$name}}) {
1884: if ($$elements{$name} eq 'selectbox') {
1885: $output .= qq|
1886: if (courseForm.elements['$name'].options[0].value == "$value") {
1887: courseForm.elements['$name'].options[0].selected = true;
1888: }|;
1889: } elsif (($$elements{$name} eq 'radio') ||
1890: ($$elements{$name} eq 'checkbox')) {
1891: $output .= qq|
1892: if (courseForm.elements['$name'].value == "$value") {
1893: courseForm.elements['$name'].checked = true;
1894: }|;
1895: }
1896: }
1897: $output .= qq|
1898: }
1899: else {
1900: for (var i=0; i<courseForm.elements['$name'].length; i++) {
1901: |;
1902: if ($$elements{$name} eq 'selectbox') {
1903: $output .= qq|
1904: courseForm.elements['$name'].options[i].selected = false;|;
1905: } elsif (($$elements{$name} eq 'radio') ||
1906: ($$elements{$name} eq 'checkbox')) {
1907: $output .= qq|
1908: courseForm.elements['$name']\[i].checked = false;|;
1909: }
1910: $output .= qq|
1911: }
1912: for (var j=0; j<courseForm.elements['$name'].length; j++) {
1913: |;
1914: foreach my $value (@{$values{$name}}) {
1915: if ($$elements{$name} eq 'selectbox') {
1916: $output .= qq|
1917: if (courseForm.elements['$name'].options[j].value == "$value") {
1918: courseForm.elements['$name'].options[j].selected = true;
1919: }|;
1920: } elsif (($$elements{$name} eq 'radio') ||
1921: ($$elements{$name} eq 'checkbox')) {
1922: $output .= qq|
1923: if (courseForm.elements['$name']\[j].value == "$value") {
1924: courseForm.elements['$name']\[j].checked = true;
1925: }|;
1926: }
1927: }
1928: $output .= qq|
1929: }
1930: }
1931: |;
1932: }
1933: }
1934: $output .= "
1935: }\n";
1936: return $output;
1937: }
1938:
1939: ##############################################
1940: ##############################################
1941:
1942: # javascript_valid_email
1943: #
1944: # Generates javascript to validate an e-mail address.
1945: # Returns a javascript function which accetps a form field as argumnent, and
1946: # returns false if field.value does not satisfy two regular expression matches
1947: # for a valid e-mail address. Backwards compatible with old browsers without
1948: # support for javascript RegExp (just checks for @ in field.value in this case).
1949:
1950: sub javascript_valid_email {
1951: my $scripttag .= <<'END';
1952: function validmail(field) {
1953: var str = field.value;
1954: if (window.RegExp) {
1955: var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
1956: var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$"; //"
1957: var reg1 = new RegExp(reg1str);
1958: var reg2 = new RegExp(reg2str);
1959: if (!reg1.test(str) && reg2.test(str)) {
1960: return true;
1961: }
1962: return false;
1963: }
1964: else
1965: {
1966: if(str.indexOf("@") >= 0) {
1967: return true;
1968: }
1969: return false;
1970: }
1971: }
1972: END
1973: return $scripttag;
1974: }
1975:
1976:
1977:
1978: 1;
1979:
1980: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>