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

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

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