File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.407: download - view: text, annotated - select for diffs
Thu Oct 20 01:03:16 2022 UTC (19 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6975
  Folders in Supplemental Content area can be hidden using Course Editor.

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

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