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