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