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

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

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