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