File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.390: download - view: text, annotated - select for diffs
Thu Nov 16 13:31:29 2017 UTC (6 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- jquery-ui progressbar -- use indeterminate progressbar display if the
  maximum number of items to do is omitted from the call to Create_PrgWin().
- an optional HTML preamble can be included in the cal to Create_PrgWin()
  to display before the progressbar.

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

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