File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.358.2.11.2.2: download - view: text, annotated - select for diffs
Sun Apr 29 16:30:35 2018 UTC (6 years ago) by raeburn
Branches: version_2_11_2_msu
Diff to branchpoint 1.358.2.11: preferred, unified
- For 2.11.2 (modified)
  Include changes in 1.358.2.12

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

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