File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.295: download - view: text, annotated - select for diffs
Thu Dec 8 21:37:46 2011 UTC (12 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #4046: eliminate date setting popup

    1: # The LearningOnline Network with CAPA
    2: # a pile of common html routines
    3: #
    4: # $Id: lonhtmlcommon.pm,v 1.295 2011/12/08 21:37:46 www 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;
   65: 
   66: sub java_not_enabled {
   67:    return "\n".'<span class="LC_error">'.
   68:           &mt('The required Java applet could not be started. Please make sure to have Java installed and active in your browser.').
   69:           "</span>\n";
   70: }
   71: 
   72: sub coursepreflink {
   73:    my ($text,$category)=@_;
   74:    if (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
   75:       return '<a href="'.&HTML::Entities::encode("/adm/courseprefs?phase=display&actions=$category",'<>&"').'"><span class="LC_setting">'.$text.'</span></a>';
   76:    } else {
   77:       return '';
   78:    }
   79: }
   80: 
   81: sub raw_href_to_link {
   82:    my ($message)=@_;
   83:    $message=~s/(https?\:\/\/[^\s\'\"\<]+)([\s\<]|$)/<a href="$1"><tt>$1<\/tt><\/a>$2/gi;
   84:    return $message;
   85: }
   86: 
   87: sub entity_encode {
   88:     my ($text)=@_;
   89:     return &HTML::Entities::encode($text, '<>&"');
   90: }
   91: 
   92: sub direct_parm_link {
   93:     my ($linktext,$symb,$filter,$part,$target)=@_;
   94:     $symb=&entity_encode($symb);
   95:     $filter=&entity_encode($filter);
   96:     $part=&entity_encode($part);
   97:     if (($symb) && (&Apache::lonnet::allowed('opa')) && ($target ne 'tex')) {
   98:        return "<a href='/adm/parmset?symb=$symb&filter=$filter&part=$part'><span class='LC_setting'>$linktext</span></a>";
   99:     } else {
  100:        return $linktext;
  101:     }
  102: }
  103: ##############################################
  104: ##############################################
  105: 
  106: =item confirm_success
  107: 
  108: Successful completion of an operation message
  109: 
  110: =cut
  111: 
  112: sub confirm_success {
  113:    my ($message,$failure)=@_;
  114:    if ($failure) {
  115:       return '<span class="LC_error" style="font-size: inherit;">'."\n"
  116:             .'<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.&mt('Error').'" /> '."\n"
  117:             .$message."\n"
  118:             .'</span>'."\n";
  119:    } else {
  120:       return '<span class="LC_success">'."\n"
  121:             .'<img src="/adm/lonIcons/navmap.correct.gif" alt="'.&mt('OK').'" /> '."\n"
  122:             .$message."\n"
  123:             .'</span>'."\n";
  124:    }
  125: }
  126: 
  127: ##############################################
  128: ##############################################
  129: 
  130: =pod
  131: 
  132: =item dragmath_button
  133: 
  134: Creates a button that launches a dragmath popup-window, in which an 
  135: expression can be edited and pasted as LaTeX into a specified textarea. 
  136: 
  137:   textarea - Name of the textarea to edit.
  138:   helpicon - If true, show a help icon to the right of the button.
  139: 
  140: =cut
  141: 
  142: sub dragmath_button {
  143:     my ($textarea,$helpicon) = @_;
  144:     my $help_text; 
  145:     if ($helpicon) {
  146:         $help_text = &Apache::loncommon::help_open_topic('Authoring_Math_Editor',undef,undef,undef,undef,'mathhelpicon_'.$textarea);
  147:     }
  148:     my $buttontext=&mt('Edit Math');
  149:     return <<ENDDRAGMATH;
  150:                 <input type="button" value="$buttontext" onclick="javascript:mathedit('$textarea',document)" />$help_text
  151: ENDDRAGMATH
  152: }
  153: 
  154: ##############################################
  155: 
  156: =pod
  157: 
  158: =item dragmath_js
  159: 
  160: Javascript used to open pop-up window containing dragmath applet which 
  161: can be used to paste LaTeX into a textarea.
  162: =cut
  163: 
  164: sub dragmath_js {
  165:     my ($popup) = @_;
  166:     return <<ENDDRAGMATHJS;
  167:                 <script type="text/javascript">
  168:                 // <![CDATA[
  169:                   function mathedit(textarea, doc) {
  170:                      targetEntry = textarea;
  171:                      targetDoc   = doc;
  172:                      newwin  = window.open("/adm/dragmath/applet/$popup.html","","width=565,height=500,resizable");
  173:                   }
  174:                 // ]]>
  175:                 </script>
  176: 
  177: ENDDRAGMATHJS
  178: }
  179: 
  180: 
  181: ##############################################
  182: ##############################################
  183: 
  184: =pod
  185: 
  186: =item authorbombs
  187: 
  188: =cut
  189: 
  190: ##############################################
  191: ##############################################
  192: 
  193: sub authorbombs {
  194:     my $url=shift;
  195:     $url=&Apache::lonnet::declutter($url);
  196:     my ($udom,$uname)=($url=~m{^($LONCAPA::domain_re)/($LONCAPA::username_re)/});
  197:     my %bombs=&Apache::lonmsg::all_url_author_res_msg($uname,$udom);
  198:     foreach my $bomb (keys(%bombs)) {
  199: 	if ($bomb =~ /^$udom\/$uname\//) {
  200: 	    return '<a href="/adm/bombs/'.$url.
  201: 		'"><img src="'.&Apache::loncommon::lonhttpdurl('/adm/lonMisc/bomb.gif').'" alt="'.&mt('Bomb').'" border="0" /></a>'.
  202: 		&Apache::loncommon::help_open_topic('About_Bombs');
  203: 	}
  204:     }
  205:     return '';
  206: }
  207: 
  208: ##############################################
  209: ##############################################
  210: 
  211: sub recent_filename {
  212:     my $area=shift;
  213:     return 'nohist_recent_'.&escape($area);
  214: }
  215: 
  216: sub store_recent {
  217:     my ($area,$name,$value,$freeze)=@_;
  218:     my $file=&recent_filename($area);
  219:     my %recent=&Apache::lonnet::dump($file);
  220:     if (scalar(keys(%recent))>20) {
  221: # remove oldest value
  222: 	my $oldest=time();
  223: 	my $delkey='';
  224: 	foreach my $item (keys(%recent)) {
  225: 	    my $thistime=(split(/\&/,$recent{$item}))[0];
  226: 	    if (($thistime ne "always_include") && ($thistime<$oldest)) {
  227: 		$oldest=$thistime;
  228: 		$delkey=$item;
  229: 	    }
  230: 	}
  231: 	&Apache::lonnet::del($file,[$delkey]);
  232:     }
  233: # store new value
  234:     my $timestamp;
  235:     if ($freeze) {
  236:         $timestamp = "always_include";
  237:     } else {
  238:         $timestamp = time();
  239:     }   
  240:     &Apache::lonnet::put($file,{ $name => 
  241: 				 $timestamp.'&'.&escape($value) });
  242: }
  243: 
  244: sub remove_recent {
  245:     my ($area,$names)=@_;
  246:     my $file=&recent_filename($area);
  247:     return &Apache::lonnet::del($file,$names);
  248: }
  249: 
  250: sub select_recent {
  251:     my ($area,$fieldname,$event)=@_;
  252:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  253:     my $return="\n<select name='$fieldname'".
  254: 	($event?" onchange='$event'":'').
  255: 	">\n<option value=''>--- ".&mt('Recent')." ---</option>";
  256:     foreach my $value (sort(keys(%recent))) {
  257: 	unless ($value =~/^error\:/) {
  258: 	    my $escaped = &Apache::loncommon::escape_url($value);
  259: 	    &Apache::loncommon::inhibit_menu_check(\$escaped);
  260:             if ($area eq 'residx') {
  261:                 next if ((!&Apache::lonnet::allowed('bre',$value)) && (!&Apache::lonnet::allowed('bro',$value)));
  262:             }
  263: 	    $return.="\n<option value='$escaped'>".
  264: 		&unescape((split(/\&/,$recent{$value}))[1]).
  265: 		'</option>';
  266: 	}
  267:     }
  268:     $return.="\n</select>\n";
  269:     return $return;
  270: }
  271: 
  272: sub get_recent {
  273:     my ($area, $n) = @_;
  274:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  275: 
  276: # Create hash with key as time and recent as value
  277: # Begin filling return_hash with any 'always_include' option
  278:     my %time_hash = ();
  279:     my %return_hash = ();
  280:     foreach my $item (keys(%recent)) {
  281:         my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
  282:         if ($thistime eq 'always_include') {
  283:             $return_hash{$item} = &unescape($thisvalue);
  284:             $n--;
  285:         } else {
  286:             $time_hash{$thistime} = $item;
  287:         }
  288:     }
  289: 
  290: # Sort by decreasing time and return key value pairs
  291:     my $idx = 1;
  292:     foreach my $item (reverse(sort(keys(%time_hash)))) {
  293:        $return_hash{$time_hash{$item}} =
  294:                   &unescape((split(/\&/,$recent{$time_hash{$item}}))[1]);
  295:        if ($n && ($idx++ >= $n)) {last;}
  296:     }
  297: 
  298:     return %return_hash;
  299: }
  300: 
  301: sub get_recent_frozen {
  302:     my ($area) = @_;
  303:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  304: 
  305: # Create hash with all 'frozen' items
  306:     my %return_hash = ();
  307:     foreach my $item (keys(%recent)) {
  308:         my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
  309:         if ($thistime eq 'always_include') {
  310:             $return_hash{$item} = &unescape($thisvalue);
  311:         }
  312:     }
  313:     return %return_hash;
  314: }
  315: 
  316: 
  317: 
  318: =pod
  319: 
  320: =item textbox
  321: 
  322: =cut
  323: 
  324: ##############################################
  325: ##############################################
  326: sub textbox {
  327:     my ($name,$value,$size,$special) = @_;
  328:     $size = 40 if (! defined($size));
  329:     $value = &HTML::Entities::encode($value,'<>&"');
  330:     my $Str = '<input type="text" name="'.$name.'" size="'.$size.'" '.
  331:         'value="'.$value.'" '.$special.' />';
  332:     return $Str;
  333: }
  334: 
  335: ##############################################
  336: ##############################################
  337: 
  338: =pod
  339: 
  340: =item checkbox
  341: 
  342: =cut
  343: 
  344: ##############################################
  345: ##############################################
  346: sub checkbox {
  347:     my ($name,$checked,$value) = @_;
  348:     my $Str = '<input type="checkbox" name="'.$name.'" ';
  349:     if (defined($value)) {
  350:         $Str .= 'value="'.$value.'"';
  351:     } 
  352:     if ($checked) {
  353:         $Str .= ' checked="checked"';
  354:     }
  355:     $Str .= ' />';
  356:     return $Str;
  357: }
  358: 
  359: 
  360: =pod
  361: 
  362: =item radiobutton
  363: 
  364: =cut
  365: 
  366: ##############################################
  367: ##############################################
  368: sub radio {
  369:     my ($name,$checked,$value) = @_;
  370:     my $Str = '<input type="radio" name="'.$name.'" ';
  371:     if (defined($value)) {
  372:         $Str .= 'value="'.$value.'"';
  373:     } 
  374:     if ($checked eq $value) {
  375:         $Str .= ' checked="checked"';
  376:     }
  377:     $Str .= ' />';
  378:     return $Str;
  379: }
  380: 
  381: ##############################################
  382: ##############################################
  383: 
  384: =pod
  385: 
  386: =item &date_setter
  387: 
  388: &date_setter returns html and javascript for a compact date-setting form.
  389: To retrieve values from it, use &get_date_from_form().
  390: 
  391: Inputs
  392: 
  393: =over 4
  394: 
  395: =item $dname 
  396: 
  397: The name to prepend to the form elements.  
  398: The form elements defined will be dname_year, dname_month, dname_day,
  399: dname_hour, dname_min, and dname_sec.
  400: 
  401: =item $currentvalue
  402: 
  403: The current setting for this time parameter.  A unix format time
  404: (time in seconds since the beginning of Jan 1st, 1970, GMT.  
  405: An undefined value is taken to indicate the value is the current time
  406: unless it is requested to leave it empty. See $includeempty.
  407: Also, to be explicit, a value of 'now' also indicates the current time.
  408: 
  409: =item $special
  410: 
  411: Additional html/javascript to be associated with each element in
  412: the date_setter.  See lonparmset for example usage.
  413: 
  414: =item $includeempty 
  415: 
  416: If it is set (true) and no date/time value is provided,
  417: the date/time fields are left empty.
  418: 
  419: =item $state
  420: 
  421: Specifies the initial state of the form elements.  Either 'disabled' or empty.
  422: Defaults to empty, which indiciates the form elements are not disabled. 
  423: 
  424: =back
  425: 
  426: Bugs
  427: 
  428: The method used to restrict user input will fail in the year 2400.
  429: 
  430: =cut
  431: 
  432: ##############################################
  433: ##############################################
  434: sub date_setter {
  435:     my ($formname,$dname,$currentvalue,$special,$includeempty,$state,
  436:         $no_hh_mm_ss,$defhour,$defmin,$defsec,$nolink) = @_;
  437:     my $now = time;
  438: 
  439:     my $tzname;
  440:     my ($sec,$min,$hour,$mday,$month,$year) = ('', '', undef,''.''.'');
  441:     #other potentially useful values:    wkday,yrday,is_daylight_savings
  442: 
  443:     if (! defined($state) || $state ne 'disabled') {
  444:         $state = '';
  445:     }
  446:     if (! defined($no_hh_mm_ss)) {
  447:         $no_hh_mm_ss = 0;
  448:     }
  449:     if ($currentvalue eq 'now') {
  450:         $currentvalue = $now;
  451:     }
  452:     
  453:     # Default value: Set empty date field to current time
  454:     # unless empty inclusion is requested
  455:     if ((!$includeempty) && (!$currentvalue)) {
  456:         $currentvalue = $now;
  457:     }
  458:     # Do we have a date? Split it!
  459:     if ($currentvalue) {
  460: 	($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($currentvalue);
  461: 
  462:         #No values provided for hour, min, sec? Use default 0
  463:         if (($defhour) || ($defmin) || ($defsec)) {
  464:             $sec  = ($defsec  ? $defsec  : 0);
  465:             $min  = ($defmin  ? $defmin  : 0);
  466:             $hour = ($defhour ? $defhour : 0);
  467:         }
  468:     }
  469:     my $result = "\n<!-- $dname date setting form -->\n";
  470:     $result .= <<ENDJS;
  471: <script type="text/javascript">
  472: // <![CDATA[
  473:     function $dname\_checkday() {
  474:         var day   = document.$formname.$dname\_day.value;
  475:         var month = document.$formname.$dname\_month.value;
  476:         var year  = document.$formname.$dname\_year.value;
  477:         var valid = true;
  478:         if (day < 1) {
  479:             document.$formname.$dname\_day.value = 1;
  480:         } 
  481:         if (day > 31) {
  482:             document.$formname.$dname\_day.value = 31;
  483:         }
  484:         if ((month == 1)  || (month == 3)  || (month == 5)  ||
  485:             (month == 7)  || (month == 8)  || (month == 10) ||
  486:             (month == 12)) {
  487:             if (day > 31) {
  488:                 document.$formname.$dname\_day.value = 31;
  489:                 day = 31;
  490:             }
  491:         } else if (month == 2 ) {
  492:             if ((year % 4 == 0) && (year % 100 != 0)) {
  493:                 if (day > 29) {
  494:                     document.$formname.$dname\_day.value = 29;
  495:                 }
  496:             } else if (day > 29) {
  497:                 document.$formname.$dname\_day.value = 28;
  498:             }
  499:         } else if (day > 30) {
  500:             document.$formname.$dname\_day.value = 30;
  501:         }
  502:     }
  503:     
  504:     function $dname\_disable() {
  505:         document.$formname.$dname\_month.disabled=true;
  506:         document.$formname.$dname\_day.disabled=true;
  507:         document.$formname.$dname\_year.disabled=true;
  508:         document.$formname.$dname\_hour.disabled=true;
  509:         document.$formname.$dname\_minute.disabled=true;
  510:         document.$formname.$dname\_second.disabled=true;
  511:     }
  512: 
  513:     function $dname\_enable() {
  514:         document.$formname.$dname\_month.disabled=false;
  515:         document.$formname.$dname\_day.disabled=false;
  516:         document.$formname.$dname\_year.disabled=false;
  517:         document.$formname.$dname\_hour.disabled=false;
  518:         document.$formname.$dname\_minute.disabled=false;
  519:         document.$formname.$dname\_second.disabled=false;        
  520:     }
  521: 
  522:     function $dname\_opencalendar() {
  523:         if (! document.$formname.$dname\_month.disabled) {
  524:             var calwin=window.open(
  525: "/adm/announcements?pickdate=yes&formname=$formname&element=$dname&month="+
  526: document.$formname.$dname\_month.value+"&year="+
  527: document.$formname.$dname\_year.value,
  528:              "LONCAPAcal",
  529:               "height=350,width=350,scrollbars=yes,resizable=yes,menubar=no");
  530:         }
  531: 
  532:     }
  533: // ]]>
  534: </script>
  535: ENDJS
  536:     $result .= '  <span class="LC_nobreak">';
  537:     my $monthselector = qq{<select name="$dname\_month" $special $state onchange="javascript:$dname\_checkday()" >};
  538:     # Month
  539:     my @Months = qw/January February  March     April   May      June 
  540:                     July    August    September October November December/;
  541:     # Pad @Months with a bogus value to make indexing easier
  542:     unshift(@Months,'If you can read this an error occurred');
  543:     if ($includeempty) { $monthselector.="<option value=''></option>"; }
  544:     for(my $m = 1;$m <=$#Months;$m++) {
  545:         $monthselector .= qq{      <option value="$m"};
  546:         $monthselector .= ' selected="selected"' if ($m-1 eq $month);
  547:         $monthselector .= '> '.&mt($Months[$m]).' </option>'."\n";
  548:     }
  549:     $monthselector.= '  </select>';
  550:     # Day
  551:     my $dayselector = qq{<input type="text" name="$dname\_day" $state value="$mday" size="3" $special onchange="javascript:$dname\_checkday()" />};
  552:     # Year
  553:     my $yearselector = qq{<input type="text" name="$dname\_year" $state value="$year" size="5" $special onchange="javascript:$dname\_checkday()" />};
  554:     #
  555:     my $hourselector = qq{<select name="$dname\_hour" $special $state >};
  556:     if ($includeempty) { 
  557:         $hourselector.=qq{<option value=''></option>};
  558:     }
  559:     for (my $h = 0;$h<24;$h++) {
  560:         $hourselector .= qq{<option value="$h"};
  561:         $hourselector .= ' selected="selected"' if (defined($hour) && $hour == $h);
  562:         $hourselector .= ">";
  563:         my $timest='';
  564:         if ($h == 0) {
  565:             $timest .= "12 am";
  566:         } elsif($h == 12) {
  567:             $timest .= "12 noon";
  568:         } elsif($h < 12) {
  569:             $timest .= "$h am";
  570:         } else {
  571:             $timest .= $h-12 ." pm";
  572:         }
  573:         $timest=&mt($timest);
  574:         $hourselector .= $timest." </option>\n";
  575:     }
  576:     $hourselector .= "  </select>\n";
  577:     my $minuteselector = qq{<input type="text" name="$dname\_minute" $special $state value="$min" size="3" />};
  578:     my $secondselector= qq{<input type="text" name="$dname\_second" $special $state value="$sec" size="3" />};
  579:     my $cal_link;
  580:     if (!$nolink) {
  581:         $cal_link = qq{<a href="javascript:$dname\_opencalendar()">};
  582:     }
  583:     #
  584:     my $tzone = ' '.$tzname.' ';
  585:     if ($no_hh_mm_ss) {
  586:         $result .= &mt('[_1] [_2] [_3] ',
  587:                        $monthselector,$dayselector,$yearselector).
  588:                    $tzone;
  589:         if (!$nolink) {
  590:             $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
  591:         }
  592:     } else {
  593:         $result .= &mt('[_1] [_2] [_3] [_4] [_5]m [_6]s ',
  594:                       $monthselector,$dayselector,$yearselector,
  595:                       $hourselector,$minuteselector,$secondselector).
  596:                    $tzone;
  597:         if (!$nolink) {
  598:             $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
  599:         }
  600:     }
  601:     $result .= "</span>\n<!-- end $dname date setting form -->\n";
  602:     return $result;
  603: }
  604: 
  605: sub get_timedates {
  606:     my ($epoch) = @_;
  607:     my $dt = DateTime->from_epoch(epoch => $epoch)
  608:                      ->set_time_zone(&Apache::lonlocal::gettimezone());
  609:     my $tzname = $dt->time_zone_short_name();
  610:     my $sec = $dt->second;
  611:     my $min = $dt->minute;
  612:     my $hour = $dt->hour;
  613:     my $mday = $dt->day;
  614:     my $month = $dt->month;
  615:     if ($month) {
  616:         $month --;
  617:     }
  618:     my $year = $dt->year;
  619:     return ($tzname,$sec,$min,$hour,$mday,$month,$year);
  620: }
  621: 
  622: sub build_url {
  623:     my ($base, $fields)=@_;
  624:     my $url;
  625:     $url = $base.'?';
  626:     foreach my $key (keys(%$fields)) {
  627:         $url.=&escape($key).'='.&escape($$fields{$key}).'&amp;';
  628:     }
  629:     $url =~ s/&amp;$//;
  630:     return $url;
  631: }
  632: 
  633: 
  634: ##############################################
  635: ##############################################
  636: 
  637: =pod
  638: 
  639: =item &get_date_from_form
  640: 
  641: get_date_from_form retrieves the date specified in an &date_setter form.
  642: 
  643: Inputs:
  644: 
  645: =over 4
  646: 
  647: =item $dname
  648: 
  649: The name passed to &date_setter, which prefixes the form elements.
  650: 
  651: =item $defaulttime
  652: 
  653: The unix time to use as the default in case of poor inputs.
  654: 
  655: =back
  656: 
  657: Returns: Unix time represented in the form.
  658: 
  659: =cut
  660: 
  661: ##############################################
  662: ##############################################
  663: sub get_date_from_form {
  664:     my ($dname) = @_;
  665:     my ($sec,$min,$hour,$day,$month,$year);
  666:     #
  667:     if (defined($env{'form.'.$dname.'_second'})) {
  668:         my $tmpsec = $env{'form.'.$dname.'_second'};
  669:         if (($tmpsec =~ /^\d+$/) && ($tmpsec >= 0) && ($tmpsec < 60)) {
  670:             $sec = $tmpsec;
  671:         }
  672: 	if (!defined($tmpsec) || $tmpsec eq '') { $sec = 0; }
  673:     } else {
  674:         $sec = 0;
  675:     }
  676:     if (defined($env{'form.'.$dname.'_minute'})) {
  677:         my $tmpmin = $env{'form.'.$dname.'_minute'};
  678:         if (($tmpmin =~ /^\d+$/) && ($tmpmin >= 0) && ($tmpmin < 60)) {
  679:             $min = $tmpmin;
  680:         }
  681: 	if (!defined($tmpmin) || $tmpmin eq '') { $min = 0; }
  682:     } else {
  683:         $min = 0;
  684:     }
  685:     if (defined($env{'form.'.$dname.'_hour'})) {
  686:         my $tmphour = $env{'form.'.$dname.'_hour'};
  687:         if (($tmphour =~ /^\d+$/) && ($tmphour >= 0) && ($tmphour < 24)) {
  688:             $hour = $tmphour;
  689:         }
  690:     } else {
  691:         $hour = 0;
  692:     }
  693:     if (defined($env{'form.'.$dname.'_day'})) {
  694:         my $tmpday = $env{'form.'.$dname.'_day'};
  695:         if (($tmpday =~ /^\d+$/) && ($tmpday > 0) && ($tmpday < 32)) {
  696:             $day = $tmpday;
  697:         }
  698:     }
  699:     if (defined($env{'form.'.$dname.'_month'})) {
  700:         my $tmpmonth = $env{'form.'.$dname.'_month'};
  701:         if (($tmpmonth =~ /^\d+$/) && ($tmpmonth > 0) && ($tmpmonth < 13)) {
  702:             $month = $tmpmonth;
  703:         }
  704:     }
  705:     if (defined($env{'form.'.$dname.'_year'})) {
  706:         my $tmpyear = $env{'form.'.$dname.'_year'};
  707:         if (($tmpyear =~ /^\d+$/) && ($tmpyear >= 1970)) {
  708:             $year = $tmpyear;
  709:         }
  710:     }
  711:     if (($year<1970) || ($year>2037)) { return undef; }
  712:     if (defined($sec) && defined($min)   && defined($hour) &&
  713:         defined($day) && defined($month) && defined($year)) {
  714:         my $timezone = &Apache::lonlocal::gettimezone();
  715:         my $dt = DateTime->new( year   => $year,
  716:                                 month  => $month,
  717:                                 day    => $day,
  718:                                 hour   => $hour,
  719:                                 minute => $min,
  720:                                 second => $sec,
  721:                                 time_zone => $timezone,
  722:                               );
  723:         my $epoch_time  = $dt->epoch;
  724:         if ($epoch_time ne '') {
  725:             return $epoch_time;
  726:         } else {
  727:             return undef;
  728:         }
  729:     } else {
  730:         return undef;
  731:     }
  732: }
  733: 
  734: ##############################################
  735: ##############################################
  736: 
  737: =pod
  738: 
  739: =item &pjump_javascript_definition()
  740: 
  741: Returns javascript defining the 'pjump' function, which opens up a
  742: parameter setting wizard.
  743: 
  744: =cut
  745: 
  746: ##############################################
  747: ##############################################
  748: sub pjump_javascript_definition {
  749:     my $Str = <<END;
  750:     function pjump(type,dis,value,marker,ret,call,hour,min,sec) {
  751:         openMyModal("/adm/rat/parameter.html?type="+escape(type)
  752:                  +"&value="+escape(value)+"&marker="+escape(marker)
  753:                  +"&return="+escape(ret)
  754:                  +"&call="+escape(call)+"&name="+escape(dis)
  755:                  +"&defhour="+escape(hour)+"&defmin="+escape(min)
  756:                  +"&defsec="+escape(sec)+"&modal=1",350,350,'no');
  757:     }
  758: END
  759:     return $Str;
  760: }
  761: 
  762: ##############################################
  763: ##############################################
  764: 
  765: =pod
  766: 
  767: =item &javascript_nothing()
  768: 
  769: Return an appropriate null for the users browser.  This is used
  770: as the first arguement for window.open calls when you want a blank
  771: window that you can then write to.
  772: 
  773: =cut
  774: 
  775: ##############################################
  776: ##############################################
  777: sub javascript_nothing {
  778:     # mozilla and other browsers work with "''", but IE on mac does not.
  779:     my $nothing = "''";
  780:     my $user_browser;
  781:     my $user_os;
  782:     $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
  783:     $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
  784:     if (! defined($user_browser) || ! defined($user_os)) {
  785:         (undef,$user_browser,undef,undef,undef,$user_os) = 
  786:                            &Apache::loncommon::decode_user_agent();
  787:     }
  788:     if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
  789:         $nothing = "'javascript:void(0);'";
  790:     }
  791:     return $nothing;
  792: }
  793: 
  794: ##############################################
  795: ##############################################
  796: sub javascript_docopen {
  797:     my ($mimetype) = @_;
  798:     $mimetype ||= 'text/html';
  799:     # safari does not understand document.open() and loads "text/html"
  800:     my $nothing = "''";
  801:     my $user_browser;
  802:     my $user_os;
  803:     $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
  804:     $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
  805:     if (! defined($user_browser) || ! defined($user_os)) {
  806:         (undef,$user_browser,undef,undef,undef,$user_os) = 
  807:                            &Apache::loncommon::decode_user_agent();
  808:     }
  809:     if ($user_browser eq 'safari' && $user_os =~ 'mac') {
  810:         $nothing = "document.clear()";
  811:     } else {
  812: 	$nothing = "document.open('$mimetype','replace')";
  813:     }
  814:     return $nothing;
  815: }
  816: 
  817: 
  818: ##############################################
  819: ##############################################
  820: 
  821: =pod
  822: 
  823: =item &StatusOptions()
  824: 
  825: Returns html for a selection box which allows the user to choose the
  826: enrollment status of students.  The selection box name is 'Status'.
  827: 
  828: Inputs:
  829: 
  830: $status: the currently selected status.  If undefined the value of
  831: $env{'form.Status'} is taken.  If that is undefined, a value of 'Active'
  832: is used.
  833: 
  834: $formname: The name of the form.  If defined the onchange attribute of
  835: the selection box is set to document.$formname.submit().
  836: 
  837: $size: the size (number of lines) of the selection box.
  838: 
  839: $onchange: javascript to use when the value is changed.  Enclosed in 
  840: double quotes, ""s, not single quotes.
  841: 
  842: Returns: a perl string as described.
  843: 
  844: =cut
  845: 
  846: ##############################################
  847: ##############################################
  848: sub StatusOptions {
  849:     my ($status, $formName,$size,$onchange,$mult)=@_;
  850:     $size = 1 if (!defined($size));
  851:     if (! defined($status)) {
  852:         $status = 'Active';
  853:         $status = $env{'form.Status'} if (exists($env{'form.Status'}));
  854:     }
  855: 
  856:     my $Str = '';
  857:     $Str .= '<select name="Status"';
  858:     if (defined($mult)){
  859:         $Str .= ' multiple="multiple" ';
  860:     }
  861:     if(defined($formName) && $formName ne '' && ! defined($onchange)) {
  862:         $Str .= ' onchange="document.'.$formName.'.submit()"';
  863:     }
  864:     if (defined($onchange)) {
  865:         $Str .= ' onchange="'.$onchange.'"';
  866:     }
  867:     $Str .= ' size="'.$size.'" ';
  868:     $Str .= '>'."\n";
  869:     foreach my $type (['Active',  &mt('Currently Has Access')],
  870: 		      ['Future',  &mt('Will Have Future Access')],
  871: 		      ['Expired', &mt('Previously Had Access')],
  872: 		      ['Any',     &mt('Any Access Status')]) {
  873: 	my ($name,$label) = @$type;
  874: 	$Str .= '<option value="'.$name.'" ';
  875: 	if ($status eq $name) {
  876: 	    $Str .= 'selected="selected" ';
  877: 	}
  878: 	$Str .= '>'.$label.'</option>'."\n";
  879:     }
  880: 
  881:     $Str .= '</select>'."\n";
  882: }
  883: 
  884: ########################################################
  885: ########################################################
  886: 
  887: =pod
  888: 
  889: =item Progess Window Handling Routines
  890: 
  891: These routines handle the creation, update, increment, and closure of 
  892: progress windows.  The progress window reports to the user the number
  893: of items completed and an estimate of the time required to complete the rest.
  894: 
  895: =over 4
  896: 
  897: 
  898: =item &Create_PrgWin
  899: 
  900: Writes javascript to the client to open a progress window and returns a
  901: data structure used for bookkeeping.
  902: 
  903: Inputs
  904: 
  905: =over 4
  906: 
  907: =item $r Apache request
  908: 
  909: =item $title The title of the progress window
  910: 
  911: =item $heading A description (usually 1 line) of the process being initiated.
  912: 
  913: =item $number_to_do The total number of items being processed.
  914: 
  915: =item $type Either 'popup' or 'inline' (popup is assumed if nothing is
  916:        specified)
  917: 
  918: =item $width Specify the width in charaters of the input field.
  919: 
  920: =item $formname Only useful in the inline case, if a form already exists, this needs to be used and specfiy the name of the form, otherwise the Progress line will be created in a new form of it's own
  921: 
  922: =item $inputname Only useful in the inline case, if a form and an input of type text exists, use this to specify the name of the input field 
  923: 
  924: =back
  925: 
  926: Returns a hash containing the progress state data structure.
  927: 
  928: 
  929: =item &Update_PrgWin
  930: 
  931: Updates the text in the progress indicator.  Does not increment the count.
  932: See &Increment_PrgWin.
  933: 
  934: Inputs:
  935: 
  936: =over 4
  937: 
  938: =item $r Apache request
  939: 
  940: =item $prog_state Pointer to the data structure returned by &Create_PrgWin
  941: 
  942: =item $displaystring The string to write to the status indicator
  943: 
  944: =back
  945: 
  946: Returns: none
  947: 
  948: 
  949: =item Increment_PrgWin
  950: 
  951: Increment the count of items completed for the progress window by $step or 1 if no step is provided.
  952: 
  953: Inputs:
  954: 
  955: =over 4
  956: 
  957: =item $r Apache request
  958: 
  959: =item $prog_state Pointer to the data structure returned by Create_PrgWin
  960: 
  961: =item $extraInfo A description of the items being iterated over.  Typically
  962: 'student'.
  963: 
  964: =item $step (optional) counter step. Will be set to default 1 if ommited. step must be greater than 0 or empty.
  965: 
  966: =back
  967: 
  968: Returns: none
  969: 
  970: 
  971: =item Close_PrgWin
  972: 
  973: Closes the progress window.
  974: 
  975: Inputs:
  976: 
  977: =over 4 
  978: 
  979: =item $r Apache request
  980: 
  981: =item $prog_state Pointer to the data structure returned by Create_PrgWin
  982: 
  983: =back
  984: 
  985: Returns: none
  986: 
  987: =back
  988: 
  989: =cut
  990: 
  991: ########################################################
  992: ########################################################
  993: 
  994: my $uniq=0;
  995: sub get_uniq_name {
  996:     $uniq++;
  997:     return 'uniquename'.$uniq;
  998: }
  999: 
 1000: # Create progress
 1001: sub Create_PrgWin {
 1002:     my ($r, $title, $heading, $number_to_do,$type,$width,$formname,
 1003: 	$inputname)=@_;
 1004:     if (!defined($type)) { $type='popup'; }
 1005:     if (!defined($width)) { $width=55; }
 1006:     my %prog_state;
 1007:     $prog_state{'type'}=$type;
 1008:     if ($type eq 'popup') {
 1009: 	$prog_state{'window'}='popwin';
 1010: 	my $start_page =
 1011: 	    &Apache::loncommon::start_page($title,undef,
 1012: 					   {'only_body' => 1,
 1013: 					    'bgcolor'   => '#88DDFF',
 1014: 					    'js_ready'  => 1});
 1015: 	my $end_page = &Apache::loncommon::end_page({'js_ready'  => 1});
 1016: 
 1017: 	#the whole function called through timeout is due to issues
 1018: 	#in mozilla Read BUG #2665 if you want to know the whole story
 1019: 	&r_print($r,&Apache::lonhtmlcommon::scripttag(
 1020:         "var popwin;
 1021:          function openpopwin () {
 1022:          popwin=open(\'\',\'popwin\',\'width=400,height=100\');".
 1023:         "popwin.document.writeln(\'".$start_page.
 1024:               "<h4>".&mt("$heading")."<\/h4>".
 1025:               "<form action=\"\" name=\"popremain\" method=\"post\">".
 1026:               '<input type="text" size="'.$width.'" name="remaining" value="'.
 1027: 	      &mt('Starting').'" /><\\/form>'.$end_page.
 1028:               "\');".
 1029:         "popwin.document.close();}".
 1030:         "\nwindow.setTimeout(openpopwin,0)"
 1031:     ));
 1032: 	$prog_state{'formname'}='popremain';
 1033: 	$prog_state{'inputname'}="remaining";
 1034:     } elsif ($type eq 'inline') {
 1035: 	$prog_state{'window'}='window';
 1036: 	if (!$formname) {
 1037: 	    $prog_state{'formname'}=&get_uniq_name();
 1038: 	    &r_print($r,'<form action="" name="'.$prog_state{'formname'}.'">');
 1039: 	} else {
 1040: 	    $prog_state{'formname'}=$formname;
 1041: 	}
 1042: 	if (!$inputname) {
 1043: 	    $prog_state{'inputname'}=&get_uniq_name();
 1044: 	    &r_print($r,&mt("$heading [_1]",' <input type="text" name="'.$prog_state{'inputname'}.'" size="'.$width.'" />'));
 1045: 	} else {
 1046: 	    $prog_state{'inputname'}=$inputname;
 1047: 	    
 1048: 	}
 1049: 	if (!$formname) { &r_print($r,'</form>'); }
 1050: 	&Update_PrgWin($r,\%prog_state,&mt('Starting'));
 1051:     }
 1052: 
 1053:     $prog_state{'done'}=0;
 1054:     $prog_state{'firststart'}=&Time::HiRes::time();
 1055:     $prog_state{'laststart'}=&Time::HiRes::time();
 1056:     $prog_state{'max'}=$number_to_do;
 1057:     
 1058:     return %prog_state;
 1059: }
 1060: 
 1061: # update progress
 1062: sub Update_PrgWin {
 1063:     my ($r,$prog_state,$displayString)=@_;
 1064:     &r_print($r,&Apache::lonhtmlcommon::scripttag(
 1065:         $$prog_state{'window'}.'.document.'.
 1066:         $$prog_state{'formname'}.'.'.
 1067:         $$prog_state{'inputname'}.'.value="'.
 1068:         $displayString.'";'
 1069:     ));
 1070:     $$prog_state{'laststart'}=&Time::HiRes::time();
 1071: }
 1072: 
 1073: # increment progress state
 1074: sub Increment_PrgWin {
 1075:     my ($r,$prog_state,$extraInfo,$step)=@_;
 1076:     $step = $step > 0 ? $step : 1;
 1077:     $$prog_state{'done'} += $step;
 1078: 
 1079:     # Catch (max modulo step) <> 0
 1080:     my $current = $$prog_state{'done'};
 1081:     my $last = ($$prog_state{'max'} - $current);
 1082:     if ($last <= 0) {
 1083:         $last = 1;
 1084:         $current = $$prog_state{'max'};
 1085:     }
 1086: 
 1087:     my $time_est= (&Time::HiRes::time() - $$prog_state{'firststart'})/
 1088:         $current * $last;
 1089:     $time_est = int($time_est);
 1090:     #
 1091:     my $min = int($time_est/60);
 1092:     my $sec = $time_est % 60;
 1093: 
 1094:     my $lasttime = &Time::HiRes::time()-$$prog_state{'laststart'};
 1095:     if ($lasttime > 9) {
 1096:         $lasttime = int($lasttime);
 1097:     } elsif ($lasttime < 0.01) {
 1098:         $lasttime = 0;
 1099:     } else {
 1100:         $lasttime = sprintf("%3.2f",$lasttime);
 1101:     }
 1102: 
 1103:     $sec = 0 if ($min >= 10); # Don't show seconds if remaining time >= 10 min.
 1104:     $sec = 1 if ( ($min == 0) && ($sec == 0) ); # Little cheating: pretend to have 1 second remaining instead of 0 to have something to display
 1105: 
 1106:     my $timeinfo =
 1107:         &mt('[_1]/[_2]:'
 1108:            .' [quant,_3,minute,minutes,] [quant,_4,second ,seconds ,]remaining'
 1109:            .' ([quant,_5,second] for '.$extraInfo.')',
 1110:             $current,
 1111:             $$prog_state{'max'},
 1112:             $min,
 1113:             $sec,
 1114:             $lasttime);
 1115: 
 1116:     &r_print($r,&Apache::lonhtmlcommon::scripttag(
 1117:         $$prog_state{'window'}.'.document.'.
 1118:         $$prog_state{'formname'}.'.'.
 1119:         $$prog_state{'inputname'}.'.value="'.$timeinfo.'";'
 1120:     ));
 1121:     $$prog_state{'laststart'}=&Time::HiRes::time();
 1122: }
 1123: 
 1124: # close Progress Line
 1125: sub Close_PrgWin {
 1126:     my ($r,$prog_state)=@_;
 1127:     if ($$prog_state{'type'} eq 'popup') {
 1128:         &r_print($r,&Apache::lonhtmlcommon::scripttag(
 1129:             'popwin.close()'
 1130:         ));
 1131:     } elsif ($$prog_state{'type'} eq 'inline') {
 1132: 	&Update_PrgWin($r,$prog_state,&mt('Done'));
 1133:     }
 1134:     undef(%$prog_state);
 1135: }
 1136: 
 1137: sub r_print {
 1138:     my ($r,$to_print)=@_;
 1139:     if ($r) {
 1140: 	$r->print($to_print);
 1141: 	$r->rflush();
 1142:     } else {
 1143: 	print($to_print);
 1144:     }
 1145: }
 1146: 
 1147: # ------------------------------------------------------- Puts directory header
 1148: 
 1149: sub crumbs {
 1150:     my ($uri,$target,$prefix,$form,$skiplast)=@_;
 1151:     if ($target) {
 1152:         $target = ' target="'.
 1153:                   &Apache::loncommon::escape_single($target).'"';
 1154:     }
 1155:     my $output='<span class="LC_filename">';
 1156:     $output.=$prefix.'/';
 1157:     if (($env{'user.adv'}) || ($env{'user.author'})) {
 1158:         my $path=$prefix.'/';
 1159:         foreach my $dir (split('/',$uri)) {
 1160:             if (! $dir) { next; }
 1161:             $path .= $dir;
 1162:             if ($path eq $uri) {
 1163:                 if ($skiplast) {
 1164:                     $output.=$dir;
 1165:                     last;
 1166:                 } 
 1167:             } else {
 1168:                 $path.='/'; 
 1169:             }
 1170:             my $href_path = &HTML::Entities::encode($path,'<>&"');
 1171:             &Apache::loncommon::inhibit_menu_check(\$href_path);
 1172:             if ($form) {
 1173:                 my $href = 'javascript:'.$form.".action='".$href_path."';".$form.'.submit();';
 1174:                 $output.=qq{<a href="$href"$target>$dir</a>/};
 1175:             } else {
 1176:                 $output.=qq{<a href="$href_path"$target>$dir</a>/};
 1177:             }
 1178:         }
 1179:     } else {
 1180:         foreach my $dir (split('/',$uri)) {
 1181:             if (! $dir) { next; }
 1182:             $output.=$dir.'/';
 1183:         }
 1184:     }
 1185:     if ($uri !~ m|/$|) { $output=~s|/$||; }
 1186:     $output.='</span>';
 1187: 
 1188:     return $output;
 1189: }
 1190: 
 1191: # --------------------- A function that generates a window for the spellchecker
 1192: 
 1193: sub spellheader {
 1194:     my $start_page=
 1195: 	&Apache::loncommon::start_page('Speller Suggestions',undef,
 1196: 				       {'only_body'   => 1,
 1197: 					'js_ready'    => 1,
 1198: 					'bgcolor'     => '#DDDDDD',
 1199: 				        'add_entries' => {
 1200: 					    'onload' => 
 1201:                                                'document.forms.spellcheckform.submit()',
 1202:                                              }
 1203: 				        });
 1204:     my $end_page=
 1205: 	&Apache::loncommon::end_page({'js_ready'  => 1}); 
 1206: 
 1207:     my $nothing=&javascript_nothing();
 1208:     return (<<ENDCHECK);
 1209: <script type="text/javascript"> 
 1210: // <![CDATA[
 1211: //<!-- BEGIN LON-CAPA Internal
 1212: var checkwin;
 1213: 
 1214: function spellcheckerwindow(string) {
 1215:     var esc_string = string.replace(/\"/g,'&quot;');
 1216:     checkwin=window.open($nothing,'spellcheckwin','height=320,width=280,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no');
 1217:     checkwin.document.writeln('$start_page<form name="spellcheckform" action="/adm/spellcheck" method="post"><input type="hidden" name="text" value="'+esc_string+'" /><\\/form>$end_page');
 1218:     checkwin.document.close();
 1219: }
 1220: // END LON-CAPA Internal -->
 1221: // ]]>
 1222: </script>
 1223: ENDCHECK
 1224: }
 1225: 
 1226: # ---------------------------------- Generate link to spell checker for a field
 1227: 
 1228: sub spelllink {
 1229:     my ($form,$field)=@_;
 1230:     my $linktext=&mt('Check Spelling');
 1231:     return (<<ENDLINK);
 1232: <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>
 1233: ENDLINK
 1234: }
 1235: 
 1236: # ------------------------------------------------- Output headers for CKEditor
 1237: 
 1238: sub htmlareaheaders {
 1239: 	my $s="";
 1240: 	if (&htmlareabrowser()) {
 1241: 		$s.=(<<ENDEDITOR);
 1242: <script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
 1243: ENDEDITOR
 1244: 	}
 1245:     $s.=(<<ENDJQUERY);
 1246: <script type="text/javascript" src="/adm/jQuery/js/jquery-1.6.2.min.js"></script>
 1247: <script type="text/javascript" src="/adm/jQuery/js/jquery-ui-1.8.16.custom.min.js"></script>
 1248: <link rel="stylesheet" type="text/css" href="/adm/jQuery/css/smoothness/jquery-ui-1.8.16.custom.css" />
 1249: ENDJQUERY
 1250: 	return $s;
 1251: }
 1252: 
 1253: # ----------------------------------------------------------------- Preferences
 1254: 
 1255: # ------------------------------------------------- lang to use in html editor
 1256: sub htmlarea_lang {
 1257:     my $lang='en';
 1258:     if (&mt('htmlarea_lang') ne 'htmlarea_lang') {
 1259: 	$lang=&mt('htmlarea_lang');
 1260:     }
 1261:     return $lang;
 1262: }
 1263: 
 1264: # ----------------------------------------- Script to activate only some fields
 1265: 
 1266: sub htmlareaselectactive {
 1267:     my ($args) = @_; 
 1268:     unless (&htmlareabrowser()) { return ''; }
 1269:     my $output='<script type="text/javascript" defer="defer">'."\n"
 1270:               .'// <![CDATA['."\n";
 1271:     my $lang = &htmlarea_lang();
 1272:     my $fullpage = 'false';
 1273:     my ($dragmath_prefix,$dragmath_helpicon,$dragmath_whitespace);
 1274:     if (ref($args) eq 'HASH') {
 1275:         if (exists($args->{'lang'})) {
 1276:             if ($args->{'lang'} ne '') {
 1277:                 $lang = $args->{'lang'};
 1278:             }
 1279:         }
 1280:         if (exists($args->{'fullpage'})) { 
 1281:             if ($args->{'fullpage'} eq 'true') {
 1282:                 $fullpage = $args->{'fullpage'};
 1283:             }
 1284:         }
 1285:         if (exists($args->{'dragmath'})) {
 1286:             if ($args->{'dragmath'} ne '') {
 1287:                 $dragmath_prefix = $args->{'dragmath'};
 1288:                 $dragmath_helpicon=&Apache::loncommon::lonhttpdurl("/adm/help/help.png");
 1289:                 $dragmath_whitespace=&Apache::loncommon::lonhttpdurl("/adm/lonIcons/transparent1x1.gif");
 1290:             }
 1291:         }
 1292:     }
 1293:     $output.='
 1294:     
 1295:     function containsBlockHtml(id) {
 1296: 		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);
 1297:     	return (re >= 0);
 1298:     }
 1299:     
 1300:     function startRichEditor(id) {
 1301:     	CKEDITOR.replace(id, 
 1302:     		{
 1303:     			customConfig: "/ckeditor/loncapaconfig.js",
 1304:                         language : "'.$lang.'",
 1305:                         fullPage : '.$fullpage.',
 1306:     		}
 1307:     	);
 1308:     }
 1309:     
 1310:     function destroyRichEditor(id) {
 1311:     	CKEDITOR.instances[id].destroy();
 1312:     }
 1313:     
 1314:     function editorHandler(event) {
 1315:     	var rawid = $(this).attr("id");
 1316:     	var id = new RegExp("LC_rt_(.*)").exec(rawid)[1];
 1317:     	event.preventDefault();
 1318:     	var rt_enabled  = $(this).hasClass("LC_enable_rt");
 1319:         if (rt_enabled) {
 1320:     		startRichEditor(id);
 1321: 			$("#LC_rt_"+id).html("<b>&laquo; Plain text</b>");
 1322: 			$("#LC_rt_"+id).attr("title", "Disable rich text formatting and edit in plain text");
 1323: 			$("#LC_rt_"+id).addClass("LC_disable_rt");
 1324: 			$("#LC_rt_"+id).removeClass("LC_enable_rt");
 1325:     	} else {
 1326: 			destroyRichEditor(id);
 1327: 			$("#LC_rt_"+id).html("<b>Rich formatting &raquo;</b>");
 1328: 			$("#LC_rt_"+id).attr("title", "Enable rich text formatting (bold, italic, etc.)");
 1329: 			$("#LC_rt_"+id).addClass("LC_enable_rt");
 1330: 			$("#LC_rt_"+id).removeClass("LC_disable_rt");
 1331: 	}';
 1332:     if ($dragmath_prefix ne '') {
 1333:         $output .= "\n                 var visible = '';
 1334:                                        if (rt_enabled) {
 1335:                                            visible = 'none';
 1336:                                        }
 1337:                                        editmath_visibility(id,visible);\n";
 1338:     }
 1339:     $output .= '
 1340:     }
 1341:     $(document).ready(function(){
 1342: 		$(".LC_richAlwaysOn").each(function() {
 1343: 			startRichEditor($(this).attr("id"));
 1344: 		});
 1345: 		$(".LC_richDetectHtml").each(function() {
 1346: 			var id = $(this).attr("id");
 1347:                         var rt_enabled = containsBlockHtml(id);
 1348: 			if(rt_enabled) {
 1349: 				$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Disable rich text formatting and edit in plain text\" class=\"LC_disable_rt\"><b>&laquo; Plain text</b></a></div>");				
 1350: 				startRichEditor(id);
 1351: 				$("#LC_rt_"+id).click(editorHandler);
 1352: 			}
 1353: 			else {
 1354: 				$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Enable rich text formatting (bold, italic, etc.)\" class=\"LC_enable_rt\"><b>Rich formatting &raquo;</b></a></div>");
 1355: 				$("#LC_rt_"+id).click(editorHandler);
 1356: 			}';
 1357:     if ($dragmath_prefix ne '') {
 1358:         $output .= "\n                 var visible = '';
 1359:                                        if (rt_enabled) {
 1360:                                            visible = 'none';
 1361:                                        }
 1362:                                        editmath_visibility(id,visible);\n";
 1363:     }
 1364:     $output .= '
 1365: 		});
 1366: 		$(".LC_richDefaultOn").each(function() {
 1367: 			var id = $(this).attr("id");
 1368: 			$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Disable rich text formatting and edit in plain text\" class=\"LC_disable_rt\"><b>&laquo; Plain text</b></a></div>");				
 1369: 			startRichEditor(id);
 1370: 			$("#LC_rt_"+id).click(editorHandler);
 1371: 		});
 1372: 		$(".LC_richDefaultOff").each(function() {
 1373: 			var id = $(this).attr("id");
 1374: 			$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Enable rich text formatting (bold, italic, etc.)\" class=\"LC_enable_rt\"><b>Rich formatting &raquo;</b></a></div>");
 1375: 			$("#LC_rt_"+id).click(editorHandler);
 1376: 		});
 1377: 	});
 1378: ';
 1379:     if ($dragmath_prefix ne '') {
 1380:         $output .= '
 1381: 
 1382:      function editmath_visibility(id,value) {
 1383: 
 1384:          if ((id == "") || (id == null)) {
 1385:              return;
 1386:          }
 1387:          var mathid = "'.$dragmath_prefix.'_"+id;
 1388:          mathele = document.getElementById(mathid);
 1389:          if (mathele == null) {
 1390:              return;
 1391:          }
 1392:          mathele.style.display = value;
 1393:          var mathhelpicon = "'.$dragmath_prefix.'helpicon'.'_"+id;
 1394:          mathhelpiconele = document.getElementById(mathhelpicon);
 1395:          if (mathhelpiconele == null) {
 1396:              return;
 1397:          }
 1398:          if (value == "none") {
 1399:              mathhelpiconele.src = "'.$dragmath_whitespace.'";
 1400:          } else {
 1401:              mathhelpiconele.src = "'.$dragmath_helpicon.'";
 1402:          }
 1403:      }
 1404: ';
 1405: 
 1406:     }
 1407:     $output.="\nwindow.status='Activated Editfields';\n"
 1408:             .'// ]]>'."\n"
 1409:             .'</script>';
 1410:     return $output;
 1411: }
 1412: 
 1413: # --------------------------------------------------------------------- Blocked
 1414: 
 1415: sub htmlareablocked {
 1416:     unless ($env{'environment.wysiwygeditor'} eq 'on') { return 1; }
 1417:     return 0;
 1418: }
 1419: 
 1420: # ---------------------------------------- Browser capable of running HTMLArea?
 1421: 
 1422: sub htmlareabrowser {
 1423:     return 1;
 1424: }
 1425: 
 1426: #
 1427: # Should the "return to content" link be shown?
 1428: #
 1429: 
 1430: sub show_return_link {
 1431: 
 1432:     unless ($env{'request.course.id'}) { return 0; }
 1433:     if ($env{'request.noversionuri'}=~m{^/priv/} ||
 1434:         $env{'request.uri'}=~m{^/~}) { return 1; }
 1435: 
 1436:     if (($env{'request.noversionuri'} =~ m{^/adm/(viewclasslist|navmaps)($|\?)})
 1437:         || ($env{'request.noversionuri'} =~ m{^/adm/.*/aboutme($|\?)})) {
 1438: 
 1439:         return if ($env{'form.register'});
 1440:     }
 1441:     return (($env{'request.noversionuri'}=~m{^/(res|public)/} &&
 1442:              $env{'request.symb'} eq '')
 1443:             ||
 1444:             ($env{'request.noversionuri'}=~ m{^/cgi-bin/printout.pl})
 1445:             ||
 1446:             (($env{'request.noversionuri'}=~/^\/adm\//) &&
 1447:              ($env{'request.noversionuri'}!~/^\/adm\/wrapper\//) &&
 1448:              ($env{'request.noversionuri'}!~
 1449:               m{^/adm/.*/(smppg|bulletinboard)($|\?)})
 1450:            ));
 1451: }
 1452: 
 1453: 
 1454: ############################################################
 1455: ############################################################
 1456: 
 1457: =pod
 1458: 
 1459: =item breadcrumbs
 1460: 
 1461: Compiles the previously registered breadcrumbs into an series of links.
 1462: Additionally supports a 'component', which will be displayed on the
 1463: right side of the breadcrumbs enclosing div (without a link).
 1464: A link to help for the component will be included if one is specified.
 1465: 
 1466: All inputs can be undef without problems.
 1467: 
 1468: Inputs: $component (the text on the right side of the breadcrumbs trail),
 1469:         $component_help
 1470:         $menulink (boolean, controls whether to include a link to /adm/menu)
 1471:         $helplink (if 'nohelp' don't include the orange help link)
 1472:         $css_class (optional name for the class to apply to the table for CSS)
 1473:         $no_mt (optional flag, 1 if &mt() is _not_ to be applied to $component
 1474:            when including the text on the right.
 1475: Returns a string containing breadcrumbs for the current page.
 1476: 
 1477: =item clear_breadcrumbs
 1478: 
 1479: Clears the previously stored breadcrumbs.
 1480: 
 1481: =item add_breadcrumb
 1482: 
 1483: Pushes a breadcrumb on the stack of crumbs.
 1484: 
 1485: input: $breadcrumb, a hash reference.  The keys 'href','title', and 'text'
 1486: are required.  If present the keys 'faq' and 'bug' will be used to provide
 1487: links to the FAQ and bug sites. If the key 'no_mt' is present the 'title' 
 1488: and 'text' values won't be sent through &mt()
 1489: 
 1490: returns: nothing    
 1491: 
 1492: =cut
 1493: 
 1494: ############################################################
 1495: ############################################################
 1496: {
 1497:     my @Crumbs;
 1498:     my %tools = ();
 1499:     
 1500:     sub breadcrumbs {
 1501:         my ($component,$component_help,$menulink,$helplink,$css_class,$no_mt, $CourseBreadcrumbs) = @_;
 1502:         #
 1503:         $css_class ||= 'LC_breadcrumbs';
 1504: 
 1505:         # Make the faq and bug data cascade
 1506:         my $faq  = '';
 1507:         my $bug  = '';
 1508:         my $help = '';
 1509:         # Crumb Symbol
 1510:         my $crumbsymbol = '&raquo;';
 1511:         # The last breadcrumb does not have a link, so handle it separately.
 1512:         my $last = pop(@Crumbs);
 1513:         #
 1514:         # The first one should be the course or a menu link
 1515:         if (!defined($menulink)) { $menulink=1; }
 1516:         if ($menulink) {
 1517:             my $description = 'Menu';
 1518:             my $no_mt_descr = 0;
 1519:             if ((exists($env{'request.course.id'})) && 
 1520:                 ($env{'request.course.id'} ne '') && 
 1521:                 ($env{'course.'.$env{'request.course.id'}.'.description'} ne '')) {
 1522:                 $description = 
 1523:                     $env{'course.'.$env{'request.course.id'}.'.description'};
 1524:                 $no_mt_descr = 1;
 1525:             }
 1526:             $menulink =  {  href   =>'/adm/menu',
 1527:                             title  =>'Go to main menu',
 1528:                             target =>'_top',
 1529:                             text   =>$description,
 1530:                             no_mt  =>$no_mt_descr, };
 1531:             if($last) {
 1532:                 #$last set, so we have some crumbs
 1533:                 unshift(@Crumbs,$menulink);
 1534:             } else {
 1535:                 #only menulink crumb present
 1536:                 $last = $menulink;
 1537:             }
 1538:         }
 1539:         my $links;
 1540:         if ((&show_return_link) && (!$CourseBreadcrumbs)) {
 1541:            $links=&htmltag( 'a',"<img src='/res/adm/pages/reload.png' border='0' style='vertical-align:middle;' />",
 1542:                             { href => '/adm/flip?postdata=return:',
 1543:                               title => &mt("Back to most recent content resource") });
 1544:         }
 1545:         $links.= join "", 
 1546:              map {
 1547:                  $faq  = $_->{'faq'}  if (exists($_->{'faq'}));
 1548:                  $bug  = $_->{'bug'}  if (exists($_->{'bug'}));
 1549:                  $help = $_->{'help'} if (exists($_->{'help'}));
 1550: 
 1551:                  my $result = $_->{no_mt} ? $_->{text} : &mt($_->{text});
 1552: 
 1553:                  if ($_->{href}){
 1554:                      $result = &htmltag( 'a', $result, 
 1555:                        { href   => $_->{href},
 1556:                          title  => $_->{no_mt} ? $_->{title} : &mt($_->{title}),
 1557:                          target => $_->{target}, });
 1558:                  }
 1559: 
 1560:                  $result = &htmltag( 'li', "$result $crumbsymbol");
 1561:              } @Crumbs;
 1562: 
 1563:         #should the last Element be translated?
 1564: 
 1565:         my $lasttext = $last->{'no_mt'} ? $last->{'text'} 
 1566:                      : mt( $last->{'text'} );
 1567: 
 1568:         # last breadcrumb is the first order heading of a page
 1569:         # for course breadcrumbs it's just bold
 1570:         $links .= &htmltag( 'li', htmltag($CourseBreadcrumbs ? 'b' : 'h1',
 1571:                 $lasttext), {title => $lasttext});
 1572: 
 1573:         my $icons = '';
 1574:         $faq  = $last->{'faq'}  if (exists($last->{'faq'}));
 1575:         $bug  = $last->{'bug'}  if (exists($last->{'bug'}));
 1576:         $help = $last->{'help'} if (exists($last->{'help'}));
 1577:         $component_help=($component_help?$component_help:$help);
 1578: #        if ($faq ne '') {
 1579: #            $icons .= &Apache::loncommon::help_open_faq($faq);
 1580: #        }
 1581: #        if ($bug ne '') {
 1582: #            $icons .= &Apache::loncommon::help_open_bug($bug);
 1583: #        }
 1584:         if ($faq ne '' || $component_help ne '' || $bug ne '') {
 1585:             $icons .= &Apache::loncommon::help_open_menu($component,
 1586:                                                          $component_help,
 1587:                                                          $faq,$bug);
 1588:         }
 1589:         #
 1590: 		
 1591: 
 1592:         unless ($CourseBreadcrumbs) {
 1593:             $links = &htmltag('ol',  $links, { id => "LC_MenuBreadcrumbs"   });
 1594:         } else {
 1595:             $links = &htmltag('ul',  $links, { class => "LC_CourseBreadcrumbs" });
 1596:         }
 1597: 
 1598:         if ($component) {
 1599:             $links = &htmltag('span', 
 1600:                              ( $no_mt ? $component : mt($component) ).
 1601:                              ( $icons ? $icons : '' ),
 1602:                              { class => 'LC_breadcrumbs_component' } )
 1603:                              .$links;
 1604:         }
 1605:         
 1606:         &render_tools(\$links);
 1607:         $links = &htmltag('div', $links, 
 1608:                         { id => "LC_breadcrumbs" }) unless ($CourseBreadcrumbs) ;
 1609:         &render_advtools(\$links);
 1610: 
 1611:         # Return the @Crumbs stack to what we started with
 1612:         push(@Crumbs,$last);
 1613:         shift(@Crumbs);
 1614:         # Return the breadcrumb's line
 1615:         return "$links";
 1616:     }
 1617: 
 1618:     sub clear_breadcrumbs {
 1619:         undef(@Crumbs);
 1620:         undef(%tools);
 1621:     }
 1622: 
 1623:     sub add_breadcrumb {
 1624:         push(@Crumbs,@_);
 1625:     }
 1626:     
 1627: =item add_breadcrumb_tool($category, $html)
 1628: 
 1629: Adds $html to $category of the breadcrumb toolbar container.
 1630: 
 1631: $html is usually a link to a page that invokes a function on the currently 
 1632: displayed data (e.g. print when viewing a problem)
 1633: 
 1634: Currently there are 3 possible values for $category: 
 1635: 
 1636: =over 
 1637: 
 1638: =item navigation 
 1639: left of breadcrumbs line
 1640: 
 1641: =item tools 
 1642: right of breadcrumbs line
 1643: 
 1644: =item advtools 
 1645: advanced tools shown in a separate box below breadcrumbs line 
 1646: 
 1647: =back
 1648:  
 1649: returns: nothing
 1650: 
 1651: =cut
 1652: 
 1653:     sub add_breadcrumb_tool {
 1654:         my ($category, @html) = @_;
 1655:         return unless @html;
 1656:         if (!keys(%tools)) { 
 1657:             %tools = ( navigation => [], tools => [], advtools => []);
 1658:         }
 1659: 
 1660:         #this cleans data received from lonmenu::innerregister
 1661:         @html = grep {defined $_ && $_ ne ''} @html;
 1662:         for (@html) { 
 1663:             s/align="(right|left)"//; 
 1664: #            s/<span.*?\/span>// if $category ne 'advtools'; 
 1665:         } 
 1666: 
 1667:         push @{$tools{$category}}, @html;
 1668:     }
 1669: 
 1670: =item clear_breadcrumb_tools()
 1671: 
 1672: Clears the breadcrumb toolbar container.
 1673: 
 1674: returns: nothing
 1675: 
 1676: =cut
 1677: 
 1678:     sub clear_breadcrumb_tools {
 1679:         undef(%tools);
 1680:     }
 1681: 
 1682: =item render_tools(\$breadcrumbs)
 1683: 
 1684: Creates html for breadcrumb tools (categories navigation and tools) and inserts 
 1685: \$breadcrumbs at the correct position.
 1686: 
 1687: input: \$breadcrumbs - a reference to the string containing prepared 
 1688: breadcrumbs.
 1689: 
 1690: returns: nothing
 1691: =cut
 1692: 
 1693: #TODO might split this in separate functions for each category
 1694:     sub render_tools {
 1695:         my ($breadcrumbs) = @_;
 1696:         return unless (keys(%tools));
 1697: 
 1698:         my $navigation = list_from_array($tools{navigation}, 
 1699:                    { listattr => { class=>"LC_breadcrumb_tools_navigation" } });
 1700:         my $tools = list_from_array($tools{tools}, 
 1701:                    { listattr => { class=>"LC_breadcrumb_tools_tools" } });
 1702:         $$breadcrumbs = list_from_array([$navigation, $tools, $$breadcrumbs], 
 1703:                    { listattr => { class=>'LC_breadcrumb_tools_outerlist' } });
 1704:     }
 1705: 
 1706: =item render_advtools(\$breadcrumbs)
 1707: 
 1708: Creates html for advanced tools (category advtools) and inserts \$breadcrumbs 
 1709: at the correct position.
 1710: 
 1711: input: \$breadcrumbs - a reference to the string containing prepared 
 1712: breadcrumbs (after render_tools call).
 1713: 
 1714: returns: nothing
 1715: =cut
 1716: 
 1717:     sub render_advtools {
 1718:         my ($breadcrumbs) = @_;
 1719:         return unless     (defined $tools{'advtools'}) 
 1720:                       and (scalar(@{$tools{'advtools'}}) > 0);
 1721: 
 1722:         $$breadcrumbs .= Apache::loncommon::head_subbox(
 1723:                             funclist_from_array($tools{'advtools'}) );
 1724:     }
 1725: 
 1726: } # End of scope for @Crumbs
 1727: 
 1728: ############################################################
 1729: ############################################################
 1730: 
 1731: # Nested table routines.
 1732: #
 1733: # Routines to display form items in a multi-row table with 2 columns.
 1734: # Uses nested tables to divide form elements into segments.
 1735: # For examples of use see loncom/interface/lonnotify.pm 
 1736: #
 1737: # Can be used in following order: ...
 1738: # &start_pick_box()
 1739: # row1
 1740: # row2
 1741: # row3   ... etc.
 1742: # &submit_row()
 1743: # &end_pick_box()
 1744: #
 1745: # where row1, row 2 etc. are chosen from &role_select_row,&course_select_row,
 1746: # &status_select_row and &email_default_row
 1747: #
 1748: # Can also be used in following order:
 1749: #
 1750: # &start_pick_box()
 1751: # &row_title()
 1752: # &row_closure()
 1753: # &row_title()
 1754: # &row_closure()  ... etc.
 1755: # &submit_row()
 1756: # &end_pick_box()
 1757: #
 1758: # In general a &submit_row() call should proceed the call to &end_pick_box(),
 1759: # as this routine adds a button for form submission.
 1760: # &submit_row() does not require a &row_closure after it.
 1761: #  
 1762: # &start_pick_box() creates a bounding table with 1-pixel wide black border.
 1763: # rows should be placed between calls to &start_pick_box() and &end_pick_box.
 1764: #
 1765: # &row_title() adds a title in the left column for each segment.
 1766: # &row_closure() closes a row with a 1-pixel wide black line.
 1767: #
 1768: # &role_select_row() provides a select box from which to choose 1 or more roles 
 1769: # &course_select_row provides ways of picking groups of courses
 1770: #    radio buttons: all, by category or by picking from a course picker pop-up
 1771: #      note: by category option is only displayed if a domain has implemented 
 1772: #                selection by year, semester, department, number etc.
 1773: #
 1774: # &status_select_row() provides a select box from which to choose 1 or more
 1775: #  access types (current access, prior access, and future access)  
 1776: #
 1777: # &email_default_row() provides text boxes for default e-mail suffixes for
 1778: #  different authentication types in a domain.
 1779: #
 1780: # &row_title() and &row_closure() are called internally by the &*_select_row
 1781: # routines, but can also be called directly to start and end rows which have 
 1782: # needs that are not accommodated by the *_select_row() routines.    
 1783: 
 1784: { # Start: row_count block for pick_box
 1785: my @row_count;
 1786: 
 1787: sub start_pick_box {
 1788:     my ($css_class) = @_;
 1789:     if (defined($css_class)) {
 1790: 	$css_class = 'class="'.$css_class.'"';
 1791:     } else {
 1792: 	$css_class= 'class="LC_pick_box"';
 1793:     }
 1794:     unshift(@row_count,0);
 1795:     my $output = <<"END";
 1796:  <table $css_class>
 1797: END
 1798:     return $output;
 1799: }
 1800: 
 1801: sub end_pick_box {
 1802:     shift(@row_count);
 1803:     my $output = <<"END";
 1804:        </table>
 1805: END
 1806:     return $output;
 1807: }
 1808: 
 1809: sub row_headline {
 1810:     my $output = <<"END";
 1811:            <tr><td colspan="2">
 1812: END
 1813:     return $output;
 1814: }
 1815: 
 1816: sub row_title {
 1817:     my ($title,$css_title_class,$css_value_class, $css_value_furtherAttributes) = @_;
 1818:     $row_count[0]++;
 1819:     my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 1820:     $css_title_class ||= 'LC_pick_box_title';
 1821:     $css_title_class = 'class="'.$css_title_class.'"';
 1822: 
 1823:     $css_value_class ||= 'LC_pick_box_value';
 1824: 
 1825:     if ($title ne '') {
 1826:         $title .= ':';
 1827:     }
 1828:     my $output = <<"ENDONE";
 1829:            <tr class="LC_pick_box_row" $css_value_furtherAttributes> 
 1830:             <td $css_title_class>
 1831: 	       $title
 1832:             </td>
 1833:             <td class="$css_value_class $css_class">
 1834: ENDONE
 1835:     return $output;
 1836: }
 1837: 
 1838: sub row_closure {
 1839:     my ($no_separator) =@_;
 1840:     my $output = <<"ENDTWO";
 1841:             </td>
 1842:            </tr>
 1843: ENDTWO
 1844:     if (!$no_separator) {
 1845:         $output .= <<"ENDTWO";
 1846:            <tr>
 1847:             <td colspan="2" class="LC_pick_box_separator">
 1848:             </td>
 1849:            </tr>
 1850: ENDTWO
 1851:     }
 1852:     return $output;
 1853: }
 1854: 
 1855: } # End: row_count block for pick_box
 1856: 
 1857: sub role_select_row {
 1858:     my ($roles,$title,$css_class,$show_separate_custom,$cdom,$cnum) = @_;
 1859:     my $crstype = 'Course';
 1860:     if ($cdom ne '' && $cnum ne '') {
 1861:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 1862:     }
 1863:     my $output;
 1864:     if (defined($title)) {
 1865:         $output = &row_title($title,$css_class);
 1866:     }
 1867:     $output .= qq|
 1868:                                   <select name="roles" multiple="multiple">\n|;
 1869:     foreach my $role (@$roles) {
 1870:         my $plrole;
 1871:         if ($role eq 'ow') {
 1872:             $plrole = &mt('Course Owner');
 1873:         } elsif ($role eq 'cr') {
 1874:             if ($show_separate_custom) {
 1875:                 if ($cdom ne '' && $cnum ne '') {
 1876:                     my %course_customroles = &course_custom_roles($cdom,$cnum);
 1877:                     foreach my $crrole (sort(keys(%course_customroles))) {
 1878:                         my ($plcrrole) = ($crrole =~ m|^cr/[^/]+/[^/]+/(.+)$|);
 1879:                         $output .= '  <option value="'.$crrole.'">'.$plcrrole.
 1880:                                    '</option>';
 1881:                     }
 1882:                 }
 1883:             } else {
 1884:                 $plrole = &mt('Custom Role');
 1885:             }
 1886:         } else {
 1887:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 1888:         }
 1889:         if (($role ne 'cr') || (!$show_separate_custom)) {
 1890:             $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
 1891:         }
 1892:     }
 1893:     $output .= qq|                </select>\n|;
 1894:     if (defined($title)) {
 1895:         $output .= &row_closure();
 1896:     }
 1897:     return $output;
 1898: }
 1899: 
 1900: sub course_select_row {
 1901:     my ($title,$formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 1902: 	$css_class,$crstype,$standardnames) = @_;
 1903:     my $output = &row_title($title,$css_class);
 1904:     $output .= &course_selection($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype,$standardnames);
 1905:     $output .= &row_closure();
 1906:     return $output;
 1907: }
 1908: 
 1909: sub course_selection {
 1910:     my ($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype,$standardnames) = @_;
 1911:     my $output = qq|
 1912: <script type="text/javascript">
 1913: // <![CDATA[
 1914:     function coursePick (formname) {
 1915:         for  (var i=0; i<formname.coursepick.length; i++) {
 1916:             if (formname.coursepick[i].value == 'category') {
 1917:                 courseSet('');
 1918:             }
 1919:             if (!formname.coursepick[i].checked) {
 1920:                 if (formname.coursepick[i].value == 'specific') {
 1921:                     formname.coursetotal.value = 0;
 1922:                     formname.courselist = '';
 1923:                 }
 1924:             }
 1925:         }
 1926:     }
 1927:     function setPick (formname) {
 1928:         for  (var i=0; i<formname.coursepick.length; i++) {
 1929:             if (formname.coursepick[i].value == 'category') {
 1930:                 formname.coursepick[i].checked = true;
 1931:             }
 1932:             formname.coursetotal.value = 0;
 1933:             formname.courselist = '';
 1934:         }
 1935:     }
 1936: // ]]>
 1937: </script>
 1938:     |;
 1939: 
 1940:     my ($allcrs,$pickspec);
 1941:     if ($crstype eq 'Community') {
 1942:         $allcrs = &mt('All communities');
 1943:         $pickspec = &mt('Pick specific communities:');
 1944:     } else {
 1945:         $allcrs = &mt('All courses');
 1946:         $pickspec = &mt('Pick specific course(s):');
 1947:     }
 1948: 
 1949:     my $courseform='<b>'.&Apache::loncommon::selectcourse_link
 1950:                      ($formname,'pickcourse','pickdomain','coursedesc','',1,$crstype).'</b>';
 1951:         $output .= '<input type="radio" name="coursepick" value="all" onclick="coursePick(this.form)" />'.$allcrs.'<br />';
 1952:     if ($totcodes > 0) {
 1953:         my $numtitles = @$codetitles;
 1954:         if ($numtitles > 0) {
 1955:             $output .= '<input type="radio" name="coursepick" value="category" onclick="coursePick(this.form);alert('."'".&mt('Choose categories, from left to right')."'".')" />'.&mt('Pick courses by category:').' <br />';
 1956:             $output .= '<table><tr><td>'.$$codetitles[0].'<br />'."\n".
 1957:                '<select name="'.$standardnames->[0].
 1958:                '" onChange="setPick(this.form);courseSet('."'$$codetitles[0]'".')">'."\n".
 1959:                ' <option value="-1" />Select'."\n";
 1960:             my @items = ();
 1961:             my @longitems = ();
 1962:             if ($$idlist{$$codetitles[0]} =~ /","/) {
 1963:                 @items = split(/","/,$$idlist{$$codetitles[0]});
 1964:             } else {
 1965:                 $items[0] = $$idlist{$$codetitles[0]};
 1966:             }
 1967:             if (defined($$idlist_titles{$$codetitles[0]})) {
 1968:                 if ($$idlist_titles{$$codetitles[0]} =~ /","/) {
 1969:                     @longitems = split(/","/,$$idlist_titles{$$codetitles[0]});
 1970:                 } else {
 1971:                     $longitems[0] = $$idlist_titles{$$codetitles[0]};
 1972:                 }
 1973:                 for (my $i=0; $i<@longitems; $i++) {
 1974:                     if ($longitems[$i] eq '') {
 1975:                         $longitems[$i] = $items[$i];
 1976:                     }
 1977:                 }
 1978:             } else {
 1979:                 @longitems = @items;
 1980:             }
 1981:             for (my $i=0; $i<@items; $i++) {
 1982:                 $output .= ' <option value="'.$items[$i].'">'.$longitems[$i].'</option>';
 1983:             }
 1984:             $output .= '</select></td>';
 1985:             for (my $i=1; $i<$numtitles; $i++) {
 1986:                 $output .= '<td>'.$$codetitles[$i].'<br />'."\n".
 1987:                           '<select name="'.$standardnames->[$i].
 1988:                           '" onChange="courseSet('."'$$codetitles[$i]'".')">'."\n".
 1989:                           '<option value="-1">&lt;-Pick '.$$codetitles[$i-1].'</option>'."\n".
 1990:                           '</select>'."\n".
 1991:                           '</td>';
 1992:             }
 1993:             $output .= '</tr></table><br />';
 1994:         }
 1995:     }
 1996:     $output .= '<input type="radio" name="coursepick" value="specific" onclick="coursePick(this.form);opencrsbrowser('."'".$formname."','dccourse','dcdomain','coursedesc','','1','$crstype'".')" />'.$pickspec.' '.$courseform.'&nbsp;&nbsp;<input type="text" value="0" size="4" name="coursetotal" /><input type="hidden" name="courselist" value="" />selected.<br />'."\n";
 1997:     return $output;
 1998: }
 1999: 
 2000: sub status_select_row {
 2001:     my ($types,$title,$css_class) = @_;
 2002:     my $output; 
 2003:     if (defined($title)) {
 2004:         $output = &row_title($title,$css_class,'LC_pick_box_select');
 2005:     }
 2006:     $output .= qq|
 2007:                                     <select name="types" multiple="multiple">\n|;
 2008:     foreach my $status_type (sort(keys(%{$types}))) {
 2009:         $output .= '  <option value="'.$status_type.'">'.$$types{$status_type}.'</option>';
 2010:     }
 2011:     $output .= qq|                   </select>\n|; 
 2012:     if (defined($title)) {
 2013:         $output .= &row_closure();
 2014:     }
 2015:     return $output;
 2016: }
 2017: 
 2018: sub email_default_row {
 2019:     my ($authtypes,$title,$descrip,$css_class) = @_;
 2020:     my $output = &row_title($title,$css_class);
 2021:     $output .= $descrip.
 2022: 	&Apache::loncommon::start_data_table().
 2023: 	&Apache::loncommon::start_data_table_header_row().
 2024: 	'<th>'.&mt('Authentication Method').'</th>'.
 2025: 	'<th align="right">'.&mt('Username -> e-mail conversion').'</th>'."\n".
 2026: 	&Apache::loncommon::end_data_table_header_row();
 2027:     my $rownum = 0;
 2028:     foreach my $auth (sort(keys(%{$authtypes}))) {
 2029:         my ($userentry,$size);
 2030:         if ($auth =~ /^krb/) {
 2031:             $userentry = '';
 2032:             $size = 25;
 2033:         } else {
 2034:             $userentry = 'username@';
 2035:             $size = 15;
 2036:         }
 2037:         $output .= &Apache::loncommon::start_data_table_row().
 2038: 	    '<td>  '.$$authtypes{$auth}.'</td>'.
 2039: 	    '<td align="right">'.$userentry.
 2040: 	    '<input type="text" name="'.$auth.'" size="'.$size.'" /></td>'.
 2041: 	    &Apache::loncommon::end_data_table_row();
 2042:     }
 2043:     $output .= &Apache::loncommon::end_data_table();
 2044:     $output .= &row_closure();
 2045:     return $output;
 2046: }
 2047: 
 2048: 
 2049: sub submit_row {
 2050:     my ($title,$cmd,$submit_text,$css_class) = @_;
 2051:     my $output = &row_title($title,$css_class,'LC_pick_box_submit');
 2052:     $output .= qq|
 2053:              <br />
 2054:              <input type="hidden" name="command" value="$cmd" />
 2055:              <input type="submit" value="$submit_text"/> &nbsp;
 2056:              <br /><br />
 2057:             \n|;
 2058:     return $output;
 2059: }
 2060: 
 2061: sub course_custom_roles {
 2062:     my ($cdom,$cnum) = @_;
 2063:     my %returnhash=();
 2064:     my %coursepersonnel=&Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 2065:     foreach my $person (sort(keys(%coursepersonnel))) {
 2066:         my ($role) = ($person =~ /^([^:]+):/);
 2067:         my ($end,$start) = split(/:/,$coursepersonnel{$person});
 2068:         if ($end == -1 && $start == -1) {
 2069:             next;
 2070:         }
 2071:         if ($role =~ m|^cr/[^/]+/[^/]+/[^/]|) {
 2072:             $returnhash{$role} ++;
 2073:         }
 2074:     }
 2075:     return %returnhash;
 2076: }
 2077: 
 2078: 
 2079: sub resource_info_box {
 2080:    my ($symb,$onlyfolderflag)=@_;
 2081:    my $return='';
 2082:    if ($symb) {
 2083:        $return=&Apache::loncommon::start_data_table();
 2084:        my ($map,$id,$resource)=&Apache::lonnet::decode_symb($symb);
 2085:        my $folder=&Apache::lonnet::gettitle($map);
 2086:        $return.=&Apache::loncommon::start_data_table_row().
 2087:                     '<th>'.&mt('Folder:').'</th><td>'.$folder.'</td>'.
 2088:                     &Apache::loncommon::end_data_table_row();
 2089:        unless ($onlyfolderflag) {
 2090:           $return.=&Apache::loncommon::start_data_table_row().
 2091:                     '<th>'.&mt('Resource:').'</th><td>'.&Apache::lonnet::gettitle($symb).'</td>'.
 2092:                     &Apache::loncommon::end_data_table_row();
 2093:        }
 2094:        $return.=&Apache::loncommon::end_data_table();
 2095:     } else {
 2096:        $return='<p><span class="LC_error">'.&mt('No context provided.').'</span></p>';
 2097:     }
 2098:     return $return;
 2099: 
 2100: }
 2101: 
 2102: ##############################################
 2103: ##############################################
 2104: 
 2105: # topic_bar
 2106: #
 2107: # Generates a div containing an (optional) number with a white background followed by a 
 2108: # title with a background color defined in the corresponding CSS: LC_topic_bar
 2109: # Inputs:
 2110: # 1. number to display.
 2111: #    If input for number is empty only the title will be displayed. 
 2112: # 2. title text to display.
 2113: # Outputs - a scalar containing html mark-up for the div.
 2114: 
 2115: sub topic_bar {
 2116:     my ($num,$title) = @_;
 2117:     my $number = '';
 2118:     if ($num ne '') {
 2119:         $number = '<span>'.$num.'</span>';
 2120:     }
 2121:     return '<div class="LC_topic_bar">'.$number.$title.'</div>';
 2122: }
 2123: 
 2124: ##############################################
 2125: ##############################################
 2126: # echo_form_input
 2127: #
 2128: # Generates html markup to add form elements from the referrer page
 2129: # as hidden form elements (values encoded) in the new page.
 2130: #
 2131: # Intended to support two types of use 
 2132: # (a) to allow backing up to earlier pages in a multi-page 
 2133: # form submission process using a breadcrumb trail.
 2134: #
 2135: # (b) to allow the current page to be reloaded with form elements
 2136: # set on previous page to remain unchanged.  An example would
 2137: # be where the a page containing a dynamically-built table of data is 
 2138: # is to be redisplayed, with only the sort order of the data changed. 
 2139: #  
 2140: # Inputs:
 2141: # 1. Reference to array of form elements in the submitted form on 
 2142: # the referrer page which are to be excluded from the echoed elements.
 2143: #
 2144: # 2. Reference to array of regular expressions, which if matched in the  
 2145: # name of the form element n the referrer page will be omitted from echo. 
 2146: #
 2147: # Outputs: A scalar containing the html markup for the echoed form
 2148: # elements (all as hidden elements, with values encoded). 
 2149: 
 2150: 
 2151: sub echo_form_input {
 2152:     my ($excluded,$regexps) = @_;
 2153:     my $output = '';
 2154:     foreach my $key (keys(%env)) {
 2155:         if ($key =~ /^form\.(.+)$/) {
 2156:             my $name = $1;
 2157:             my $match = 0;
 2158:             if (ref($excluded) eq 'ARRAY') {    
 2159:                 next if (grep(/^\Q$name\E$/,@{$excluded}));
 2160:             }
 2161:             if (ref($regexps) eq 'ARRAY') {
 2162:                 if (@{$regexps} > 0) {
 2163:                     foreach my $regexp (@{$regexps}) {
 2164:                         if ($name =~ /$regexp/) {
 2165:                             $match = 1;
 2166:                             last;
 2167:                         }
 2168:                     }
 2169:                 }
 2170:             }
 2171:             next if ($match);
 2172:             if (ref($env{$key}) eq 'ARRAY') {
 2173:                 foreach my $value (@{$env{$key}}) {
 2174:                     $value = &HTML::Entities::encode($value,'<>&"');
 2175:                     $output .= '<input type="hidden" name="'.$name.
 2176:                                '" value="'.$value.'" />'."\n";
 2177:                 }
 2178:             } else {
 2179:                 my $value = &HTML::Entities::encode($env{$key},'<>&"');
 2180:                 $output .= '<input type="hidden" name="'.$name.
 2181:                            '" value="'.$value.'" />'."\n";
 2182:             }
 2183:         }
 2184:     }
 2185:     return $output;
 2186: }
 2187: 
 2188: ##############################################
 2189: ##############################################
 2190: # set_form_elements
 2191: #
 2192: # Generates javascript to set form elements to values based on
 2193: # corresponding values for the same form elements when the page was
 2194: # previously submitted.
 2195: #     
 2196: # Last submission values are read from hidden form elements in referring 
 2197: # page which have the same name, i.e., generated by &echo_form_input(). 
 2198: #
 2199: # Intended to be called by onload event.
 2200: #
 2201: # Inputs:
 2202: # (a) Reference to hash of echoed form elements to be set.
 2203: #
 2204: # In the hash, keys are the form element names, and the values are the
 2205: # element type (selectbox, radio, checkbox or text -for textbox, textarea or
 2206: # hidden).
 2207: #
 2208: # (b) Optional reference to hash of stored elements to be set.
 2209: #
 2210: # If the page being displayed is a page which permits modification of
 2211: # previously stored data, e.g., the first page in a multi-page submission,
 2212: # then if stored is supplied, form elements will be set to the last stored
 2213: # values.  If user supplied values are also available for the same elements
 2214: # these will replace the stored values. 
 2215: #        
 2216: # Output:
 2217: #  
 2218: # javascript function - set_form_elements() which sets form elements,
 2219: # expects an argument: formname - the name of the form according to 
 2220: # the DOM, e.g., document.compose
 2221: 
 2222: sub set_form_elements {
 2223:     my ($elements,$stored) = @_;
 2224:     my %values;
 2225:     my $output .= 'function setFormElements(courseForm) {
 2226: ';
 2227:     if (defined($stored)) {
 2228:         foreach my $name (keys(%{$stored})) {
 2229:             if (exists($$elements{$name})) {
 2230:                 if (ref($$stored{$name}) eq 'ARRAY') {
 2231:                     $values{$name} = $$stored{$name};
 2232:                 } else {
 2233:                     @{$values{$name}} = ($$stored{$name});
 2234:                 }
 2235:             }
 2236:         }
 2237:     }
 2238: 
 2239:     foreach my $key (keys(%env)) {
 2240:         if ($key =~ /^form\.(.+)$/) {
 2241:             my $name = $1;
 2242:             if (exists($$elements{$name})) {
 2243:                 @{$values{$name}} = &Apache::loncommon::get_env_multiple($key);
 2244:             }
 2245:         }
 2246:     }
 2247: 
 2248:     foreach my $name (keys(%values)) {
 2249:         for (my $i=0; $i<@{$values{$name}}; $i++) {
 2250:             $values{$name}[$i] = &HTML::Entities::decode($values{$name}[$i],'<>&"');
 2251:             $values{$name}[$i] =~ s/([\r\n\f]+)/\\n/g;
 2252:             $values{$name}[$i] =~ s/"/\\"/g;
 2253:         }
 2254:         if (($$elements{$name} eq 'text') || ($$elements{$name} eq 'hidden')) {
 2255:             my $numvalues = @{$values{$name}};
 2256:             if ($numvalues > 1) {
 2257:                 my $valuestring = join('","',@{$values{$name}});
 2258:                 $output .= qq|
 2259:   var textvalues = new Array ("$valuestring");
 2260:   var total = courseForm.elements['$name'].length;
 2261:   if (total > $numvalues) {
 2262:       total = $numvalues;
 2263:   }    
 2264:   for (var i=0; i<total; i++) {
 2265:       courseForm.elements['$name']\[i].value = textvalues[i];
 2266:   }
 2267: |;
 2268:             } else {
 2269:                 $output .= qq|
 2270:   courseForm.elements['$name'].value = "$values{$name}[0]";
 2271: |;
 2272:             }
 2273:         } else {
 2274:             $output .=  qq|
 2275:   var elementLength = courseForm.elements['$name'].length;
 2276:   if (elementLength==undefined) {
 2277: |;
 2278:             foreach my $value (@{$values{$name}}) {
 2279:                 if ($$elements{$name} eq 'selectbox') {
 2280:                     $output .=  qq|
 2281:       if (courseForm.elements['$name'].options[0].value == "$value") {
 2282:           courseForm.elements['$name'].options[0].selected = true;
 2283:       }|;
 2284:                 } elsif (($$elements{$name} eq 'radio') ||
 2285:                          ($$elements{$name} eq 'checkbox')) {
 2286:                     $output .= qq|
 2287:       if (courseForm.elements['$name'].value == "$value") {
 2288:           courseForm.elements['$name'].checked = true;
 2289:       } else {
 2290:           courseForm.elements['$name'].checked = false;
 2291:       }|;
 2292:                 }
 2293:             }
 2294:             $output .= qq|
 2295:   }
 2296:   else {
 2297:       for (var i=0; i<courseForm.elements['$name'].length; i++) {
 2298: |;
 2299:             if ($$elements{$name} eq 'selectbox') {
 2300:                 $output .=  qq|
 2301:           courseForm.elements['$name'].options[i].selected = false;|;
 2302:             } elsif (($$elements{$name} eq 'radio') || 
 2303:                      ($$elements{$name} eq 'checkbox')) {
 2304:                 $output .= qq|
 2305:           courseForm.elements['$name']\[i].checked = false;|; 
 2306:             }
 2307:             $output .= qq|
 2308:       }
 2309:       for (var j=0; j<courseForm.elements['$name'].length; j++) {
 2310: |;
 2311:             foreach my $value (@{$values{$name}}) {
 2312:                 if ($$elements{$name} eq 'selectbox') {
 2313:                     $output .=  qq|
 2314:           if (courseForm.elements['$name'].options[j].value == "$value") {
 2315:               courseForm.elements['$name'].options[j].selected = true;
 2316:           }|;
 2317:                 } elsif (($$elements{$name} eq 'radio') ||
 2318:                          ($$elements{$name} eq 'checkbox')) { 
 2319:                       $output .= qq|
 2320:           if (courseForm.elements['$name']\[j].value == "$value") {
 2321:               courseForm.elements['$name']\[j].checked = true;
 2322:           }|;
 2323:                 }
 2324:             }
 2325:             $output .= qq|
 2326:       }
 2327:   }
 2328: |;
 2329:         }
 2330:     }
 2331:     $output .= "
 2332:     return;
 2333: }\n";
 2334:     return $output;
 2335: }
 2336: 
 2337: ##############################################
 2338: ##############################################
 2339: 
 2340: sub file_submissionchk_js {
 2341:     my ($turninpaths,$multiples) = @_;
 2342:     my $overwritewarn = &mt('File(s) you uploaded for your submission will overwrite existing file(s) submitted for this item').'\\n'.
 2343:                       &mt('Continue submission and overwrite the file(s)?');
 2344:     my $delfilewarn = &mt('You have indicated you wish to remove some files previously included in your submission.').'\\n'.
 2345:                       &mt('Continue submission with these files removed?');
 2346:     my ($turninpathtext,$multtext,$arrayindexofjs);
 2347:     if (ref($turninpaths) eq 'HASH') {
 2348:         foreach my $key (sort(keys(%{$turninpaths}))) {
 2349:             $turninpathtext .= "    if (prefix == '$key') {\n".
 2350:                                "        return '$turninpaths->{$key}';\n".
 2351:                                "    }\n";
 2352:         }
 2353:     }
 2354:     $turninpathtext .= "    return '';\n";
 2355:     if (ref($multiples) eq 'HASH') {
 2356:         foreach my $key (sort(keys(%{$multiples}))) {
 2357:             $multtext .= "    if (prefix == '$key') {\n".
 2358:                          "        return '$multiples->{$key}';\n".
 2359:                          "    }\n";
 2360:         }
 2361:     }
 2362:     $multtext .= "    return '';\n";
 2363: 
 2364:     $arrayindexofjs = &Apache::loncommon::javascript_array_indexof();
 2365:     return <<"ENDSCRIPT";
 2366: <script type="text/javascript">
 2367: // <![CDATA[
 2368: 
 2369: function file_submission_check(formname,path,multiresp) {
 2370:     var elemnum = formname.elements.length;
 2371:     if (elemnum == 0) {
 2372:         return true;
 2373:     }
 2374:     var alloverwrites = [];
 2375:     var alldelconfirm = [];
 2376:     var result = [];
 2377:     var submitter;
 2378:     var subprefix;
 2379:     var allsub = getIndexByName(formname,'all_submit');
 2380:     if (allsub == -1) {
 2381:         var idx = getIndexByName(formname,'submitted');
 2382:         if (idx != -1) {
 2383:             var subval = String(formname.elements[idx].value);
 2384:             submitter = subval.replace(/^part_/,'');
 2385:             result = overwritten_check(formname,path,multiresp,submitter);
 2386:             alloverwrites.push.apply(alloverwrites,result['overwrite']);
 2387:             alldelconfirm.push.apply(alldelconfirm,result['delete']);
 2388:         }
 2389:     } else {
 2390:         if (formname.elements[allsub].type == 'submit') {
 2391:             var partsub = /^\\d+\\.\\d+_submit_.+\$/;
 2392:             var allprefixes = [];
 2393:             var allparts = [];
 2394:             for (var i=0; i<formname.elements.length; i++) {
 2395:                 if (formname.elements[i].type == 'submit') {
 2396:                     var elemname = formname.elements[i].name;
 2397:                     var subname = String(elemname);
 2398:                     var savesub = String(elemname);
 2399:                     if (partsub.test(subname)) {
 2400:                         var prefix = subname.replace(/_submit_.+\$/,'');
 2401:                         if (allprefixes.indexOf(prefix) == -1) {
 2402:                             allprefixes.push(prefix);
 2403:                             allparts[prefix] = [];
 2404:                         }
 2405:                         var part = savesub.replace(/^\\d+\\.\\d+_submit_/,'');
 2406:                         allparts[prefix].push(part);
 2407:                     }
 2408:                 }
 2409:             }
 2410:             for (var k=0; k<allprefixes.length; k++) {
 2411:                 var idx = getIndexByName(formname,allprefixes[k]+'_submitted');
 2412:                 if (idx > -1) {
 2413:                     if (formname.elements[idx].value != 'yes') {
 2414:                         submitterval = formname.elements[idx].value;
 2415:                         submitter = submitterval.replace(/^part_/,'');
 2416:                         subprefix = allprefixes[k];
 2417:                         result = overwritten_check(formname,path,multiresp,submitter,subprefix);
 2418:                         alloverwrites.push.apply(alloverwrites,result['overwrite']);
 2419:                         alldelconfirm.push.apply(alldelconfirm,result['delete']);
 2420:                         break;
 2421:                     }
 2422:                 }
 2423:             }
 2424:             if (submitter == '' || submitter == undefined) {
 2425:                 for (var m=0; m<allprefixes.length; m++) {
 2426:                     for (var n=0; n<allparts[allprefixes[m]].length; n++) {
 2427:                         var result = overwritten_check(formname,path,multiresp,allparts[allprefixes[m]][n],allprefixes[m]);
 2428:                         alloverwrites.push.apply(alloverwrites,result['overwrite']);
 2429:                         alldelconfirm.push.apply(alldelconfirm,result['delete']);
 2430:                     }
 2431:                 }
 2432:             }
 2433:         }
 2434:     }
 2435:     if (alloverwrites.length > 0) {
 2436:         if (!confirm("$overwritewarn")) {
 2437:             for (var n=0; n<alloverwrites.length; n++) {
 2438:                 formname.elements[alloverwrites[n]].value = "";
 2439:             }
 2440:             return false;
 2441:         }
 2442:     }
 2443:     if (alldelconfirm.length > 0) {
 2444:         if (!confirm("$delfilewarn")) {
 2445:             for (var p=0; p<alldelconfirm.length; p++) {
 2446:                 formname.elements[alldelconfirm[p]].checked = false;
 2447:             }
 2448:             return false;
 2449:         }
 2450:     }
 2451:     return true;
 2452: }
 2453: 
 2454: function getIndexByName(formname,item) {
 2455:     for (var i=0;i<formname.elements.length;i++) {
 2456:         if (formname.elements[i].name == item) {
 2457:             return i;
 2458:         }
 2459:     }
 2460:     return -1;
 2461: }
 2462: 
 2463: function overwritten_check(formname,path,multiresp,part,prefix) {
 2464:     var result = [];
 2465:     result['overwrite'] = [];
 2466:     result['delete'] = [];
 2467:     var elemnum = formname.elements.length;
 2468:     if (elemnum == 0) {
 2469:         return result;
 2470:     }
 2471:     var uploadstr;
 2472:     var deletestr;
 2473:     if ((prefix != undefined) && (prefix != '')) {
 2474:         var prepend = prefix+'_';
 2475:         uploadstr = new RegExp("^"+prepend+"HWFILE"+part+".+\$");
 2476:         deletestr = new RegExp("^"+prepend+"HWFILE"+part+".+_\\\\d+_delete\$");
 2477:         multiresp = check_for_multiples(prepend);
 2478:         path = check_for_turninpath(prepend);
 2479:     } else {
 2480:         uploadstr = new RegExp("^HWFILE"+part+".+\$");
 2481:         deletestr = new RegExp("^HWFILE"+part+".+_\\\\d+_delete\$");
 2482:     }
 2483:     var alluploads = [];
 2484:     var allchecked = [];
 2485:     var allskipdel = [];
 2486:     var fnametrim = /[^\\/\\\\]+\$/;
 2487:     for (var i=0; i<formname.elements.length; i++) {
 2488:         var id = formname.elements[i].id;
 2489:         if (id != '') {
 2490:             if (uploadstr.test(id)) {
 2491:                 if (formname.elements[i].type == 'file') {
 2492:                     alluploads.push(id);
 2493:                 } else {
 2494:                     if (deletestr.test(id)) {
 2495:                         if (formname.elements[i].type == 'checkbox') {
 2496:                             if (formname.elements[i].checked) {
 2497:                                 allchecked.push(id);
 2498:                             }
 2499:                         }
 2500:                     }
 2501:                 }
 2502:             }
 2503:         }
 2504:     }
 2505:     for (var j=0; j<alluploads.length; j++) {
 2506:         var delstr = new RegExp("^"+alluploads[j]+"_\\\\d+_delete\$");
 2507:         var delboxes = [];
 2508:         for (var k=0; k<formname.elements.length; k++) {
 2509:             var id = formname.elements[k].id;
 2510:             if ((id != '') && (id != undefined)) {
 2511:                 if (delstr.test(id)) {
 2512:                     if (formname.elements[k].type == 'checkbox') {
 2513:                         delboxes.push(id);
 2514:                     }
 2515:                 }
 2516:             }
 2517:         }
 2518:         if (delboxes.length > 0) {
 2519:             if ((formname.elements[alluploads[j]].value != undefined) &&
 2520:                 (formname.elements[alluploads[j]].value != '')) {
 2521:                 var filepath = formname.elements[alluploads[j]].value;
 2522:                 var newfilename = fnametrim.exec(filepath);
 2523:                 if (newfilename != null) {
 2524:                     var filename = String(newfilename);
 2525:                     var nospaces = filename.replace(/\\s+/g,'_');
 2526:                     var nospecials = nospaces.replace(/[^\\/\\w\\.\\-]/g,'');
 2527:                     var cleanfilename = nospecials.replace(/\\.(\\d+\\.)/g,"_\$1");
 2528:                     if (cleanfilename != '') {
 2529:                         var fullpath = path+"/"+cleanfilename;
 2530:                         if (multiresp == 1) {
 2531:                             var partid = String(alluploads[i]);
 2532:                             var subdir = partid.replace(/^\\d*.?\\d*_?HWFILE/,'');
 2533:                             if (subdir != "" && subdir != undefined) {
 2534:                                 fullpath = path+"/"+subdir+"/"+cleanfilename;
 2535:                             }
 2536:                         }
 2537:                         for (var m=0; m<delboxes.length; m++) {
 2538:                             if (fullpath == formname.elements[delboxes[m]].value) {
 2539:                                 if (formname.elements[delboxes[m]].checked) {
 2540:                                     allskipdel.push(delboxes[m]);
 2541:                                 } else {
 2542:                                     result['overwrite'].push(alluploads[j]);
 2543:                                 }
 2544:                                 break;
 2545:                             }
 2546:                         }
 2547:                     }
 2548:                 }
 2549:             }
 2550:         }
 2551:     }
 2552:     if (allchecked.length > 0) {
 2553:         if (allskipdel.length > 0) {
 2554:             for (var n=0; n<allchecked.length; n++) {
 2555:                 if (allskipdel.indexOf(allchecked[n]) == -1) {
 2556:                     result['delete'].push(allchecked[n]);
 2557:                 }
 2558:             }
 2559:         } else {
 2560:             result['delete'].push.apply(result['delete'],allchecked);
 2561:         }
 2562:     }
 2563:     return result;
 2564: }
 2565: 
 2566: function check_for_multiples(prefix) {
 2567: $multtext
 2568: }
 2569: 
 2570: function check_for_turninpath(prefix) {
 2571: $turninpathtext
 2572: }
 2573: 
 2574: // ]]>
 2575: </script>
 2576: 
 2577: $arrayindexofjs
 2578: 
 2579: ENDSCRIPT
 2580: }
 2581: 
 2582: ##############################################
 2583: ##############################################
 2584: 
 2585: # javascript_valid_email
 2586: #
 2587: # Generates javascript to validate an e-mail address.
 2588: # Returns a javascript function which accetps a form field as argumnent, and
 2589: # returns false if field.value does not satisfy two regular expression matches
 2590: # for a valid e-mail address.  Backwards compatible with old browsers without
 2591: # support for javascript RegExp (just checks for @ in field.value in this case). 
 2592: 
 2593: sub javascript_valid_email {
 2594:     my $scripttag .= <<'END';
 2595: function validmail(field) {
 2596:     var str = field.value;
 2597:     if (window.RegExp) {
 2598:         var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
 2599:         var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$"; //"
 2600:         var reg1 = new RegExp(reg1str);
 2601:         var reg2 = new RegExp(reg2str);
 2602:         if (!reg1.test(str) && reg2.test(str)) {
 2603:             return true;
 2604:         }
 2605:         return false;
 2606:     }
 2607:     else
 2608:     {
 2609:         if(str.indexOf("@") >= 0) {
 2610:             return true;
 2611:         }
 2612:         return false;
 2613:     }
 2614: }
 2615: END
 2616:     return $scripttag;
 2617: }
 2618: 
 2619: 
 2620: # USAGE: htmltag(element, content, {attribute => value,...});
 2621: #
 2622: # EXAMPLES: 
 2623: #  - htmltag('a', 'this is an anchor', {href  => 'www.example.com', 
 2624: #                                       title => 'this is a title'})
 2625: #
 2626: #  - You might want to set up needed tags like: 
 2627: #
 2628: #     my $h3  = sub { return htmltag( "h3",  @_ ) };
 2629: #
 2630: #    ... and use them: $h3->("This is a headline")
 2631: #
 2632: #  - To set up a couple of tags, see sub inittags
 2633: #
 2634: # NOTES:
 2635: # - Empty elements, such as <br/> are correctly terminated, 
 2636: #   i.e. htmltag('br') returns <br/> 
 2637: # - Empty attributes (title="") are filtered out.
 2638: # - The function will not check for deprecated attributes.
 2639: #
 2640: # OUTPUT: content enclosed in xhtml conform tags
 2641: sub htmltag{
 2642:     return
 2643:         qq|<$_[0]|
 2644:         . join( '', map { qq| $_="${$_[2]}{$_}"| if ${$_[2]}{$_} } keys %{ $_[2] } )
 2645:         . ($_[1] ? qq|>$_[1]</$_[0]>| : qq|/>|). "\n";
 2646: };
 2647: 
 2648: 
 2649: # USAGE: inittags(@tags);
 2650: #
 2651: # EXAMPLES:
 2652: #  - my ($h1, $h2, $h3) = inittags( qw( h1 h2 h3 ) )
 2653: #    $h1->("This is a headline") #Returns: <h1>This is a headline</h1>
 2654: #
 2655: # NOTES: See sub htmltag for further information.
 2656: #
 2657: # OUTPUT: List of subroutines. 
 2658: sub inittags {
 2659:     my @tags = @_;
 2660:     return map { my $tag = $_;
 2661:                  sub { return htmltag( $tag, @_ ) }
 2662:                } @tags;
 2663: }
 2664: 
 2665: 
 2666: # USAGE: scripttag(scriptcode, [start|end|both]);
 2667: #
 2668: # EXAMPLES: 
 2669: #  - scripttag("alert('Hello World!')", 'both') 
 2670: #    returns:
 2671: #    <script type="text/javascript">
 2672: #    // BEGIN LON-CAPA Internal
 2673: #    alert(Hello World!')
 2674: #    // END LON-CAPA Internal
 2675: #    </script>
 2676: #
 2677: # NOTES:
 2678: # - works currently only for javascripts
 2679: #
 2680: # OUTPUT: 
 2681: # Scriptcode properly enclosed in <script> and CDATA tags (and LC
 2682: # Internal markers if 2nd argument is given)
 2683: sub scripttag {
 2684:     my ( $content, $marker ) = @_;
 2685:     return unless defined $content;
 2686: 
 2687:     my $begin = "\n// BEGIN LON-CAPA Internal\n";
 2688:     my $end   = "\n// END LON-CAPA Internal\n";
 2689: 
 2690:     if ($marker) {
 2691:         $content  = $begin . $content if $marker eq 'start' or $marker eq 'both';
 2692:         $content .= $end              if $marker eq 'end'   or $marker eq 'both';
 2693:     }
 2694: 
 2695:     $content = "\n// <![CDATA[\n$content\n// ]]>\n";
 2696: 
 2697:     return htmltag('script', $content, {type => 'text/javascript'});
 2698: };
 2699: 
 2700: 
 2701: =item list_from_array( \@array, { listattr =>{}, itemattr =>{} } )
 2702: 
 2703: Constructs a XHTML list from \@array.
 2704: 
 2705: input: 
 2706: 
 2707: =over
 2708: 
 2709: =item \@array 
 2710: 
 2711: A reference to the array containing text that will be wrapped in <li></li> tags.
 2712: 
 2713: =item { listattr => {}, itemattr =>{} } 
 2714: 
 2715: Attributes for <ul> and <li> passed in as hash references. 
 2716: See htmltag() for more details.
 2717: 
 2718: =back
 2719:  
 2720: returns: XHTML list as String. 
 2721: 
 2722: =cut   
 2723: 
 2724: # \@items, {listattr => { class => 'abc', id => 'xyx' }, itemattr => {class => 'abc', id => 'xyx'}}
 2725: sub list_from_array {
 2726:     my ($items, $args) = @_;
 2727:     return unless (ref($items) eq 'ARRAY');
 2728:     return unless scalar @$items;
 2729:     my ($ul, $li) = inittags( qw(ul li) );
 2730:     my $listitems = join '', map { $li->($_, $args->{itemattr}) } @$items;
 2731:     return $ul->( $listitems, $args->{listattr} );
 2732: }
 2733: 
 2734: 
 2735: ##############################################
 2736: ##############################################
 2737: 
 2738: # generate_menu
 2739: #
 2740: # Generates html markup for a menu. 
 2741: #
 2742: # Inputs:
 2743: # An array of following structure:
 2744: #   ({	categorytitle => 'Categorytitle',
 2745: #	items => [
 2746: #		    {	
 2747: #           linktext    =>	'Text to be displayed',
 2748: #			url	        =>	'URL the link is pointing to, i.e. /adm/site?action=dosomething',
 2749: #			permission  =>	'Contains permissions as returned from lonnet::allowed(),
 2750: #					         must evaluate to true in order to activate the link',
 2751: #			icon        =>  'icon filename',
 2752: #			alttext	    =>	'alt text for the icon',
 2753: #			help	    =>	'Name of the corresponding helpfile',
 2754: #			linktitle   =>	'Description of the link (used for title tag)'
 2755: #		    },
 2756: #		    ...
 2757: #		]
 2758: #   }, 
 2759: #   ...
 2760: #   )
 2761: #
 2762: # Outputs: A scalar containing the html markup for the menu.
 2763: 
 2764: sub generate_menu {
 2765:     my @menu = @_;
 2766:     # subs for specific html elements
 2767:     my ($h3, $div, $ul, $li, $a, $img) = inittags( qw(h3 div ul li a img) ); 
 2768:     
 2769:     my @categories; # each element represents the entire markup for a category
 2770:    
 2771:     foreach my $category (@menu) {
 2772:         my @links;  # contains the links for the current $category
 2773:         foreach my $link (@{$$category{items}}) {
 2774:             next unless $$link{permission};
 2775:             
 2776:             # create the markup for the current $link and push it into @links.
 2777:             # each entry consists of an image and a text optionally followed 
 2778:             # by a help link.
 2779:             my $src;
 2780:             if ($$link{icon} ne '') {
 2781:                 $src = '/res/adm/pages/'.$$link{icon};
 2782:             }
 2783:             push(@links,$li->(
 2784:                         $a->(
 2785:                             $img->("", {
 2786:                                 class => "LC_noBorder LC_middle",
 2787:                                 src   => $src,
 2788:                                 alt   => mt(defined($$link{alttext}) ?
 2789:                                 $$link{alttext} : $$link{linktext})
 2790:                             }), {
 2791:                             href  => $$link{url},
 2792:                             title => mt($$link{linktitle})
 2793:                             }).
 2794:                         $a->(mt($$link{linktext}), {
 2795:                             href  => $$link{url},
 2796:                             title => mt($$link{linktitle}),
 2797:                             class => "LC_menubuttons_link"
 2798:                             }).
 2799:                          (defined($$link{help}) ? 
 2800:                          Apache::loncommon::help_open_topic($$link{help}) : ''),
 2801:                          {class => "LC_menubuttons_inline_text"}));
 2802:         }
 2803: 
 2804:         # wrap categorytitle in <h3>, concatenate with 
 2805:         # joined and in <ul> tags wrapped @links
 2806:         # and wrap everything in an enclosing <div> and push it into
 2807:         # @categories
 2808:         # such that each element looks like:
 2809:         # <div><h3>title</h3><ul><li>...</li>...</ul></div>
 2810:         # the category won't be added if there aren't any links
 2811:         push(@categories, 
 2812:             $div->($h3->(mt($$category{categorytitle}), {class=>"LC_hcell"}).
 2813:             $ul->(join('' ,@links),  {class =>"LC_ListStyleNormal" }),
 2814:             {class=>"LC_Box LC_400Box"})) if scalar(@links);
 2815:     }
 2816: 
 2817:     # wrap the joined @categories in another <div> (column layout)
 2818:     return $div->(join('', @categories), {class => "LC_columnSection"});
 2819: }
 2820: 
 2821: ##############################################
 2822: ##############################################
 2823: 
 2824: =pod
 2825: 
 2826: =item &start_funclist
 2827: 
 2828: Start list of available functions
 2829: 
 2830: Typically used to offer a simple list of available functions
 2831: at top or bottom of page.
 2832: All available functions/actions for the current page
 2833: should be included in this list.
 2834: 
 2835: If the optional headline text is not provided, a default text will be used.
 2836: 
 2837: 
 2838: Related routines:
 2839: =over 4
 2840: add_item_funclist
 2841: end_funclist
 2842: =back
 2843: 
 2844: 
 2845: Inputs: (optional) headline text
 2846: 
 2847: Returns: HTML code with function list start
 2848: 
 2849: =cut
 2850: 
 2851: ##############################################
 2852: ##############################################
 2853: 
 2854: sub start_funclist {
 2855:     my($legendtext)=@_;
 2856:     $legendtext=&mt('Functions') if !$legendtext;
 2857:     return '<ul class="LC_funclist"><li style="font-weight:bold; margin-left:0.8em;">'.$legendtext.'</li>'."\n";
 2858: }
 2859: 
 2860: 
 2861: ##############################################
 2862: ##############################################
 2863: 
 2864: =pod
 2865: 
 2866: =item &add_item_funclist
 2867: 
 2868: Adds an item to the list of available functions
 2869: 
 2870: Related routines:
 2871: =over 4
 2872: start_funclist
 2873: end_funclist
 2874: =back
 2875: 
 2876: Inputs: content item with text and link to function
 2877: 
 2878: Returns: HTML code with list item for funclist
 2879: 
 2880: =cut
 2881: 
 2882: ##############################################
 2883: ##############################################
 2884: 
 2885: sub add_item_funclist {
 2886:     my($content) = @_;
 2887:     return '<li>'.$content.'</li>'."\n";
 2888: }
 2889: 
 2890: =pod
 2891: 
 2892: =item &end_funclist
 2893: 
 2894: End list of available functions
 2895: 
 2896: Related routines:
 2897: =over 4
 2898: start_funclist
 2899: add_item_funclist
 2900: =back
 2901: 
 2902: Inputs: ./.
 2903: 
 2904: Returns: HTML code with function list end
 2905: =cut
 2906: 
 2907: sub end_funclist {
 2908:     return "</ul>\n";
 2909: }
 2910: 
 2911: =pod
 2912: 
 2913: =item funclist_from_array( \@array, {legend => 'text for legend'} )
 2914: 
 2915: Constructs a XHTML list from \@array with the first item being visually
 2916: highlighted and set to the value of legend or 'Functions' if legend is
 2917: empty. 
 2918: 
 2919: =over
 2920: 
 2921: =item \@array
 2922: 
 2923: A reference to the array containing text that will be wrapped in <li></li> tags.
 2924: 
 2925: =item { legend => 'text' }
 2926: 
 2927: A string that's used as visually highlighted first item. 'Functions' is used if
 2928: it's value evaluates to false.
 2929: 
 2930: =back
 2931:  
 2932: returns: XHTML list as string. 
 2933: 
 2934: =back
 2935: 
 2936: =cut  
 2937: 
 2938: sub funclist_from_array {
 2939:     my ($items, $args) = @_;
 2940:     return unless(ref($items) eq 'ARRAY');
 2941:     $args->{legend} ||= mt('Functions');
 2942:     return list_from_array( [$args->{legend}, @$items], 
 2943:                { listattr => {class => 'LC_funclist'} });
 2944: }   
 2945: 
 2946: 1;
 2947: 
 2948: __END__

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