File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.336: download - view: text, annotated - select for diffs
Mon Dec 3 14:47:30 2012 UTC (11 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Eliminate use of pagepath and pagesymb.
- Information about current map hierarchy found in $env{'form.folderpath'}
  for both .page and .sequence in /uploaded.
- Container type (.sequence or .page) appears in additional fifth colon
  separated field appended to map title. (1 if page, blank otherwise).

    1: # The LearningOnline Network with CAPA
    2: # a pile of common html routines
    3: #
    4: # $Id: lonhtmlcommon.pm,v 1.336 2012/12/03 14:47:30 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ######################################################################
   29: ######################################################################
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: Apache::lonhtmlcommon - routines to do common html things
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: Referenced by other mod_perl Apache modules.
   40: 
   41: =head1 INTRODUCTION
   42: 
   43: lonhtmlcommon is a collection of subroutines used to present information
   44: in a consistent html format, or provide other functionality related to
   45: html.
   46: 
   47: =head2 General Subroutines
   48: 
   49: =over 4
   50: 
   51: =cut 
   52: 
   53: ######################################################################
   54: ######################################################################
   55: 
   56: package Apache::lonhtmlcommon;
   57: 
   58: use strict;
   59: use Time::Local;
   60: use Time::HiRes;
   61: use Apache::lonlocal;
   62: use Apache::lonnet;
   63: use HTML::Entities();
   64: use LONCAPA qw(:DEFAULT :match);
   65: 
   66: sub java_not_enabled {
   67:    return "\n".'<span class="LC_error">'.
   68:           &mt('The required Java applet could not be started. Please make sure to have Java installed and active in your browser.').
   69:           "</span>\n";
   70: }
   71: 
   72: sub coursepreflink {
   73:    my ($text,$category)=@_;
   74:    if (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
   75:       return '<a target="_top" href="'.&HTML::Entities::encode("/adm/courseprefs?phase=display&actions=$category",'<>&"').'"><span class="LC_setting">'.$text.'</span></a>';
   76:    } else {
   77:       return '';
   78:    }
   79: }
   80: 
   81: sub raw_href_to_link {
   82:    my ($message)=@_;
   83:    $message=~s/(https?\:\/\/[^\s\'\"\<]+)([\s\<]|$)/<a href="$1"><tt>$1<\/tt><\/a>$2/gi;
   84:    return $message;
   85: }
   86: 
   87: sub entity_encode {
   88:     my ($text)=@_;
   89:     return &HTML::Entities::encode($text, '<>&"');
   90: }
   91: 
   92: sub direct_parm_link {
   93:     my ($linktext,$symb,$filter,$part,$target)=@_;
   94:     $symb=&entity_encode($symb);
   95:     $filter=&entity_encode($filter);
   96:     $part=&entity_encode($part);
   97:     if (($symb) && (&Apache::lonnet::allowed('opa')) && ($target ne 'tex')) {
   98:        return "<a target='_top' href='/adm/parmset?symb=$symb&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:     $output.='
 1284:     
 1285:     function containsBlockHtml(id) {
 1286: 		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);
 1287:     	return (re >= 0);
 1288:     }
 1289:     
 1290:     function startRichEditor(id) {
 1291:     	CKEDITOR.replace(id, 
 1292:     		{
 1293:     			customConfig: "/ckeditor/loncapaconfig.js",
 1294:                         language : "'.$lang.'",
 1295:                         fullPage : '.$fullpage.',
 1296:     		}
 1297:     	);
 1298:     }
 1299:     
 1300:     function destroyRichEditor(id) {
 1301:     	CKEDITOR.instances[id].destroy();
 1302:     }
 1303:     
 1304:     function editorHandler(event) {
 1305:     	var rawid = $(this).attr("id");
 1306:     	var id = new RegExp("LC_rt_(.*)").exec(rawid)[1];
 1307:     	event.preventDefault();
 1308:     	var rt_enabled  = $(this).hasClass("LC_enable_rt");
 1309:         if (rt_enabled) {
 1310:     		startRichEditor(id);
 1311: 			$("#LC_rt_"+id).html("<b>&laquo; Plain text</b>");
 1312: 			$("#LC_rt_"+id).attr("title", "Disable rich text formatting and edit in plain text");
 1313: 			$("#LC_rt_"+id).addClass("LC_disable_rt");
 1314: 			$("#LC_rt_"+id).removeClass("LC_enable_rt");
 1315:     	} else {
 1316: 			destroyRichEditor(id);
 1317: 			$("#LC_rt_"+id).html("<b>Rich formatting &raquo;</b>");
 1318: 			$("#LC_rt_"+id).attr("title", "Enable rich text formatting (bold, italic, etc.)");
 1319: 			$("#LC_rt_"+id).addClass("LC_enable_rt");
 1320: 			$("#LC_rt_"+id).removeClass("LC_disable_rt");
 1321: 	}';
 1322:     if ($dragmath_prefix ne '') {
 1323:         $output .= "\n                 var visible = '';
 1324:                                        if (rt_enabled) {
 1325:                                            visible = 'none';
 1326:                                        }
 1327:                                        editmath_visibility(id,visible);\n";
 1328:     }
 1329:     $output .= '
 1330:     }
 1331:     $(document).ready(function(){
 1332: 		$(".LC_richAlwaysOn").each(function() {
 1333: 			startRichEditor($(this).attr("id"));
 1334: 		});
 1335: 		$(".LC_richDetectHtml").each(function() {
 1336: 			var id = $(this).attr("id");
 1337:                         var rt_enabled = containsBlockHtml(id);
 1338: 			if(rt_enabled) {
 1339: 				$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Disable rich text formatting and edit in plain text\" class=\"LC_disable_rt\"><b>&laquo; Plain text</b></a></div>");				
 1340: 				startRichEditor(id);
 1341: 				$("#LC_rt_"+id).click(editorHandler);
 1342: 			}
 1343: 			else {
 1344: 				$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Enable rich text formatting (bold, italic, etc.)\" class=\"LC_enable_rt\"><b>Rich formatting &raquo;</b></a></div>");
 1345: 				$("#LC_rt_"+id).click(editorHandler);
 1346: 			}';
 1347:     if ($dragmath_prefix ne '') {
 1348:         $output .= "\n                 var visible = '';
 1349:                                        if (rt_enabled) {
 1350:                                            visible = 'none';
 1351:                                        }
 1352:                                        editmath_visibility(id,visible);\n";
 1353:     }
 1354:     $output .= '
 1355: 		});
 1356: 		$(".LC_richDefaultOn").each(function() {
 1357: 			var id = $(this).attr("id");
 1358: 			$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Disable rich text formatting and edit in plain text\" class=\"LC_disable_rt\"><b>&laquo; Plain text</b></a></div>");				
 1359: 			startRichEditor(id);
 1360: 			$("#LC_rt_"+id).click(editorHandler);
 1361: 		});
 1362: 		$(".LC_richDefaultOff").each(function() {
 1363: 			var id = $(this).attr("id");
 1364: 			$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Enable rich text formatting (bold, italic, etc.)\" class=\"LC_enable_rt\"><b>Rich formatting &raquo;</b></a></div>");
 1365: 			$("#LC_rt_"+id).click(editorHandler);
 1366: 		});
 1367: 
 1368: 
 1369: 	});
 1370: ';
 1371:     $output .= &color_picker;
 1372: 
 1373:     # Code to put a due date countdown in 'duedatecountdown' span.
 1374:     # This is currently located in the breadcrumb headers.
 1375:     # note that the dueDateLayout is internatinoalized below.
 1376:     # Here document is used to support the substitution into the javascript below.
 1377:     # ..which unforunately necessitates escaping the $'s in the javascript.
 1378:     # There are several times of importance
 1379:     #
 1380:     # serverDueDate -  The absolute time at which the problem expires.
 1381:     # serverTime    -  The server's time when the problem finished computing.
 1382:     # clientTime    -  The client's time...as close to serverTime as possible.
 1383:     #                  The clientTime will be slightly later due to
 1384:     #                  1. The latency between problem computation and 
 1385:     #                     the first network action.
 1386:     #                  2. The time required between the page load-start and the actual
 1387:     #                     initial javascript execution that got clientTime.
 1388:     # These are used as follows:
 1389:     #   The difference between clientTime and serverTime are used to 
 1390:     #   correct for differences in clock settings between the browser's system and the
 1391:     #   server's.
 1392:     #
 1393:     #   The difference between clientTime and the time at which the ready() method
 1394:     #   starts executing is used to estimate latencies for page load and submission.
 1395:     #   Since this is an estimate, it is doubled.  The latency estimate + one minute
 1396:     #   is used to determine when the countdown timer turns red to warn the user
 1397:     #   to think about submitting.
 1398: 
 1399:     my $dueDateLayout = &mt('Due in: {dn} {dl} {hnn}{sep}{mnn}{sep}{snn} [_1]',"<span id='submitearly'></span>");
 1400:     my $early = '- <b>'.&mt('Submit Early').'</b>';
 1401:     my $pastdue = '- <b>'.&mt('Past Due').'</b>';
 1402:     $output .= <<JAVASCRIPT;
 1403: 
 1404:     var documentReadyTime;
 1405: 
 1406: \$(document).ready(function() {
 1407:    if (typeof(dueDate) != "undefined") {
 1408:        documentReadyTime = (new Date()).getTime();
 1409:       \$("#duedatecountdown").countdown({until: dueDate, compact: true, 
 1410:          layout: "$dueDateLayout",
 1411:          onTick: function (periods) {
 1412: 	    var latencyEstimate = (documentReadyTime - clientTime) * 2;
 1413:             if(\$.countdown.periodsToSeconds(periods) < (300 + latencyEstimate)) {
 1414:                \$("#submitearly").html("$early");
 1415:                if (\$.countdown.periodsToSeconds(periods) < 1) {
 1416:                     \$("#submitearly").html("$pastdue");
 1417:                }
 1418:             }
 1419:             if(\$.countdown.periodsToSeconds(periods) < (60 + latencyEstimate)) {
 1420:                \$(this).css("color", "red");   //Highlight last minute.
 1421:             }
 1422:          }
 1423:       });
 1424:    }
 1425: });
 1426: 
 1427:     /* This code describes the spellcheck options that will be used for
 1428:        items with class 'spellchecked'.  It is necessary for those objects'
 1429:        to explicitly request checking (e.g. onblur is a nice event for that).
 1430:      */
 1431:      \$(document).ready(function() {
 1432: 	 \$(".spellchecked").spellchecker({
 1433: 	   url: "/ajax/spellcheck",
 1434: 	   lang: "en",                      
 1435: 	   engine: "pspell",
 1436: 	   suggestionBoxPosition: "below",
 1437: 	   innerDocument: true
 1438: 					  });
 1439: 	 \$("textarea.spellchecked").spellchecker({
 1440: 	   url: "/ajax/spellcheck",
 1441: 	   lang: "en",                      
 1442: 	   engine: "pspell",
 1443: 	   suggestionBoxPosition: "below",
 1444: 	   innerDocument: true
 1445: 					  });
 1446: 
 1447: 			});
 1448: 
 1449:     /* the muli colored editor can generate spellcheck with language 'none'
 1450:        to disable spellcheck as well
 1451:     */
 1452:     function doSpellcheck(element, lang) {
 1453: 	if (lang != 'none') {
 1454:  	    \$(element).spellchecker('option', {lang: lang});
 1455: 	    \$(element).spellchecker('check');
 1456:         }
 1457:     }
 1458: 
 1459: 
 1460: JAVASCRIPT
 1461:     if ($dragmath_prefix ne '') {
 1462:         $output .= '
 1463: 
 1464:      function editmath_visibility(id,value) {
 1465: 
 1466:          if ((id == "") || (id == null)) {
 1467:              return;
 1468:          }
 1469:          var mathid = "'.$dragmath_prefix.'_"+id;
 1470:          mathele = document.getElementById(mathid);
 1471:          if (mathele == null) {
 1472:              return;
 1473:          }
 1474:          mathele.style.display = value;
 1475:          var mathhelpicon = "'.$dragmath_prefix.'helpicon'.'_"+id;
 1476:          mathhelpiconele = document.getElementById(mathhelpicon);
 1477:          if (mathhelpiconele == null) {
 1478:              return;
 1479:          }
 1480:          if (value == "none") {
 1481:              mathhelpiconele.src = "'.$dragmath_whitespace.'";
 1482:          } else {
 1483:              mathhelpiconele.src = "'.$dragmath_helpicon.'";
 1484:          }
 1485:      }
 1486: ';
 1487: 
 1488:     }
 1489:     $output.="\nwindow.status='Activated Editfields';\n"
 1490:             .'// ]]>'."\n"
 1491:             .'</script>';
 1492:     return $output;
 1493: }
 1494: 
 1495: # --------------------------------------------------------------------- Blocked
 1496: 
 1497: sub htmlareablocked {
 1498:     unless ($env{'environment.wysiwygeditor'} eq 'on') { return 1; }
 1499:     return 0;
 1500: }
 1501: 
 1502: # ---------------------------------------- Browser capable of running HTMLArea?
 1503: 
 1504: sub htmlareabrowser {
 1505:     return 1;
 1506: }
 1507: 
 1508: #
 1509: # Should the "return to content" link be shown?
 1510: #
 1511: 
 1512: sub show_return_link {
 1513: 
 1514:     unless ($env{'request.course.id'}) { return 0; }
 1515:     if ($env{'request.noversionuri'}=~m{^/priv/} ||
 1516:         $env{'request.uri'}=~m{^/priv/}) { return 1; }
 1517:     return if ($env{'request.noversionuri'} eq '/adm/supplemental');
 1518: 
 1519:     if (($env{'request.noversionuri'} =~ m{^/adm/(viewclasslist|navmaps)($|\?)})
 1520:         || ($env{'request.noversionuri'} =~ m{^/adm/.*/aboutme($|\?)})) {
 1521: 
 1522:         return if ($env{'form.register'});
 1523:     }
 1524:     return (($env{'request.noversionuri'}=~m{^/(res|public)/} &&
 1525:              $env{'request.symb'} eq '')
 1526:             ||
 1527:             ($env{'request.noversionuri'}=~ m{^/cgi-bin/printout.pl})
 1528:             ||
 1529:             (($env{'request.noversionuri'}=~/^\/adm\//) &&
 1530:              ($env{'request.noversionuri'}!~/^\/adm\/wrapper\//) &&
 1531:              ($env{'request.noversionuri'}!~
 1532:               m{^/adm/.*/(smppg|bulletinboard)($|\?)})
 1533:            ));
 1534: }
 1535: 
 1536: 
 1537: ##
 1538: #   Set the dueDate variable...note this is done in the timezone
 1539: #   of the browser.
 1540: #
 1541: # @param epoch relative time at which the problem is due.
 1542: #
 1543: # @return the javascript fragment to set the date:
 1544: #
 1545: sub set_due_date {
 1546:     my $dueStamp = shift;
 1547:     my $duems    = $dueStamp * 1000; # Javascript Date object needs ms not seconds.
 1548: 
 1549:     my $now = time()*1000;
 1550: 
 1551:     # This slightly obscure bit of javascript sets the dueDate variable
 1552:     # to the time in the browser at which the problem was due.  
 1553:     # The code should correct for gross differences between the server
 1554:     # and client's time setting
 1555: 
 1556:      return <<"END";
 1557: 
 1558: <script type="text/javascript">
 1559:   //<![CDATA[
 1560: var serverDueDate = $duems;
 1561: var serverTime    = $now;
 1562: var clientTime    = (new Date()).getTime();
 1563: var dueDate       = new Date(serverDueDate + (clientTime - serverTime));
 1564: 
 1565:   //]]>
 1566: </script>
 1567: 
 1568: END
 1569: }
 1570: ##
 1571: # Sets the time at which the problem finished computing.
 1572: # This just updates the serverTime and clientTime variables above.
 1573: # Calling this in e.g. end_problem provides a better estimate of the
 1574: # difference beetween the server and client time setting as 
 1575: # the difference contains less of the latency/problem compute time.
 1576: #
 1577: sub set_compute_end_time {
 1578: 
 1579:     my $now = time()*1000;	# Javascript times are in ms.
 1580:     return <<"END";
 1581: 
 1582: <script type="text/javascript">
 1583: //<![CDATA[
 1584: serverTime = $now;
 1585: clientTime = (new Date()).getTime();
 1586: //]]>
 1587: </script>
 1588: 
 1589: END
 1590: }
 1591: 
 1592: ############################################################
 1593: ############################################################
 1594: 
 1595: =pod
 1596: 
 1597: =item &breadcrumbs()
 1598: 
 1599: Compiles the previously registered breadcrumbs into an series of links.
 1600: Additionally supports a 'component', which will be displayed on the
 1601: right side of the breadcrumbs enclosing div (without a link).
 1602: A link to help for the component will be included if one is specified.
 1603: 
 1604: All inputs can be undef without problems.
 1605: 
 1606: Inputs: $component (the text on the right side of the breadcrumbs trail),
 1607:         $component_help
 1608:         $menulink (boolean, controls whether to include a link to /adm/menu)
 1609:         $helplink (if 'nohelp' don't include the orange help link)
 1610:         $css_class (optional name for the class to apply to the table for CSS)
 1611:         $no_mt (optional flag, 1 if &mt() is _not_ to be applied to $component
 1612:            when including the text on the right.
 1613: Returns a string containing breadcrumbs for the current page.
 1614: 
 1615: =item &clear_breadcrumbs()
 1616: 
 1617: Clears the previously stored breadcrumbs.
 1618: 
 1619: =item &add_breadcrumb()
 1620: 
 1621: Pushes a breadcrumb on the stack of crumbs.
 1622: 
 1623: input: $breadcrumb, a hash reference.  The keys 'href','title', and 'text'
 1624: are required.  If present the keys 'faq' and 'bug' will be used to provide
 1625: links to the FAQ and bug sites. If the key 'no_mt' is present the 'title' 
 1626: and 'text' values won't be sent through &mt()
 1627: 
 1628: returns: nothing    
 1629: 
 1630: =cut
 1631: 
 1632: ############################################################
 1633: ############################################################
 1634: {
 1635:     my @Crumbs;
 1636:     my %tools = ();
 1637:     
 1638:     sub breadcrumbs {
 1639:         my ($component,$component_help,$menulink,$helplink,$css_class,$no_mt, 
 1640:             $CourseBreadcrumbs) = @_;
 1641:         #
 1642:         $css_class ||= 'LC_breadcrumbs';
 1643: 
 1644:         # Make the faq and bug data cascade
 1645:         my $faq  = '';
 1646:         my $bug  = '';
 1647:         my $help = '';
 1648:         # Crumb Symbol
 1649:         my $crumbsymbol = '&raquo;';
 1650:         # The last breadcrumb does not have a link, so handle it separately.
 1651:         my $last = pop(@Crumbs);
 1652:         #
 1653:         # The first one should be the course or a menu link
 1654:         if (!defined($menulink)) { $menulink=1; }
 1655:         if ($menulink) {
 1656:             my $description = 'Menu';
 1657:             my $no_mt_descr = 0;
 1658:             if ((exists($env{'request.course.id'})) && 
 1659:                 ($env{'request.course.id'} ne '') && 
 1660:                 ($env{'course.'.$env{'request.course.id'}.'.description'} ne '')) {
 1661:                 $description = 
 1662:                     $env{'course.'.$env{'request.course.id'}.'.description'};
 1663:                 $no_mt_descr = 1;
 1664:                 if ($env{'request.noversionuri'} =~ 
 1665:                     m{^/public/($match_domain)/($match_courseid)/syllabus$}) {
 1666:                     unless (($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1) &&
 1667:                             ($env{'course.'.$env{'request.course.id'}.'.num'} eq $2)) {
 1668:                         $description = 'Menu';
 1669:                         $no_mt_descr = 0;
 1670:                     }
 1671:                 }
 1672:             }
 1673:             $menulink =  {  href   =>'/adm/menu',
 1674:                             title  =>'Go to main menu',
 1675:                             target =>'_top',
 1676:                             text   =>$description,
 1677:                             no_mt  =>$no_mt_descr, };
 1678:             if($last) {
 1679:                 #$last set, so we have some crumbs
 1680:                 unshift(@Crumbs,$menulink);
 1681:             } else {
 1682:                 #only menulink crumb present
 1683:                 $last = $menulink;
 1684:             }
 1685:         }
 1686:         my $links;
 1687:         if ((&show_return_link) && (!$CourseBreadcrumbs) && (ref($last) eq 'HASH')) {
 1688:             my $alttext = &mt('Go Back');
 1689:             $links=&htmltag( 'a','<img src="/res/adm/pages/tolastloc.png" alt="'.$alttext.'" class="LC_icon" />',
 1690:                             { href => '/adm/flip?postdata=return:',
 1691:                               title => &mt('Back to most recent content resource'),
 1692:                               class => 'LC_menubuttons_link',
 1693:                             });
 1694:             $links=&htmltag('li',$links);
 1695:         }
 1696:         $links.= join "", 
 1697:              map {
 1698:                  $faq  = $_->{'faq'}  if (exists($_->{'faq'}));
 1699:                  $bug  = $_->{'bug'}  if (exists($_->{'bug'}));
 1700:                  $help = $_->{'help'} if (exists($_->{'help'}));
 1701: 
 1702:                  my $result = $_->{no_mt} ? $_->{text} : &mt($_->{text});
 1703: 
 1704:                  if ($_->{href}){
 1705:                      $result = &htmltag( 'a', $result, 
 1706:                        { href   => $_->{href},
 1707:                          title  => $_->{no_mt} ? $_->{title} : &mt($_->{title}),
 1708:                          target => $_->{target}, });
 1709:                  }
 1710: 
 1711:                  $result = &htmltag( 'li', "$result $crumbsymbol");
 1712:              } @Crumbs;
 1713: 
 1714:         #should the last Element be translated?
 1715: 
 1716:         my $lasttext = $last->{'no_mt'} ? $last->{'text'} 
 1717:                      : mt( $last->{'text'} );
 1718: 
 1719:         # last breadcrumb is the first order heading of a page
 1720:         # for course breadcrumbs it's just bold
 1721: 
 1722:         if ($lasttext ne '') {
 1723:             $links .= &htmltag( 'li', htmltag($CourseBreadcrumbs ? 'b' : 'h1',
 1724:                     $lasttext), {title => $lasttext});
 1725:         }
 1726: 
 1727:         my $icons = '';
 1728:         $faq  = $last->{'faq'}  if (exists($last->{'faq'}));
 1729:         $bug  = $last->{'bug'}  if (exists($last->{'bug'}));
 1730:         $help = $last->{'help'} if (exists($last->{'help'}));
 1731:         $component_help=($component_help?$component_help:$help);
 1732: #        if ($faq ne '') {
 1733: #            $icons .= &Apache::loncommon::help_open_faq($faq);
 1734: #        }
 1735: #        if ($bug ne '') {
 1736: #            $icons .= &Apache::loncommon::help_open_bug($bug);
 1737: #        }
 1738:         if ($faq ne '' || $component_help ne '' || $bug ne '') {
 1739:             $icons .= &Apache::loncommon::help_open_menu($component,
 1740:                                                          $component_help,
 1741:                                                          $faq,$bug);
 1742:         }
 1743:         #
 1744: 
 1745: 		
 1746:         if ($links ne '') {
 1747:             unless ($CourseBreadcrumbs) {
 1748:                 $links = &htmltag('ol',  $links, { id => "LC_MenuBreadcrumbs"   });
 1749:             } else {
 1750:                 $links = &htmltag('ul',  $links, { class => "LC_CourseBreadcrumbs" });
 1751:             }
 1752:         }
 1753: 
 1754: 
 1755:         if ($component) {
 1756:             $links = &htmltag('span', 
 1757:                              ( $no_mt ? $component : mt($component) ).
 1758:                              ( $icons ? $icons : '' ),
 1759:                              { class => 'LC_breadcrumbs_component' } )
 1760:                              .$links 
 1761: ;
 1762:         }
 1763:         
 1764:         &render_tools(\$links);
 1765:         $links = &htmltag('div', $links, 
 1766:                         { id => "LC_breadcrumbs" }) unless ($CourseBreadcrumbs) ;
 1767:         &render_advtools(\$links);
 1768: 
 1769:         # Return the @Crumbs stack to what we started with
 1770:         push(@Crumbs,$last);
 1771:         shift(@Crumbs);
 1772: 
 1773: 
 1774:         # Return the breadcrumb's line
 1775: 
 1776:     
 1777: 
 1778:         return "$links";
 1779:     }
 1780: 
 1781:     sub clear_breadcrumbs {
 1782:         undef(@Crumbs);
 1783:         undef(%tools);
 1784:     }
 1785: 
 1786:     sub add_breadcrumb {
 1787:         push(@Crumbs,@_);
 1788:     }
 1789:     
 1790: =item &add_breadcrumb_tool($category, $html)
 1791: 
 1792: Adds $html to $category of the breadcrumb toolbar container.
 1793: 
 1794: $html is usually a link to a page that invokes a function on the currently 
 1795: displayed data (e.g. print when viewing a problem)
 1796: 
 1797: Currently there are 3 possible values for $category: 
 1798: 
 1799: =over 
 1800: 
 1801: =item navigation 
 1802: left of breadcrumbs line
 1803: 
 1804: =item tools 
 1805: remaining items in right of breadcrumbs line
 1806: 
 1807: =item advtools 
 1808: advanced tools shown in a separate box below breadcrumbs line 
 1809: 
 1810: =back
 1811:  
 1812: returns: nothing
 1813: 
 1814: =cut
 1815: 
 1816:     sub add_breadcrumb_tool {
 1817:         my ($category, @html) = @_;
 1818:         return unless @html;
 1819:         if (!keys(%tools)) { 
 1820:             %tools = ( navigation => [], tools => [], advtools => []);
 1821:         }
 1822: 
 1823:         #this cleans data received from lonmenu::innerregister
 1824:         @html = grep {defined $_ && $_ ne ''} @html;
 1825:         for (@html) { 
 1826:             s/align="(right|left)"//; 
 1827: #            s/<span.*?\/span>// if $category ne 'advtools'; 
 1828:         } 
 1829: 
 1830:         push @{$tools{$category}}, @html;
 1831:     }
 1832: 
 1833: =item &clear_breadcrumb_tools()
 1834: 
 1835: Clears the breadcrumb toolbar container.
 1836: 
 1837: returns: nothing
 1838: 
 1839: =cut
 1840: 
 1841:     sub clear_breadcrumb_tools {
 1842:         undef(%tools);
 1843:     }
 1844: 
 1845: =item &render_tools(\$breadcrumbs)
 1846: 
 1847: Creates html for breadcrumb tools (categories navigation and tools) and inserts 
 1848: \$breadcrumbs at the correct position.
 1849: 
 1850: input: \$breadcrumbs - a reference to the string containing prepared 
 1851: breadcrumbs.
 1852: 
 1853: returns: nothing
 1854: 
 1855: =cut
 1856: 
 1857: #TODO might split this in separate functions for each category
 1858:     sub render_tools {
 1859:         my ($breadcrumbs) = @_;
 1860:         return unless (keys(%tools));
 1861: 
 1862:         my $navigation = list_from_array($tools{navigation}, 
 1863:                    { listattr => { class=>"LC_breadcrumb_tools_navigation" } });
 1864:         my $tools = list_from_array($tools{tools}, 
 1865:                    { listattr => { class=>"LC_breadcrumb_tools_tools" } });
 1866:         $$breadcrumbs = list_from_array([$navigation, $tools, $$breadcrumbs], 
 1867:                    { listattr => { class=>'LC_breadcrumb_tools_outerlist' } });
 1868:     }
 1869: 
 1870: =pod
 1871: 
 1872: =item &render_advtools(\$breadcrumbs)
 1873: 
 1874: Creates html for advanced tools (category advtools) and inserts \$breadcrumbs 
 1875: at the correct position.
 1876: 
 1877: input: \$breadcrumbs - a reference to the string containing prepared 
 1878: breadcrumbs (after render_tools call).
 1879: 
 1880: returns: nothing
 1881: 
 1882: =cut
 1883: 
 1884:     sub render_advtools {
 1885:         my ($breadcrumbs) = @_;
 1886:         return unless     (defined $tools{'advtools'}) 
 1887:                       and (scalar(@{$tools{'advtools'}}) > 0);
 1888: 
 1889:         $$breadcrumbs .= Apache::loncommon::head_subbox(
 1890:                             funclist_from_array($tools{'advtools'}) );
 1891:     }
 1892: 
 1893: } # End of scope for @Crumbs
 1894: 
 1895: sub docs_breadcrumbs {
 1896:     my ($allowed,$crstype,$contenteditor,$title,$precleared)=@_;
 1897:     my ($folderpath,@folders);
 1898:     my @folders = split('&',$env{'form.folderpath'});
 1899:     my $plain='';
 1900:     my $container = 'sequence';
 1901:     my ($randompick,$isencrypted,$ishidden,$is_random_order) = (-1,0,0,0);
 1902:     my @docs_crumbs;
 1903:     while (@folders) {
 1904:         my $folder=shift(@folders);
 1905:         my $foldername=shift(@folders);
 1906:         if ($folderpath) {$folderpath.='&';}
 1907:         $folderpath.=$folder.'&'.$foldername;
 1908:         my $url;
 1909:         if ($allowed) {
 1910:             $url = '/adm/coursedocs?folderpath=';
 1911:         } else {
 1912:             $url = '/adm/supplemental?folderpath=';
 1913:         }
 1914:         $url .= &escape($folderpath);
 1915:         my $name=&unescape($foldername);
 1916: # each of randompick number, hidden, encrypted, random order, is_page 
 1917: # are appended with ":"s to the foldername
 1918:         $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)\:?(\d*)$//;
 1919:         if ($contenteditor) { 
 1920:             if ($1 ne '') {
 1921:                 $randompick=$1;
 1922:             } else {
 1923:                $randompick=-1;
 1924:             }
 1925:             if ($2) { $ishidden=1; }
 1926:             if ($3) { $isencrypted=1; }
 1927:             if ($4 ne '') { $is_random_order = 1; }
 1928:             if ($5 == 1) {$container = 'page'; }
 1929:         }
 1930:         if ($folder eq 'supplemental') {
 1931:             $name = &mt('Supplemental '.$crstype.' Contents');
 1932:         }
 1933:         if ($contenteditor) {
 1934:             $plain.=$name.' &gt; ';
 1935:         }
 1936:         push(@docs_crumbs,
 1937:                           {'href'  => $url,
 1938:                            'title' => $name,
 1939:                            'text'  => $name,
 1940:                            'no_mt' => 1,
 1941:                           });
 1942:     }
 1943:     if ($title) {
 1944:         push(@docs_crumbs,
 1945:                           {'title' => $title,
 1946:                            'text'  => $title,
 1947:                            'no_mt' => 1,}
 1948:                           );
 1949:     }
 1950:     if (wantarray) {
 1951:         unless ($precleared) {
 1952:             &clear_breadcrumbs();
 1953:         }
 1954:         &add_breadcrumb(@docs_crumbs);
 1955:         if ($contenteditor) {
 1956:             $plain=~s/\&gt\;\s*$//;
 1957:         }
 1958:         my $menulink = 0;
 1959:         if (!$allowed && !$contenteditor) {
 1960:             $menulink = 1;
 1961:         }
 1962:         return (&breadcrumbs(undef,undef,$menulink,'nohelp',undef,undef,
 1963:                              $contenteditor),
 1964:                              $randompick,$ishidden,$isencrypted,$plain,
 1965:                              $is_random_order,$container);
 1966:     } else {
 1967:         return \@docs_crumbs;
 1968:     }
 1969: }
 1970: 
 1971: ############################################################
 1972: ############################################################
 1973: 
 1974: # Nested table routines.
 1975: #
 1976: # Routines to display form items in a multi-row table with 2 columns.
 1977: # Uses nested tables to divide form elements into segments.
 1978: # For examples of use see loncom/interface/lonnotify.pm 
 1979: #
 1980: # Can be used in following order: ...
 1981: # &start_pick_box()
 1982: # row1
 1983: # row2
 1984: # row3   ... etc.
 1985: # &submit_row()
 1986: # &end_pick_box()
 1987: #
 1988: # where row1, row 2 etc. are chosen from &role_select_row,&course_select_row,
 1989: # &status_select_row and &email_default_row
 1990: #
 1991: # Can also be used in following order:
 1992: #
 1993: # &start_pick_box()
 1994: # &row_title()
 1995: # &row_closure()
 1996: # &row_title()
 1997: # &row_closure()  ... etc.
 1998: # &submit_row()
 1999: # &end_pick_box()
 2000: #
 2001: # In general a &submit_row() call should proceed the call to &end_pick_box(),
 2002: # as this routine adds a button for form submission.
 2003: # &submit_row() does not require a &row_closure after it.
 2004: #  
 2005: # &start_pick_box() creates a bounding table with 1-pixel wide black border.
 2006: # rows should be placed between calls to &start_pick_box() and &end_pick_box.
 2007: #
 2008: # &row_title() adds a title in the left column for each segment.
 2009: # &row_closure() closes a row with a 1-pixel wide black line.
 2010: #
 2011: # &role_select_row() provides a select box from which to choose 1 or more roles 
 2012: # &course_select_row provides ways of picking groups of courses
 2013: #    radio buttons: all, by category or by picking from a course picker pop-up
 2014: #      note: by category option is only displayed if a domain has implemented 
 2015: #                selection by year, semester, department, number etc.
 2016: #
 2017: # &status_select_row() provides a select box from which to choose 1 or more
 2018: #  access types (current access, prior access, and future access)  
 2019: #
 2020: # &email_default_row() provides text boxes for default e-mail suffixes for
 2021: #  different authentication types in a domain.
 2022: #
 2023: # &row_title() and &row_closure() are called internally by the &*_select_row
 2024: # routines, but can also be called directly to start and end rows which have 
 2025: # needs that are not accommodated by the *_select_row() routines.    
 2026: 
 2027: { # Start: row_count block for pick_box
 2028: my @row_count;
 2029: 
 2030: sub start_pick_box {
 2031:     my ($css_class,$id) = @_;
 2032:     if (defined($css_class)) {
 2033: 	$css_class = 'class="'.$css_class.'"';
 2034:     } else {
 2035: 	$css_class= 'class="LC_pick_box"';
 2036:     }
 2037:     my $table_id;
 2038:     if (defined($id)) {
 2039:         $table_id = ' id="'.$id.'"';
 2040:     }
 2041:     unshift(@row_count,0);
 2042:     my $output = <<"END";
 2043:  <table $css_class $table_id>
 2044: END
 2045:     return $output;
 2046: }
 2047: 
 2048: sub end_pick_box {
 2049:     shift(@row_count);
 2050:     my $output = <<"END";
 2051:        </table>
 2052: END
 2053:     return $output;
 2054: }
 2055: 
 2056: sub row_headline {
 2057:     my $output = <<"END";
 2058:            <tr><td colspan="2">
 2059: END
 2060:     return $output;
 2061: }
 2062: 
 2063: sub row_title {
 2064:     my ($title,$css_title_class,$css_value_class, $css_value_furtherAttributes) = @_;
 2065:     $row_count[0]++;
 2066:     my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 2067:     $css_title_class ||= 'LC_pick_box_title';
 2068:     $css_title_class = 'class="'.$css_title_class.'"';
 2069: 
 2070:     $css_value_class ||= 'LC_pick_box_value';
 2071: 
 2072:     if ($title ne '') {
 2073:         $title .= ':';
 2074:     }
 2075:     my $output = <<"ENDONE";
 2076:            <tr class="LC_pick_box_row" $css_value_furtherAttributes> 
 2077:             <td $css_title_class>
 2078: 	       $title
 2079:             </td>
 2080:             <td class="$css_value_class $css_class">
 2081: ENDONE
 2082:     return $output;
 2083: }
 2084: 
 2085: sub row_closure {
 2086:     my ($no_separator) =@_;
 2087:     my $output = <<"ENDTWO";
 2088:             </td>
 2089:            </tr>
 2090: ENDTWO
 2091:     if (!$no_separator) {
 2092:         $output .= <<"ENDTWO";
 2093:            <tr>
 2094:             <td colspan="2" class="LC_pick_box_separator">
 2095:             </td>
 2096:            </tr>
 2097: ENDTWO
 2098:     }
 2099:     return $output;
 2100: }
 2101: 
 2102: } # End: row_count block for pick_box
 2103: 
 2104: sub role_select_row {
 2105:     my ($roles,$title,$css_class,$show_separate_custom,$cdom,$cnum) = @_;
 2106:     my $crstype = 'Course';
 2107:     if ($cdom ne '' && $cnum ne '') {
 2108:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2109:     }
 2110:     my $output;
 2111:     if (defined($title)) {
 2112:         $output = &row_title($title,$css_class);
 2113:     }
 2114:     $output .= qq|
 2115:                                   <select name="roles" multiple="multiple">\n|;
 2116:     foreach my $role (@$roles) {
 2117:         my $plrole;
 2118:         if ($role eq 'ow') {
 2119:             $plrole = &mt('Course Owner');
 2120:         } elsif ($role eq 'cr') {
 2121:             if ($show_separate_custom) {
 2122:                 if ($cdom ne '' && $cnum ne '') {
 2123:                     my %course_customroles = &course_custom_roles($cdom,$cnum);
 2124:                     foreach my $crrole (sort(keys(%course_customroles))) {
 2125:                         my ($plcrrole) = ($crrole =~ m|^cr/[^/]+/[^/]+/(.+)$|);
 2126:                         $output .= '  <option value="'.$crrole.'">'.$plcrrole.
 2127:                                    '</option>';
 2128:                     }
 2129:                 }
 2130:             } else {
 2131:                 $plrole = &mt('Custom Role');
 2132:             }
 2133:         } else {
 2134:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 2135:         }
 2136:         if (($role ne 'cr') || (!$show_separate_custom)) {
 2137:             $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
 2138:         }
 2139:     }
 2140:     $output .= qq|                </select>\n|;
 2141:     if (defined($title)) {
 2142:         $output .= &row_closure();
 2143:     }
 2144:     return $output;
 2145: }
 2146: 
 2147: sub course_select_row {
 2148:     my ($title,$formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 2149: 	$css_class,$crstype,$standardnames) = @_;
 2150:     my $output = &row_title($title,$css_class);
 2151:     $output .= &course_selection($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype,$standardnames);
 2152:     $output .= &row_closure();
 2153:     return $output;
 2154: }
 2155: 
 2156: sub course_selection {
 2157:     my ($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype,$standardnames) = @_;
 2158:     my $output = qq|
 2159: <script type="text/javascript">
 2160: // <![CDATA[
 2161:     function coursePick (formname) {
 2162:         for  (var i=0; i<formname.coursepick.length; i++) {
 2163:             if (formname.coursepick[i].value == 'category') {
 2164:                 courseSet('');
 2165:             }
 2166:             if (!formname.coursepick[i].checked) {
 2167:                 if (formname.coursepick[i].value == 'specific') {
 2168:                     formname.coursetotal.value = 0;
 2169:                     formname.courselist = '';
 2170:                 }
 2171:             }
 2172:         }
 2173:     }
 2174:     function setPick (formname) {
 2175:         for  (var i=0; i<formname.coursepick.length; i++) {
 2176:             if (formname.coursepick[i].value == 'category') {
 2177:                 formname.coursepick[i].checked = true;
 2178:             }
 2179:             formname.coursetotal.value = 0;
 2180:             formname.courselist = '';
 2181:         }
 2182:     }
 2183: // ]]>
 2184: </script>
 2185:     |;
 2186: 
 2187:     my ($allcrs,$pickspec);
 2188:     if ($crstype eq 'Community') {
 2189:         $allcrs = &mt('All communities');
 2190:         $pickspec = &mt('Pick specific communities:');
 2191:     } else {
 2192:         $allcrs = &mt('All courses');
 2193:         $pickspec = &mt('Pick specific course(s):');
 2194:     }
 2195: 
 2196:     my $courseform='<b>'.&Apache::loncommon::selectcourse_link
 2197:                      ($formname,'pickcourse','pickdomain','coursedesc','',1,$crstype).'</b>';
 2198:         $output .= '<input type="radio" name="coursepick" value="all" onclick="coursePick(this.form)" />'.$allcrs.'<br />';
 2199:     if ($totcodes > 0) {
 2200:         my $numtitles = @$codetitles;
 2201:         if ($numtitles > 0) {
 2202:             $output .= '<input type="radio" name="coursepick" value="category" onclick="coursePick(this.form);alert('."'".&mt('Choose categories, from left to right')."'".')" />'.&mt('Pick courses by category:').' <br />';
 2203:             $output .= '<table><tr><td>'.$$codetitles[0].'<br />'."\n".
 2204:                '<select name="'.$standardnames->[0].
 2205:                '" onChange="setPick(this.form);courseSet('."'$$codetitles[0]'".')">'."\n".
 2206:                ' <option value="-1" />Select'."\n";
 2207:             my @items = ();
 2208:             my @longitems = ();
 2209:             if ($$idlist{$$codetitles[0]} =~ /","/) {
 2210:                 @items = split(/","/,$$idlist{$$codetitles[0]});
 2211:             } else {
 2212:                 $items[0] = $$idlist{$$codetitles[0]};
 2213:             }
 2214:             if (defined($$idlist_titles{$$codetitles[0]})) {
 2215:                 if ($$idlist_titles{$$codetitles[0]} =~ /","/) {
 2216:                     @longitems = split(/","/,$$idlist_titles{$$codetitles[0]});
 2217:                 } else {
 2218:                     $longitems[0] = $$idlist_titles{$$codetitles[0]};
 2219:                 }
 2220:                 for (my $i=0; $i<@longitems; $i++) {
 2221:                     if ($longitems[$i] eq '') {
 2222:                         $longitems[$i] = $items[$i];
 2223:                     }
 2224:                 }
 2225:             } else {
 2226:                 @longitems = @items;
 2227:             }
 2228:             for (my $i=0; $i<@items; $i++) {
 2229:                 $output .= ' <option value="'.$items[$i].'">'.$longitems[$i].'</option>';
 2230:             }
 2231:             $output .= '</select></td>';
 2232:             for (my $i=1; $i<$numtitles; $i++) {
 2233:                 $output .= '<td>'.$$codetitles[$i].'<br />'."\n".
 2234:                           '<select name="'.$standardnames->[$i].
 2235:                           '" onChange="courseSet('."'$$codetitles[$i]'".')">'."\n".
 2236:                           '<option value="-1">&lt;-Pick '.$$codetitles[$i-1].'</option>'."\n".
 2237:                           '</select>'."\n".
 2238:                           '</td>';
 2239:             }
 2240:             $output .= '</tr></table><br />';
 2241:         }
 2242:     }
 2243:     $output .= '<input type="radio" name="coursepick" value="specific" onclick="coursePick(this.form);opencrsbrowser('."'".$formname."','dccourse','dcdomain','coursedesc','','1','$crstype'".')" />'.$pickspec.' '.$courseform.'&nbsp;&nbsp;<input type="text" value="0" size="4" name="coursetotal" /><input type="hidden" name="courselist" value="" />selected.<br />'."\n";
 2244:     return $output;
 2245: }
 2246: 
 2247: sub status_select_row {
 2248:     my ($types,$title,$css_class) = @_;
 2249:     my $output; 
 2250:     if (defined($title)) {
 2251:         $output = &row_title($title,$css_class,'LC_pick_box_select');
 2252:     }
 2253:     $output .= qq|
 2254:                                     <select name="types" multiple="multiple">\n|;
 2255:     foreach my $status_type (sort(keys(%{$types}))) {
 2256:         $output .= '  <option value="'.$status_type.'">'.$$types{$status_type}.'</option>';
 2257:     }
 2258:     $output .= qq|                   </select>\n|; 
 2259:     if (defined($title)) {
 2260:         $output .= &row_closure();
 2261:     }
 2262:     return $output;
 2263: }
 2264: 
 2265: sub email_default_row {
 2266:     my ($authtypes,$title,$descrip,$css_class) = @_;
 2267:     my $output = &row_title($title,$css_class);
 2268:     $output .= $descrip.
 2269: 	&Apache::loncommon::start_data_table().
 2270: 	&Apache::loncommon::start_data_table_header_row().
 2271: 	'<th>'.&mt('Authentication Method').'</th>'.
 2272: 	'<th align="right">'.&mt('Username -> e-mail conversion').'</th>'."\n".
 2273: 	&Apache::loncommon::end_data_table_header_row();
 2274:     my $rownum = 0;
 2275:     foreach my $auth (sort(keys(%{$authtypes}))) {
 2276:         my ($userentry,$size);
 2277:         if ($auth =~ /^krb/) {
 2278:             $userentry = '';
 2279:             $size = 25;
 2280:         } else {
 2281:             $userentry = 'username@';
 2282:             $size = 15;
 2283:         }
 2284:         $output .= &Apache::loncommon::start_data_table_row().
 2285: 	    '<td>  '.$$authtypes{$auth}.'</td>'.
 2286: 	    '<td align="right">'.$userentry.
 2287: 	    '<input type="text" name="'.$auth.'" size="'.$size.'" /></td>'.
 2288: 	    &Apache::loncommon::end_data_table_row();
 2289:     }
 2290:     $output .= &Apache::loncommon::end_data_table();
 2291:     $output .= &row_closure();
 2292:     return $output;
 2293: }
 2294: 
 2295: 
 2296: sub submit_row {
 2297:     my ($title,$cmd,$submit_text,$css_class) = @_;
 2298:     my $output = &row_title($title,$css_class,'LC_pick_box_submit');
 2299:     $output .= qq|
 2300:              <br />
 2301:              <input type="hidden" name="command" value="$cmd" />
 2302:              <input type="submit" value="$submit_text"/> &nbsp;
 2303:              <br /><br />
 2304:             \n|;
 2305:     return $output;
 2306: }
 2307: 
 2308: sub course_custom_roles {
 2309:     my ($cdom,$cnum) = @_;
 2310:     my %returnhash=();
 2311:     my %coursepersonnel=&Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 2312:     foreach my $person (sort(keys(%coursepersonnel))) {
 2313:         my ($role) = ($person =~ /^([^:]+):/);
 2314:         my ($end,$start) = split(/:/,$coursepersonnel{$person});
 2315:         if ($end == -1 && $start == -1) {
 2316:             next;
 2317:         }
 2318:         if ($role =~ m|^cr/[^/]+/[^/]+/[^/]|) {
 2319:             $returnhash{$role} ++;
 2320:         }
 2321:     }
 2322:     return %returnhash;
 2323: }
 2324: 
 2325: 
 2326: sub resource_info_box {
 2327:    my ($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp)=@_;
 2328:    my $return='';
 2329:    if ($stuvcurrent ne '') {
 2330:        $return = '<div class="LC_left_float">';
 2331:    }
 2332:    if ($symb) {
 2333:        $return.=&Apache::loncommon::start_data_table();
 2334:        my ($map,$id,$resource)=&Apache::lonnet::decode_symb($symb);
 2335:        my $folder=&Apache::lonnet::gettitle($map);
 2336:        $return.=&Apache::loncommon::start_data_table_row().
 2337:                     '<th align="left">'.&mt('Folder:').'</th><td>'.$folder.'</td>'.
 2338:                     &Apache::loncommon::end_data_table_row();
 2339:        unless ($onlyfolderflag) {
 2340:           $return.=&Apache::loncommon::start_data_table_row().
 2341:                     '<th align="left">'.&mt('Resource:').'</th><td>'.&Apache::lonnet::gettitle($symb).'</td>'.
 2342:                     &Apache::loncommon::end_data_table_row();
 2343:        }
 2344:        if ($stuvcurrent ne '') {
 2345:            $return .= &Apache::loncommon::start_data_table_row().
 2346:                     '<th align="left">'.&mt("Student's current version:").'</th><td>'.$stuvcurrent.'</td>'.
 2347:                     &Apache::loncommon::end_data_table_row();
 2348:        }
 2349:        if ($stuvdisp ne '') {
 2350:            $return .= &Apache::loncommon::start_data_table_row().
 2351:                     '<th align="left">'.&mt("Student's version displayed:").'</th><td>'.$stuvdisp.'</td>'.
 2352:                     &Apache::loncommon::end_data_table_row();
 2353:        }
 2354:        $return.=&Apache::loncommon::end_data_table();
 2355:     } else {
 2356:        $return='<p><span class="LC_error">'.&mt('No context provided.').'</span></p>';
 2357:     }
 2358:     if ($stuvcurrent ne '') {
 2359:         $return .= '</div>';
 2360:     }
 2361:     return $return;
 2362: }
 2363: 
 2364: ##############################################
 2365: ##############################################
 2366: 
 2367: # topic_bar
 2368: #
 2369: # Generates a div containing an (optional) number with a white background followed by a 
 2370: # title with a background color defined in the corresponding CSS: LC_topic_bar
 2371: # Inputs:
 2372: # 1. number to display.
 2373: #    If input for number is empty only the title will be displayed. 
 2374: # 2. title text to display.
 2375: # 3. optional id for the <div>
 2376: # Outputs - a scalar containing html mark-up for the div.
 2377: 
 2378: sub topic_bar {
 2379:     my ($num,$title,$id) = @_;
 2380:     my $number = '';
 2381:     if ($num ne '') {
 2382:         $number = '<span>'.$num.'</span>';
 2383:     }
 2384:     if ($id ne '') {
 2385:         $id = 'id="'.$id.'"';
 2386:     }
 2387:     return '<div class="LC_topic_bar" '.$id.'>'.$number.$title.'</div>';
 2388: }
 2389: 
 2390: ##############################################
 2391: ##############################################
 2392: # echo_form_input
 2393: #
 2394: # Generates html markup to add form elements from the referrer page
 2395: # as hidden form elements (values encoded) in the new page.
 2396: #
 2397: # Intended to support two types of use 
 2398: # (a) to allow backing up to earlier pages in a multi-page 
 2399: # form submission process using a breadcrumb trail.
 2400: #
 2401: # (b) to allow the current page to be reloaded with form elements
 2402: # set on previous page to remain unchanged.  An example would
 2403: # be where the a page containing a dynamically-built table of data is 
 2404: # is to be redisplayed, with only the sort order of the data changed. 
 2405: #  
 2406: # Inputs:
 2407: # 1. Reference to array of form elements in the submitted form on 
 2408: # the referrer page which are to be excluded from the echoed elements.
 2409: #
 2410: # 2. Reference to array of regular expressions, which if matched in the  
 2411: # name of the form element n the referrer page will be omitted from echo. 
 2412: #
 2413: # Outputs: A scalar containing the html markup for the echoed form
 2414: # elements (all as hidden elements, with values encoded). 
 2415: 
 2416: 
 2417: sub echo_form_input {
 2418:     my ($excluded,$regexps) = @_;
 2419:     my $output = '';
 2420:     foreach my $key (keys(%env)) {
 2421:         if ($key =~ /^form\.(.+)$/) {
 2422:             my $name = $1;
 2423:             my $match = 0;
 2424:             if (ref($excluded) eq 'ARRAY') {    
 2425:                 next if (grep(/^\Q$name\E$/,@{$excluded}));
 2426:             }
 2427:             if (ref($regexps) eq 'ARRAY') {
 2428:                 if (@{$regexps} > 0) {
 2429:                     foreach my $regexp (@{$regexps}) {
 2430:                         if ($name =~ /$regexp/) {
 2431:                             $match = 1;
 2432:                             last;
 2433:                         }
 2434:                     }
 2435:                 }
 2436:             }
 2437:             next if ($match);
 2438:             if (ref($env{$key}) eq 'ARRAY') {
 2439:                 foreach my $value (@{$env{$key}}) {
 2440:                     $value = &HTML::Entities::encode($value,'<>&"');
 2441:                     $output .= '<input type="hidden" name="'.$name.
 2442:                                '" value="'.$value.'" />'."\n";
 2443:                 }
 2444:             } else {
 2445:                 my $value = &HTML::Entities::encode($env{$key},'<>&"');
 2446:                 $output .= '<input type="hidden" name="'.$name.
 2447:                            '" value="'.$value.'" />'."\n";
 2448:             }
 2449:         }
 2450:     }
 2451:     return $output;
 2452: }
 2453: 
 2454: ##############################################
 2455: ##############################################
 2456: # set_form_elements
 2457: #
 2458: # Generates javascript to set form elements to values based on
 2459: # corresponding values for the same form elements when the page was
 2460: # previously submitted.
 2461: #     
 2462: # Last submission values are read from hidden form elements in referring 
 2463: # page which have the same name, i.e., generated by &echo_form_input(). 
 2464: #
 2465: # Intended to be called by onload event.
 2466: #
 2467: # Inputs:
 2468: # (a) Reference to hash of echoed form elements to be set.
 2469: #
 2470: # In the hash, keys are the form element names, and the values are the
 2471: # element type (selectbox, radio, checkbox or text -for textbox, textarea or
 2472: # hidden).
 2473: #
 2474: # (b) Optional reference to hash of stored elements to be set.
 2475: #
 2476: # If the page being displayed is a page which permits modification of
 2477: # previously stored data, e.g., the first page in a multi-page submission,
 2478: # then if stored is supplied, form elements will be set to the last stored
 2479: # values.  If user supplied values are also available for the same elements
 2480: # these will replace the stored values. 
 2481: #        
 2482: # Output:
 2483: #  
 2484: # javascript function - set_form_elements() which sets form elements,
 2485: # expects an argument: formname - the name of the form according to 
 2486: # the DOM, e.g., document.compose
 2487: 
 2488: sub set_form_elements {
 2489:     my ($elements,$stored) = @_;
 2490:     my %values;
 2491:     my $output .= 'function setFormElements(courseForm) {
 2492: ';
 2493:     if (defined($stored)) {
 2494:         foreach my $name (keys(%{$stored})) {
 2495:             if (exists($$elements{$name})) {
 2496:                 if (ref($$stored{$name}) eq 'ARRAY') {
 2497:                     $values{$name} = $$stored{$name};
 2498:                 } else {
 2499:                     @{$values{$name}} = ($$stored{$name});
 2500:                 }
 2501:             }
 2502:         }
 2503:     }
 2504: 
 2505:     foreach my $key (keys(%env)) {
 2506:         if ($key =~ /^form\.(.+)$/) {
 2507:             my $name = $1;
 2508:             if (exists($$elements{$name})) {
 2509:                 @{$values{$name}} = &Apache::loncommon::get_env_multiple($key);
 2510:             }
 2511:         }
 2512:     }
 2513: 
 2514:     foreach my $name (keys(%values)) {
 2515:         for (my $i=0; $i<@{$values{$name}}; $i++) {
 2516:             $values{$name}[$i] = &HTML::Entities::decode($values{$name}[$i],'<>&"');
 2517:             $values{$name}[$i] =~ s/([\r\n\f]+)/\\n/g;
 2518:             $values{$name}[$i] =~ s/"/\\"/g;
 2519:         }
 2520:         if (($$elements{$name} eq 'text') || ($$elements{$name} eq 'hidden')) {
 2521:             my $numvalues = @{$values{$name}};
 2522:             if ($numvalues > 1) {
 2523:                 my $valuestring = join('","',@{$values{$name}});
 2524:                 $output .= qq|
 2525:   var textvalues = new Array ("$valuestring");
 2526:   var total = courseForm.elements['$name'].length;
 2527:   if (total > $numvalues) {
 2528:       total = $numvalues;
 2529:   }    
 2530:   for (var i=0; i<total; i++) {
 2531:       courseForm.elements['$name']\[i].value = textvalues[i];
 2532:   }
 2533: |;
 2534:             } else {
 2535:                 $output .= qq|
 2536:   courseForm.elements['$name'].value = "$values{$name}[0]";
 2537: |;
 2538:             }
 2539:         } else {
 2540:             $output .=  qq|
 2541:   var elementLength = courseForm.elements['$name'].length;
 2542:   if (elementLength==undefined) {
 2543: |;
 2544:             foreach my $value (@{$values{$name}}) {
 2545:                 if ($$elements{$name} eq 'selectbox') {
 2546:                     $output .=  qq|
 2547:       if (courseForm.elements['$name'].options[0].value == "$value") {
 2548:           courseForm.elements['$name'].options[0].selected = true;
 2549:       }|;
 2550:                 } elsif (($$elements{$name} eq 'radio') ||
 2551:                          ($$elements{$name} eq 'checkbox')) {
 2552:                     $output .= qq|
 2553:       if (courseForm.elements['$name'].value == "$value") {
 2554:           courseForm.elements['$name'].checked = true;
 2555:       } else {
 2556:           courseForm.elements['$name'].checked = false;
 2557:       }|;
 2558:                 }
 2559:             }
 2560:             $output .= qq|
 2561:   }
 2562:   else {
 2563:       for (var i=0; i<courseForm.elements['$name'].length; i++) {
 2564: |;
 2565:             if ($$elements{$name} eq 'selectbox') {
 2566:                 $output .=  qq|
 2567:           courseForm.elements['$name'].options[i].selected = false;|;
 2568:             } elsif (($$elements{$name} eq 'radio') || 
 2569:                      ($$elements{$name} eq 'checkbox')) {
 2570:                 $output .= qq|
 2571:           courseForm.elements['$name']\[i].checked = false;|; 
 2572:             }
 2573:             $output .= qq|
 2574:       }
 2575:       for (var j=0; j<courseForm.elements['$name'].length; j++) {
 2576: |;
 2577:             foreach my $value (@{$values{$name}}) {
 2578:                 if ($$elements{$name} eq 'selectbox') {
 2579:                     $output .=  qq|
 2580:           if (courseForm.elements['$name'].options[j].value == "$value") {
 2581:               courseForm.elements['$name'].options[j].selected = true;
 2582:           }|;
 2583:                 } elsif (($$elements{$name} eq 'radio') ||
 2584:                          ($$elements{$name} eq 'checkbox')) { 
 2585:                       $output .= qq|
 2586:           if (courseForm.elements['$name']\[j].value == "$value") {
 2587:               courseForm.elements['$name']\[j].checked = true;
 2588:           }|;
 2589:                 }
 2590:             }
 2591:             $output .= qq|
 2592:       }
 2593:   }
 2594: |;
 2595:         }
 2596:     }
 2597:     $output .= "
 2598:     return;
 2599: }\n";
 2600:     return $output;
 2601: }
 2602: 
 2603: ##############################################
 2604: ##############################################
 2605: 
 2606: sub file_submissionchk_js {
 2607:     my ($turninpaths,$multiples) = @_;
 2608:     my $overwritewarn = &mt('File(s) you uploaded for your submission will overwrite existing file(s) submitted for this item').'\\n'.
 2609:                       &mt('Continue submission and overwrite the file(s)?');
 2610:     my $delfilewarn = &mt('You have indicated you wish to remove some files previously included in your submission.').'\\n'.
 2611:                       &mt('Continue submission with these files removed?');
 2612:     my ($turninpathtext,$multtext,$arrayindexofjs);
 2613:     if (ref($turninpaths) eq 'HASH') {
 2614:         foreach my $key (sort(keys(%{$turninpaths}))) {
 2615:             $turninpathtext .= "    if (prefix == '$key') {\n".
 2616:                                "        return '$turninpaths->{$key}';\n".
 2617:                                "    }\n";
 2618:         }
 2619:     }
 2620:     $turninpathtext .= "    return '';\n";
 2621:     if (ref($multiples) eq 'HASH') {
 2622:         foreach my $key (sort(keys(%{$multiples}))) {
 2623:             $multtext .= "    if (prefix == '$key') {\n".
 2624:                          "        return '$multiples->{$key}';\n".
 2625:                          "    }\n";
 2626:         }
 2627:     }
 2628:     $multtext .= "    return '';\n";
 2629: 
 2630:     $arrayindexofjs = &Apache::loncommon::javascript_array_indexof();
 2631:     return <<"ENDSCRIPT";
 2632: <script type="text/javascript">
 2633: // <![CDATA[
 2634: 
 2635: function file_submission_check(formname,path,multiresp) {
 2636:     var elemnum = formname.elements.length;
 2637:     if (elemnum == 0) {
 2638:         return true;
 2639:     }
 2640:     var alloverwrites = [];
 2641:     var alldelconfirm = [];
 2642:     var result = [];
 2643:     var submitter;
 2644:     var subprefix;
 2645:     var allsub = getIndexByName(formname,'all_submit');
 2646:     if (allsub == -1) {
 2647:         var idx = getIndexByName(formname,'submitted');
 2648:         if (idx != -1) {
 2649:             var subval = String(formname.elements[idx].value);
 2650:             submitter = subval.replace(/^part_/,'');
 2651:             result = overwritten_check(formname,path,multiresp,submitter);
 2652:             alloverwrites.push.apply(alloverwrites,result['overwrite']);
 2653:             alldelconfirm.push.apply(alldelconfirm,result['delete']);
 2654:         }
 2655:     } else {
 2656:         if (formname.elements[allsub].type == 'submit') {
 2657:             var partsub = /^\\d+\\.\\d+_submit_.+\$/;
 2658:             var allprefixes = [];
 2659:             var allparts = [];
 2660:             for (var i=0; i<formname.elements.length; i++) {
 2661:                 if (formname.elements[i].type == 'submit') {
 2662:                     var elemname = formname.elements[i].name;
 2663:                     var subname = String(elemname);
 2664:                     var savesub = String(elemname);
 2665:                     if (partsub.test(subname)) {
 2666:                         var prefix = subname.replace(/_submit_.+\$/,'');
 2667:                         if (allprefixes.indexOf(prefix) == -1) {
 2668:                             allprefixes.push(prefix);
 2669:                             allparts[prefix] = [];
 2670:                         }
 2671:                         var part = savesub.replace(/^\\d+\\.\\d+_submit_/,'');
 2672:                         allparts[prefix].push(part);
 2673:                     }
 2674:                 }
 2675:             }
 2676:             for (var k=0; k<allprefixes.length; k++) {
 2677:                 var idx = getIndexByName(formname,allprefixes[k]+'_submitted');
 2678:                 if (idx > -1) {
 2679:                     if (formname.elements[idx].value != 'yes') {
 2680:                         submitterval = formname.elements[idx].value;
 2681:                         submitter = submitterval.replace(/^part_/,'');
 2682:                         subprefix = allprefixes[k];
 2683:                         result = overwritten_check(formname,path,multiresp,submitter,subprefix);
 2684:                         alloverwrites.push.apply(alloverwrites,result['overwrite']);
 2685:                         alldelconfirm.push.apply(alldelconfirm,result['delete']);
 2686:                         break;
 2687:                     }
 2688:                 }
 2689:             }
 2690:             if (submitter == '' || submitter == undefined) {
 2691:                 for (var m=0; m<allprefixes.length; m++) {
 2692:                     for (var n=0; n<allparts[allprefixes[m]].length; n++) {
 2693:                         var result = overwritten_check(formname,path,multiresp,allparts[allprefixes[m]][n],allprefixes[m]);
 2694:                         alloverwrites.push.apply(alloverwrites,result['overwrite']);
 2695:                         alldelconfirm.push.apply(alldelconfirm,result['delete']);
 2696:                     }
 2697:                 }
 2698:             }
 2699:         }
 2700:     }
 2701:     if (alloverwrites.length > 0) {
 2702:         if (!confirm("$overwritewarn")) {
 2703:             for (var n=0; n<alloverwrites.length; n++) {
 2704:                 formname.elements[alloverwrites[n]].value = "";
 2705:             }
 2706:             return false;
 2707:         }
 2708:     }
 2709:     if (alldelconfirm.length > 0) {
 2710:         if (!confirm("$delfilewarn")) {
 2711:             for (var p=0; p<alldelconfirm.length; p++) {
 2712:                 formname.elements[alldelconfirm[p]].checked = false;
 2713:             }
 2714:             return false;
 2715:         }
 2716:     }
 2717:     return true;
 2718: }
 2719: 
 2720: function getIndexByName(formname,item) {
 2721:     for (var i=0;i<formname.elements.length;i++) {
 2722:         if (formname.elements[i].name == item) {
 2723:             return i;
 2724:         }
 2725:     }
 2726:     return -1;
 2727: }
 2728: 
 2729: function overwritten_check(formname,path,multiresp,part,prefix) {
 2730:     var result = [];
 2731:     result['overwrite'] = [];
 2732:     result['delete'] = [];
 2733:     var elemnum = formname.elements.length;
 2734:     if (elemnum == 0) {
 2735:         return result;
 2736:     }
 2737:     var uploadstr;
 2738:     var deletestr;
 2739:     if ((prefix != undefined) && (prefix != '')) {
 2740:         var prepend = prefix+'_';
 2741:         uploadstr = new RegExp("^"+prepend+"HWFILE"+part+".+\$");
 2742:         deletestr = new RegExp("^"+prepend+"HWFILE"+part+".+_\\\\d+_delete\$");
 2743:         multiresp = check_for_multiples(prepend);
 2744:         path = check_for_turninpath(prepend);
 2745:     } else {
 2746:         uploadstr = new RegExp("^HWFILE"+part+".+\$");
 2747:         deletestr = new RegExp("^HWFILE"+part+".+_\\\\d+_delete\$");
 2748:     }
 2749:     var alluploads = [];
 2750:     var allchecked = [];
 2751:     var allskipdel = [];
 2752:     var fnametrim = /[^\\/\\\\]+\$/;
 2753:     for (var i=0; i<formname.elements.length; i++) {
 2754:         var id = formname.elements[i].id;
 2755:         if (id != '') {
 2756:             if (uploadstr.test(id)) {
 2757:                 if (formname.elements[i].type == 'file') {
 2758:                     alluploads.push(id);
 2759:                 } else {
 2760:                     if (deletestr.test(id)) {
 2761:                         if (formname.elements[i].type == 'checkbox') {
 2762:                             if (formname.elements[i].checked) {
 2763:                                 allchecked.push(id);
 2764:                             }
 2765:                         }
 2766:                     }
 2767:                 }
 2768:             }
 2769:         }
 2770:     }
 2771:     for (var j=0; j<alluploads.length; j++) {
 2772:         var delstr = new RegExp("^"+alluploads[j]+"_\\\\d+_delete\$");
 2773:         var delboxes = [];
 2774:         for (var k=0; k<formname.elements.length; k++) {
 2775:             var id = formname.elements[k].id;
 2776:             if ((id != '') && (id != undefined)) {
 2777:                 if (delstr.test(id)) {
 2778:                     if (formname.elements[k].type == 'checkbox') {
 2779:                         delboxes.push(id);
 2780:                     }
 2781:                 }
 2782:             }
 2783:         }
 2784:         if (delboxes.length > 0) {
 2785:             if ((formname.elements[alluploads[j]].value != undefined) &&
 2786:                 (formname.elements[alluploads[j]].value != '')) {
 2787:                 var filepath = formname.elements[alluploads[j]].value;
 2788:                 var newfilename = fnametrim.exec(filepath);
 2789:                 if (newfilename != null) {
 2790:                     var filename = String(newfilename);
 2791:                     var nospaces = filename.replace(/\\s+/g,'_');
 2792:                     var nospecials = nospaces.replace(/[^\\/\\w\\.\\-]/g,'');
 2793:                     var cleanfilename = nospecials.replace(/\\.(\\d+\\.)/g,"_\$1");
 2794:                     if (cleanfilename != '') {
 2795:                         var fullpath = path+"/"+cleanfilename;
 2796:                         if (multiresp == 1) {
 2797:                             var partid = String(alluploads[i]);
 2798:                             var subdir = partid.replace(/^\\d*.?\\d*_?HWFILE/,'');
 2799:                             if (subdir != "" && subdir != undefined) {
 2800:                                 fullpath = path+"/"+subdir+"/"+cleanfilename;
 2801:                             }
 2802:                         }
 2803:                         for (var m=0; m<delboxes.length; m++) {
 2804:                             if (fullpath == formname.elements[delboxes[m]].value) {
 2805:                                 if (formname.elements[delboxes[m]].checked) {
 2806:                                     allskipdel.push(delboxes[m]);
 2807:                                 } else {
 2808:                                     result['overwrite'].push(alluploads[j]);
 2809:                                 }
 2810:                                 break;
 2811:                             }
 2812:                         }
 2813:                     }
 2814:                 }
 2815:             }
 2816:         }
 2817:     }
 2818:     if (allchecked.length > 0) {
 2819:         if (allskipdel.length > 0) {
 2820:             for (var n=0; n<allchecked.length; n++) {
 2821:                 if (allskipdel.indexOf(allchecked[n]) == -1) {
 2822:                     result['delete'].push(allchecked[n]);
 2823:                 }
 2824:             }
 2825:         } else {
 2826:             result['delete'].push.apply(result['delete'],allchecked);
 2827:         }
 2828:     }
 2829:     return result;
 2830: }
 2831: 
 2832: function check_for_multiples(prefix) {
 2833: $multtext
 2834: }
 2835: 
 2836: function check_for_turninpath(prefix) {
 2837: $turninpathtext
 2838: }
 2839: 
 2840: // ]]>
 2841: </script>
 2842: 
 2843: $arrayindexofjs
 2844: 
 2845: ENDSCRIPT
 2846: }
 2847: 
 2848: ##############################################
 2849: ##############################################
 2850: 
 2851: sub resize_scrollbox_js {
 2852:     my ($context,$tabidstr) = @_;
 2853:     my (%names,$paddingwfrac,$offsetwfrac,$offsetv,$minw,$minv);
 2854:     if ($context eq 'docs') {
 2855:         %names = (
 2856:                    boxw   => 'contenteditor',
 2857:                    item   => 'contentlist',
 2858:                    header => 'uploadfileresult',
 2859:                    scroll => 'contentscroll',
 2860:                    boxh   => 'contenteditor',
 2861:                  );
 2862:         $paddingwfrac = 0.09; 
 2863:         $offsetwfrac = 0.015;
 2864:         $offsetv = 20;
 2865:         $minw = 250;
 2866:         $minv = 200;
 2867:     } elsif ($context eq 'params') {
 2868:         %names = (
 2869:                    boxw   => 'parameditor',
 2870:                    item   => 'mapmenuinner',
 2871:                    header => 'parmstep1',
 2872:                    scroll => 'mapmenuscroll',
 2873:                    boxh   => 'parmlevel',
 2874:                  );
 2875:         $paddingwfrac = 0.2;
 2876:         $offsetwfrac = 0.015;
 2877:         $offsetv = 80;
 2878:         $minw = 100;
 2879:         $minv = 100; 
 2880:     }
 2881:     my $viewport_js = &Apache::loncommon::viewport_geometry_js();
 2882:     my $output = '
 2883: 
 2884: window.onresize=callResize;
 2885: 
 2886: ';
 2887:     if ($context eq 'docs') {
 2888:         $output .= '
 2889: var activeTab;
 2890: ';
 2891:     }
 2892:     $output .=  <<"FIRST";
 2893: 
 2894: $viewport_js
 2895: 
 2896: function resize_scrollbox(scrollboxname,chkw,chkh) {
 2897:     var scrollboxid = 'div_'+scrollboxname;
 2898:     var scrolltableid = 'table_'+scrollboxname;
 2899:     var scrollbox;
 2900:     var scrolltable;
 2901: 
 2902:     if (document.getElementById("$names{'boxw'}") == null) {
 2903:         return;
 2904:     }
 2905: 
 2906:     if (document.getElementById(scrollboxid) == null) {
 2907:         return;
 2908:     } else {
 2909:         scrollbox = document.getElementById(scrollboxid);
 2910:     }
 2911: 
 2912: 
 2913:     if (document.getElementById(scrolltableid) == null) {
 2914:         return;
 2915:     } else {
 2916:         scrolltable = document.getElementById(scrolltableid);
 2917:     }
 2918: 
 2919:     init_geometry();
 2920:     var vph = Geometry.getViewportHeight();
 2921:     var vpw = Geometry.getViewportWidth();
 2922: 
 2923: FIRST
 2924:     if ($context eq 'docs') {
 2925:         $output .= "
 2926:     var alltabs = ['$tabidstr'];
 2927: ";
 2928:     } elsif ($context eq 'params') {
 2929:         $output .= "
 2930:     if (document.getElementById('$names{'boxh'}') == null) {
 2931:         return;
 2932:     }
 2933: ";
 2934:     }
 2935:     $output .= <<"SECOND";
 2936:     var listwchange;
 2937:     if (chkw == 1) {
 2938:         var boxw = document.getElementById("$names{'boxw'}").offsetWidth;
 2939:         var itemw;
 2940:         var itemid = document.getElementById("$names{'item'}");
 2941:         if (itemid != null) {
 2942:             itemw = itemid.offsetWidth;
 2943:         }
 2944:         var itemwstart = itemw;
 2945: 
 2946:         var scrollboxw = scrollbox.offsetWidth;
 2947:         var scrollboxscrollw = scrollbox.scrollWidth;
 2948: 
 2949:         var offsetw = parseInt(vpw * $offsetwfrac);
 2950:         var paddingw = parseInt(vpw * $paddingwfrac);
 2951: 
 2952:         var minscrollboxw = $minw;
 2953:         var maxcolw = 0;
 2954: SECOND
 2955:     if ($context eq 'docs') {
 2956:         $output .= <<"DOCSONE";
 2957:         var actabw = 0;
 2958:         for (var i=0; i<alltabs.length; i++) {
 2959:             if (activeTab == alltabs[i]) {
 2960:                 actabw = document.getElementById(alltabs[i]).offsetWidth;
 2961:                 if (actabw > maxcolw) {
 2962:                     maxcolw = actabw;
 2963:                 }
 2964:             } else {
 2965:                 if (document.getElementById(alltabs[i]) != null) {
 2966:                     var thistab = document.getElementById(alltabs[i]);
 2967:                     thistab.style.visibility = 'hidden';
 2968:                     thistab.style.display = 'block';
 2969:                     var tabw = document.getElementById(alltabs[i]).offsetWidth;
 2970:                     thistab.style.display = 'none';
 2971:                     thistab.style.visibility = '';
 2972:                     if (tabw > maxcolw) {
 2973:                         maxcolw = tabw;
 2974:                     }
 2975:                 }
 2976:             }
 2977:         }
 2978: DOCSONE
 2979:     } elsif ($context eq 'params') {
 2980:         $output .= <<"PARAMSONE";
 2981:         var parmlevelrows = new Array();
 2982:         var mapmenucells = new Array();
 2983:         parmlevelrows = document.getElementById("$names{'boxh'}").rows;
 2984:         var numrows = parmlevelrows.length;
 2985:         if (numrows > 1) {
 2986:             mapmenucells = parmlevelrows[2].getElementsByTagName('td');
 2987:         }
 2988:         maxcolw = mapmenucells[0].offsetWidth;
 2989: PARAMSONE
 2990:     }
 2991:     $output .= <<"THIRD";
 2992:         if (maxcolw > 0) {
 2993:             var newscrollboxw;
 2994:             if (maxcolw+paddingw+scrollboxscrollw<boxw) {
 2995:                 newscrollboxw = boxw-paddingw-maxcolw;
 2996:                 if (newscrollboxw < minscrollboxw) {
 2997:                     newscrollboxw = minscrollboxw;
 2998:                 }
 2999:                 scrollbox.style.width = newscrollboxw+"px";
 3000:                 if (newscrollboxw != scrollboxw) {
 3001:                     var newitemw = newscrollboxw-offsetw;
 3002:                     itemid.style.width = newitemw+"px";
 3003:                 }
 3004:             } else {
 3005:                 newscrollboxw = boxw-paddingw-maxcolw;
 3006:                 if (newscrollboxw < minscrollboxw) {
 3007:                     newscrollboxw = minscrollboxw;
 3008:                 }
 3009:                 scrollbox.style.width = newscrollboxw+"px";
 3010:                 if (newscrollboxw != scrollboxw) {
 3011:                     var newitemw = newscrollboxw-offsetw;
 3012:                     itemid.style.width = newitemw+"px";
 3013:                 }
 3014:             }
 3015: 
 3016:             if (newscrollboxw != scrollboxw) {
 3017:                 var newscrolltablew = newscrollboxw+offsetw;
 3018:                 scrolltable.style.width = newscrolltablew+"px";
 3019:             }
 3020:         }
 3021: 
 3022:         if (itemid.offsetWidth != itemwstart) {
 3023:             listwchange = 1;
 3024:         }
 3025:     }
 3026:     if ((chkh == 1) || (listwchange)) {
 3027:         var primaryheight = document.getElementById('LC_nav_bar').offsetHeight;
 3028:         var secondaryheight = document.getElementById('LC_secondary_menu').offsetHeight;
 3029:         var crumbsheight = document.getElementById('LC_breadcrumbs').offsetHeight;
 3030:         var dccidheight = 0;
 3031:         if (document.getElementById('dccid') != null) {
 3032:             dccidheight = document.getElementById('dccid').offsetHeight;
 3033:         }
 3034:         var headerheight = 0;
 3035:         if (document.getElementById("$names{'header'}") != null) {
 3036:             headerheight = document.getElementById("$names{'header'}").offsetHeight;
 3037:         }
 3038:         var tabbedheight = document.getElementById("tabbededitor").offsetHeight;
 3039:         var boxheight = document.getElementById("$names{'boxh'}").offsetHeight;
 3040:         var freevspace = vph-(primaryheight+secondaryheight+crumbsheight+dccidheight+headerheight+tabbedheight+boxheight);
 3041: 
 3042:         var scrollboxheight = scrollbox.offsetHeight;
 3043:         var scrollboxscrollheight = scrollbox.scrollHeight;
 3044: 
 3045:         var minvscrollbox = $minv;
 3046:         var offsetv = $offsetv;
 3047:         var newscrollboxheight;
 3048:         if (freevspace < 0) {
 3049:             newscrollboxheight = scrollboxheight+freevspace-offsetv;
 3050:             if (newscrollboxheight < minvscrollbox) {
 3051:                 newscrollboxheight = minvscrollbox;
 3052:             }
 3053:             scrollbox.style.height = newscrollboxheight + "px";
 3054:         } else {
 3055:             if (scrollboxscrollheight > scrollboxheight) {
 3056:                 if (freevspace > offsetv) {
 3057:                     newscrollboxheight = scrollboxheight+freevspace-offsetv;
 3058:                     if (newscrollboxheight < minvscrollbox) {
 3059:                         newscrollboxheight = minvscrollbox;
 3060:                     }
 3061:                     scrollbox.style.height = newscrollboxheight+"px";
 3062:                 }
 3063:             }
 3064:         }
 3065:         scrollboxheight = scrollbox.offsetHeight;
 3066:         var itemh = document.getElementById("$names{'item'}").offsetHeight;
 3067: 
 3068:         if (scrollboxscrollheight <= scrollboxheight) {
 3069:             if ((itemh+offsetv)<scrollboxheight) {
 3070:                 newscrollheight = itemh+offsetv;
 3071:                 scrollbox.style.height = newscrollheight+"px";
 3072:             }
 3073:         }
 3074:     }
 3075:     return;
 3076: }
 3077: 
 3078: function callResize() {
 3079:     var timer;
 3080:     clearTimeout(timer);
 3081:     timer=setTimeout('resize_scrollbox("$names{'scroll'}","1","1")',500);
 3082: }
 3083: 
 3084: THIRD
 3085:     return $output;
 3086: }
 3087: 
 3088: ##############################################
 3089: ##############################################
 3090: 
 3091: sub javascript_jumpto_resource {
 3092:     my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
 3093:                          &mt('Switch server?');
 3094:     return (<<ENDUTILITY)
 3095: 
 3096: function go(url) {
 3097:    if (url!='' && url!= null) {
 3098:        currentURL = null;
 3099:        currentSymb= null;
 3100:        window.location.href=url;
 3101:    }
 3102: }
 3103: 
 3104: function need_switchserver(url) {
 3105:     if (url!='' && url!= null) {
 3106:         if (confirm("$confirm_switch")) {
 3107:             go(url);
 3108:         }
 3109:     }
 3110:     return;
 3111: }
 3112: 
 3113: ENDUTILITY
 3114: 
 3115: }
 3116: 
 3117: sub jump_to_editres {
 3118:     my ($cfile,$home,$switchserver,$forceedit,$forcereg,$symb,$folderpath,
 3119:         $title,$idx,$suppurl) = @_;
 3120:     my $jscall;
 3121:     if ($switchserver) {
 3122:         if ($home) {
 3123:             $cfile = '/adm/switchserver?otherserver='.$home.'&amp;role='.
 3124:                      &HTML::Entities::encode($env{'request.role'},'"<>&');
 3125:             if ($symb) {
 3126:                 $cfile .= '&amp;symb='.&HTML::Entities::encode($symb,'"<>&');
 3127:             } elsif ($folderpath) {
 3128:                 $cfile .= '&amp;folderpath='.&HTML::Entities::encode($folderpath,'"<>&');
 3129:             }
 3130:             if ($forceedit) {
 3131:                 $cfile .= '&amp;forceedit=1';
 3132:             }
 3133:             if ($forcereg) {
 3134:                 $cfile .= '&amp;register=1';
 3135:             }
 3136:             $jscall = "need_switchserver('$cfile');";
 3137:         }
 3138:     } else {
 3139:         unless ($cfile =~ m{^/priv/}) {
 3140:             if ($symb) {
 3141:                 $cfile .= (($cfile=~/\?/)?'&amp;':'?')."symb=$symb";
 3142:             } elsif ($folderpath) {
 3143:                 $cfile .= (($cfile=~/\?/)?'&amp;':'?').
 3144:                           'folderpath='.&HTML::Entities::encode(&escape($folderpath),'"<>&');
 3145:                 if ($title) {
 3146:                     $cfile .= (($cfile=~/\?/)?'&amp;':'?').
 3147:                               'title='.&HTML::Entities::encode(&escape($title),'"<>&');
 3148:                 }
 3149:                 if ($idx) {
 3150:                     $cfile .= (($cfile=~/\?/)?'&amp;':'?').'idx='.$idx;
 3151:                 }
 3152:                 if ($suppurl) {
 3153:                     $cfile .= (($cfile=~/\?/)?'&amp;':'?').
 3154:                               'suppurl='.&HTML::Entities::encode(&escape($suppurl));
 3155:                 }
 3156:             }
 3157:             if ($forceedit) {
 3158:                 $cfile .= (($cfile=~/\?/)?'&amp;':'?').'forceedit=1';
 3159:             }
 3160:             if ($forcereg) {
 3161:                 $cfile .= (($cfile=~/\?/)?'&amp;':'?').'register=1';
 3162:             }
 3163:         }
 3164:         $jscall = "go('$cfile')";
 3165:     }
 3166:     return $jscall;
 3167: }
 3168: 
 3169: ##############################################
 3170: ##############################################
 3171: 
 3172: # javascript_valid_email
 3173: #
 3174: # Generates javascript to validate an e-mail address.
 3175: # Returns a javascript function which accetps a form field as argumnent, and
 3176: # returns false if field.value does not satisfy two regular expression matches
 3177: # for a valid e-mail address.  Backwards compatible with old browsers without
 3178: # support for javascript RegExp (just checks for @ in field.value in this case). 
 3179: 
 3180: sub javascript_valid_email {
 3181:     my $scripttag .= <<'END';
 3182: function validmail(field) {
 3183:     var str = field.value;
 3184:     if (window.RegExp) {
 3185:         var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
 3186:         var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$"; //"
 3187:         var reg1 = new RegExp(reg1str);
 3188:         var reg2 = new RegExp(reg2str);
 3189:         if (!reg1.test(str) && reg2.test(str)) {
 3190:             return true;
 3191:         }
 3192:         return false;
 3193:     }
 3194:     else
 3195:     {
 3196:         if(str.indexOf("@") >= 0) {
 3197:             return true;
 3198:         }
 3199:         return false;
 3200:     }
 3201: }
 3202: END
 3203:     return $scripttag;
 3204: }
 3205: 
 3206: 
 3207: # USAGE: htmltag(element, content, {attribute => value,...});
 3208: #
 3209: # EXAMPLES: 
 3210: #  - htmltag('a', 'this is an anchor', {href  => 'www.example.com', 
 3211: #                                       title => 'this is a title'})
 3212: #
 3213: #  - You might want to set up needed tags like: 
 3214: #
 3215: #     my $h3  = sub { return htmltag( "h3",  @_ ) };
 3216: #
 3217: #    ... and use them: $h3->("This is a headline")
 3218: #
 3219: #  - To set up a couple of tags, see sub inittags
 3220: #
 3221: # NOTES:
 3222: # - Empty elements, such as <br/> are correctly terminated, 
 3223: #   i.e. htmltag('br') returns <br/> 
 3224: # - Empty attributes (title="") are filtered out.
 3225: # - The function will not check for deprecated attributes.
 3226: #
 3227: # OUTPUT: content enclosed in xhtml conform tags
 3228: sub htmltag{
 3229:     return
 3230:         qq|<$_[0]|
 3231:         . join( '', map { qq| $_="${$_[2]}{$_}"| if ${$_[2]}{$_} } keys %{ $_[2] } )
 3232:         . ($_[1] ? qq|>$_[1]</$_[0]>| : qq|/>|). "\n";
 3233: };
 3234: 
 3235: 
 3236: # USAGE: inittags(@tags);
 3237: #
 3238: # EXAMPLES:
 3239: #  - my ($h1, $h2, $h3) = inittags( qw( h1 h2 h3 ) )
 3240: #    $h1->("This is a headline") #Returns: <h1>This is a headline</h1>
 3241: #
 3242: # NOTES: See sub htmltag for further information.
 3243: #
 3244: # OUTPUT: List of subroutines. 
 3245: sub inittags {
 3246:     my @tags = @_;
 3247:     return map { my $tag = $_;
 3248:                  sub { return htmltag( $tag, @_ ) }
 3249:                } @tags;
 3250: }
 3251: 
 3252: 
 3253: # USAGE: scripttag(scriptcode, [start|end|both]);
 3254: #
 3255: # EXAMPLES: 
 3256: #  - scripttag("alert('Hello World!')", 'both') 
 3257: #    returns:
 3258: #    <script type="text/javascript">
 3259: #    // BEGIN LON-CAPA Internal
 3260: #    alert(Hello World!')
 3261: #    // END LON-CAPA Internal
 3262: #    </script>
 3263: #
 3264: # NOTES:
 3265: # - works currently only for javascripts
 3266: #
 3267: # OUTPUT: 
 3268: # Scriptcode properly enclosed in <script> and CDATA tags (and LC
 3269: # Internal markers if 2nd argument is given)
 3270: sub scripttag {
 3271:     my ( $content, $marker ) = @_;
 3272:     return unless defined $content;
 3273: 
 3274:     my $begin = "\n// BEGIN LON-CAPA Internal\n";
 3275:     my $end   = "\n// END LON-CAPA Internal\n";
 3276: 
 3277:     if ($marker) {
 3278:         $content  = $begin . $content if $marker eq 'start' or $marker eq 'both';
 3279:         $content .= $end              if $marker eq 'end'   or $marker eq 'both';
 3280:     }
 3281: 
 3282:     $content = "\n// <![CDATA[\n$content\n// ]]>\n";
 3283: 
 3284:     return htmltag('script', $content, {type => 'text/javascript'});
 3285: };
 3286: 
 3287: =pod
 3288: 
 3289: =item &list_from_array( \@array, { listattr =>{}, itemattr =>{} } )
 3290: 
 3291: Constructs a XHTML list from \@array.
 3292: 
 3293: input: 
 3294: 
 3295: =over
 3296: 
 3297: =item \@array 
 3298: 
 3299: A reference to the array containing text that will be wrapped in <li></li> tags.
 3300: 
 3301: =item { listattr => {}, itemattr =>{} } 
 3302: 
 3303: Attributes for <ul> and <li> passed in as hash references. 
 3304: See htmltag() for more details.
 3305: 
 3306: =back
 3307:  
 3308: returns: XHTML list as String. 
 3309: 
 3310: =cut   
 3311: 
 3312: # \@items, {listattr => { class => 'abc', id => 'xyx' }, itemattr => {class => 'abc', id => 'xyx'}}
 3313: sub list_from_array {
 3314:     my ($items, $args) = @_;
 3315:     return unless (ref($items) eq 'ARRAY');
 3316:     return unless scalar @$items;
 3317:     my ($ul, $li) = inittags( qw(ul li) );
 3318:     my $listitems = join '', map { $li->($_, $args->{itemattr}) } @$items;
 3319:     return $ul->( $listitems, $args->{listattr} );
 3320: }
 3321: 
 3322: 
 3323: ##############################################
 3324: ##############################################
 3325: 
 3326: # generate_menu
 3327: #
 3328: # Generates html markup for a menu. 
 3329: #
 3330: # Inputs:
 3331: # An array of following structure:
 3332: #   ({	categorytitle => 'Categorytitle',
 3333: #	items => [
 3334: #		    {	
 3335: #           linktext    =>	'Text to be displayed',
 3336: #			url	        =>	'URL the link is pointing to, i.e. /adm/site?action=dosomething',
 3337: #			permission  =>	'Contains permissions as returned from lonnet::allowed(),
 3338: #					         must evaluate to true in order to activate the link',
 3339: #			icon        =>  'icon filename',
 3340: #			alttext	    =>	'alt text for the icon',
 3341: #			help	    =>	'Name of the corresponding helpfile',
 3342: #			linktitle   =>	'Description of the link (used for title tag)'
 3343: #		    },
 3344: #		    ...
 3345: #		]
 3346: #   }, 
 3347: #   ...
 3348: #   )
 3349: #
 3350: # Outputs: A scalar containing the html markup for the menu.
 3351: 
 3352: sub generate_menu {
 3353:     my @menu = @_;
 3354:     # subs for specific html elements
 3355:     my ($h3, $div, $ul, $li, $a, $img) = inittags( qw(h3 div ul li a img) ); 
 3356:     
 3357:     my @categories; # each element represents the entire markup for a category
 3358:    
 3359:     foreach my $category (@menu) {
 3360:         my @links;  # contains the links for the current $category
 3361:         foreach my $link (@{$$category{items}}) {
 3362:             next unless $$link{permission};
 3363:             
 3364:             # create the markup for the current $link and push it into @links.
 3365:             # each entry consists of an image and a text optionally followed 
 3366:             # by a help link.
 3367:             my $src;
 3368:             if ($$link{icon} ne '') {
 3369:                 $src = '/res/adm/pages/'.$$link{icon};
 3370:             }
 3371:             push(@links,$li->(
 3372:                         $a->(
 3373:                             $img->("", {
 3374:                                 class => "LC_noBorder LC_middle",
 3375:                                 src   => $src,
 3376:                                 alt   => mt(defined($$link{alttext}) ?
 3377:                                 $$link{alttext} : $$link{linktext})
 3378:                             }), {
 3379:                             href  => $$link{url},
 3380:                             title => mt($$link{linktitle}),
 3381:                             class => 'LC_menubuttons_link'
 3382:                             }).
 3383:                         $a->(mt($$link{linktext}), {
 3384:                             href  => $$link{url},
 3385:                             title => mt($$link{linktitle}),
 3386:                             class => "LC_menubuttons_link"
 3387:                             }).
 3388:                          (defined($$link{help}) ? 
 3389:                          Apache::loncommon::help_open_topic($$link{help}) : ''),
 3390:                          {class => "LC_menubuttons_inline_text"}));
 3391:         }
 3392: 
 3393:         # wrap categorytitle in <h3>, concatenate with 
 3394:         # joined and in <ul> tags wrapped @links
 3395:         # and wrap everything in an enclosing <div> and push it into
 3396:         # @categories
 3397:         # such that each element looks like:
 3398:         # <div><h3>title</h3><ul><li>...</li>...</ul></div>
 3399:         # the category won't be added if there aren't any links
 3400:         push(@categories, 
 3401:             $div->($h3->(mt($$category{categorytitle}), {class=>"LC_hcell"}).
 3402:             $ul->(join('' ,@links),  {class =>"LC_ListStyleNormal" }),
 3403:             {class=>"LC_Box LC_400Box"})) if scalar(@links);
 3404:     }
 3405: 
 3406:     # wrap the joined @categories in another <div> (column layout)
 3407:     return $div->(join('', @categories), {class => "LC_columnSection"});
 3408: }
 3409: 
 3410: ##############################################
 3411: ##############################################
 3412: 
 3413: =pod
 3414: 
 3415: =item &start_funclist()
 3416: 
 3417: Start list of available functions
 3418: 
 3419: Typically used to offer a simple list of available functions
 3420: at top or bottom of page.
 3421: All available functions/actions for the current page
 3422: should be included in this list.
 3423: 
 3424: If the optional headline text is not provided, a default text will be used.
 3425: 
 3426: 
 3427: Related routines:
 3428: =over 4
 3429: add_item_funclist
 3430: end_funclist
 3431: =back
 3432: 
 3433: 
 3434: Inputs: (optional) headline text
 3435: 
 3436: Returns: HTML code with function list start
 3437: 
 3438: =cut
 3439: 
 3440: ##############################################
 3441: ##############################################
 3442: 
 3443: sub start_funclist {
 3444:     my($legendtext)=@_;
 3445:     $legendtext=&mt('Functions') if !$legendtext;
 3446:     return '<ul class="LC_funclist"><li style="font-weight:bold; margin-left:0.8em;">'.$legendtext.'</li>'."\n";
 3447: }
 3448: 
 3449: 
 3450: ##############################################
 3451: ##############################################
 3452: 
 3453: =pod
 3454: 
 3455: =item &add_item_funclist()
 3456: 
 3457: Adds an item to the list of available functions
 3458: 
 3459: Related routines:
 3460: =over 4
 3461: start_funclist
 3462: end_funclist
 3463: =back
 3464: 
 3465: Inputs: content item with text and link to function
 3466: 
 3467: Returns: HTML code with list item for funclist
 3468: 
 3469: =cut
 3470: 
 3471: ##############################################
 3472: ##############################################
 3473: 
 3474: sub add_item_funclist {
 3475:     my($content) = @_;
 3476:     return '<li>'.$content.'</li>'."\n";
 3477: }
 3478: 
 3479: =pod
 3480: 
 3481: =item &end_funclist()
 3482: 
 3483: End list of available functions
 3484: 
 3485: Related routines:
 3486: =over 4
 3487: start_funclist
 3488: add_item_funclist
 3489: =back
 3490: 
 3491: Inputs: ./.
 3492: 
 3493: Returns: HTML code with function list end
 3494: =cut
 3495: 
 3496: sub end_funclist {
 3497:     return "</ul>\n";
 3498: }
 3499: 
 3500: =pod
 3501: 
 3502: =item &funclist_from_array( \@array, {legend => 'text for legend'} )
 3503: 
 3504: Constructs a XHTML list from \@array with the first item being visually
 3505: highlighted and set to the value of legend or 'Functions' if legend is
 3506: empty. 
 3507: 
 3508: =over
 3509: 
 3510: =item \@array
 3511: 
 3512: A reference to the array containing text that will be wrapped in <li></li> tags.
 3513: 
 3514: =item { legend => 'text' }
 3515: 
 3516: A string that's used as visually highlighted first item. 'Functions' is used if
 3517: it's value evaluates to false.
 3518: 
 3519: =back
 3520:  
 3521: returns: XHTML list as string. 
 3522: 
 3523: =back
 3524: 
 3525: =cut  
 3526: 
 3527: sub funclist_from_array {
 3528:     my ($items, $args) = @_;
 3529:     return unless(ref($items) eq 'ARRAY');
 3530:     $args->{legend} ||= mt('Functions');
 3531:     return list_from_array( [$args->{legend}, @$items], 
 3532:                { listattr => {class => 'LC_funclist'} });
 3533: }   
 3534: 
 3535: =pod
 3536: 
 3537: =item &actionbox( \@array )
 3538: 
 3539: Constructs a XHTML list from \@array with the first item being visually
 3540: highlighted and set to the value 'Actions'. The list is wrapped in a division.
 3541: 
 3542: The actionlist is used to offer contextual actions, mostly at the bottom
 3543: of a page, on which the outcome of an processed action is shown,
 3544: e.g. a file operation in Construction Space.
 3545: 
 3546: =over
 3547: 
 3548: =item \@array
 3549: 
 3550: A reference to the array containing text. Details: sub funclist_from_array
 3551: 
 3552: =back
 3553:  
 3554: Returns: XHTML div as string. 
 3555: 
 3556: =back
 3557: 
 3558: =cut  
 3559: 
 3560: sub actionbox {
 3561:     my ($items) = @_;
 3562:     return unless(ref($items) eq 'ARRAY');
 3563:     return
 3564:         '<div class="LC_actionbox">'
 3565:        .&funclist_from_array($items, {legend => &mt('Actions')})
 3566:        .'</div>';
 3567: }
 3568: 
 3569: 1;
 3570: 
 3571: __END__

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