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

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

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