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

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

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