File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.343: download - view: text, annotated - select for diffs
Tue Apr 30 15:10:22 2013 UTC (11 years, 1 month ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Internationalization: Richtext Editor

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>