File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.287: download - view: text, annotated - select for diffs
Sun Jan 16 22:45:05 2011 UTC (13 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Move "return" button to where the other navigation arrows are (also, it's
not a function that is available in courses at all times, so it should
not have been in the line where it was)

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

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