File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.398: download - view: text, annotated - select for diffs
Thu Apr 29 17:45:22 2021 UTC (3 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6914
  Update domain config UI to support settings documented in
  Domain_Configuration_WAF_Proxy.tex

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

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