File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.285.2.2: download - view: text, annotated - select for diffs
Tue Oct 11 13:12:23 2011 UTC (12 years, 8 months ago) by raeburn
Branches: version_2_10_X
Diff to branchpoint 1.285: preferred, unified
- Backport 1.286 (part).

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

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