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