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