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

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

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