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