File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.392: download - view: text, annotated - select for diffs
Sat Apr 14 02:29:44 2018 UTC (6 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Provider
  - Original LTI launch of LON-CAPA is for a resource, a map, or an entire
    course, and display is for iframe, tab or window; retain this in %env.

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

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