Annotation of loncom/interface/lonhtmlcommon.pm, revision 1.345

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

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