File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.358.2.19.2.8: download - view: text, annotated - select for diffs
Mon Sep 11 12:10:39 2023 UTC (8 months, 4 weeks ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.358.2.19: preferred, unified
- For 2.11.4 (modified)
  Include changes in 1.409

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

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