File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.378: download - view: text, annotated - select for diffs
Wed Nov 9 02:04:04 2016 UTC (7 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- &checkbox() can take additional arg (e.g., to set to disabled).
- If system-level bre priv absent, /res in breadcrumb trail is plain text
  instead of a link, when browsing resource space.

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

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